142: MongoDB Security — Authentication, RBAC, TLS, Network Controls, Encryption, Auditing, and Queryable Encryption
Learning objectives
You will learn to:
- secure MongoDB network access;
- understand MongoDB authentication;
- use role-based access control;
- apply least privilege;
- use TLS;
- understand encryption at rest;
- understand client-side field-level encryption;
- understand Queryable Encryption conceptually;
- understand X.509/Kerberos/LDAP enterprise options at a high level;
- use auditing;
- protect connection strings and credentials;
- secure Atlas deployments;
- avoid application-level operator injection and tenant leaks.
Security starts with network exposure
Never run production MongoDB open to the public internet with weak/no authentication.
Controls:
private network / firewall Atlas network access / private endpoints TLS authentication RBAC application authorization
Database auth does not replace network controls.
Authentication
MongoDB authenticates users/services through configured mechanisms.
Common application deployments use username/password SCRAM or cloud/managed identity integrations where supported.
Enterprise environments may use:
- X.509;
- Kerberos;
- LDAP proxy;
- cloud IAM integrations.
Use the mechanism supported by your deployment/security team.
SCRAM
Username/password authentication uses SCRAM mechanisms.
Connection:
mongodb+srv://appUser:...@cluster/...
Never embed literal password in source.
Use secret manager/env injection.
URL-encode special credentials when building URI—but prefer driver URI/config facilities.
Separate users by service
Do not share:
root/admin credential
across applications.
Create dedicated app user.
Permissions only required database/actions.
If service only CRUD tasks:
do not grant clusterAdmin
RBAC
MongoDB built-in roles include database/cluster administrative and read/write roles.
Custom roles can grant specific privileges.
Principle:
least privilege
Application credential should not be able to:
- create admin users;
- drop unrelated databases;
- change cluster config;
- read unrelated tenant database if avoidable.
App authorization still required
MongoDB user:
readWrite on app database
does not know which logged-in tenant/user can access which task.
Application must enforce:
tenantId ownership permissions status
DB RBAC is service-level boundary.
App ABAC/RBAC is user-level boundary.
Atlas database users
Atlas separates Atlas project/cloud user concepts from database users.
Understand which credential controls:
- Atlas administration;
- database access.
Do not grant developers production DB superuser because they need Atlas UI login.
Network allowlist
Atlas can restrict IPs.
Production better uses:
- private endpoint/peering;
- stable egress;
- narrow allowlist.
0.0.0.0/0 is broad internet exposure; avoid unless justified with strong controls and temporary policy.
TLS
Encrypt network traffic.
MongoDB clients/servers can verify certificates.
Do not disable certificate verification:
tlsAllowInvalidCertificates=true
in production to “fix” TLS.
Fix CA/hostname.
Certificate rotation
Plan:
- expiration monitoring;
- CA rotation;
- overlap;
- deployment.
A certificate expiring at midnight can cause full outage.
X.509
Client/server certificates can authenticate database users in enterprise/security environments.
Strong machine identity.
Operational complexity:
- PKI;
- issuance;
- rotation;
- DN mapping.
Kerberos
Enterprise single sign-on mechanism.
Common in corporate environments.
Do not implement unless organization identity infrastructure requires.
LDAP proxy
MongoDB Enterprise can integrate LDAP authorization/authentication workflows depending product capability.
Know roadmap topic; application developers usually consume centrally managed identity.
Encryption at rest
Atlas/cloud/disk encryption protects storage media.
It protects against lost disk/snapshot exposure according to key management.
It does not prevent an authorized database query from reading plaintext fields.
KMS
Encryption keys can be managed through cloud KMS/customer-managed keys depending deployment.
Key access policy/rotation becomes part of security.
Losing key can lose data.
Client-Side Field Level Encryption (CSFLE)
Sensitive fields encrypted by driver before sending to MongoDB.
Database can store ciphertext without plaintext access in selected models.
Architecture:
app driver → encrypt field → Mongo stores encrypted → authorized client decrypts
Key vault/KMS involved.
Useful when database operators should not see sensitive fields.
Adds complexity and query limitations depending encryption type.
Queryable Encryption
MongoDB provides queryable encrypted-field capabilities allowing selected queries on encrypted data while keeping plaintext protected from server under designed threat model.
Current capabilities evolve by MongoDB version.
In 8.3, consult official Queryable Encryption docs for supported query types/index behavior.
Do not invent custom deterministic encryption to query sensitive values.
Encryption and indexing
Ordinary encrypted random ciphertext cannot support normal plaintext index queries.
Queryable Encryption uses specialized design.
Understand performance/storage trade-offs.
Field encryption threat model
Does not protect against:
- compromised application with decryption key;
- malicious authorized user;
- plaintext logging before encryption;
- XSS/client data theft;
- business-layer authorization bugs.
Defense in depth.
Auditing
MongoDB Enterprise/Atlas capabilities can audit security/admin/data events depending configuration.
Audit:
authentication user/role changes privileged operations selected data access
Audit logs can contain sensitive metadata.
Protect/retain appropriately.
Application audit
Business audit often belongs application-level:
who refunded order who changed role who exported data
Database audit cannot always infer business action.
Store actor/request/reason.
Do not rely solely on generic DB logs.
Connection string security
Never:
console.log(process.env.MONGODB_URI);
URI may contain password.
Redact.
Error messages can also include hostnames.
Secret rotation
Design app to rotate DB credentials without long outage.
Approaches:
- overlap old/new;
- managed IAM;
- restart/reload connections.
Do not have one permanent password for years.
Principle of separate environments
Dev/test/prod:
- separate clusters/databases;
- separate credentials;
- separate network.
Do not run tests against production.
Operator injection
Danger:
collection.findOne({
email: req.body.email,
password: req.body.password,
});
If parser allows object:
{
"email": {
"$ne": null
}
}
could alter query semantics in naive code.
Schema validate:
email must be string
Hash password verification separately.
Do not construct auth query from raw objects.
$where
Server-side JavaScript query operator has security/performance concerns and is often disabled/not appropriate.
Do not expose user-controlled expressions.
Use standard operators.
Regex injection
Search string:
.*
changes regex semantics.
Escape or use search indexes.
Limit length.
Tenant leakage
Every DB query:
{
tenantId: auth.tenantId,
_id: taskId
}
not:
{
_id: taskId
}
then check tenant in JavaScript after returning.
Query scope reduces exposure.
Unique indexes should also include tenant for per-tenant uniqueness.
Backups are sensitive
Backup contains production data.
Encrypt:
- storage;
- transfer;
- access.
Restrict who can restore/download.
Backup leak can bypass live DB controls.
mongodump
Dump files may contain plaintext user data.
Do not upload to public bucket.
Use supported encryption/storage.
Security updates
MongoDB 8.3 patch releases in 2026 include security fixes.
Always install supported patched release, not only “8.3.0 forever.”
Subscribe to security bulletins.
Node driver/Mongoose also need updates.
Supply chain
Application DB stack:
mongodb driver Mongoose plugins monitoring agents
review dependencies.
Avoid abandoned Mongoose plugins with broad hooks.
DoS/query cost
Even authorized query can exhaust DB:
unindexed regex huge sort deep skip massive aggregation
Apply:
- indexes;
- limits;
maxTimeMSwhere appropriate;- rate limits;
- query allowlist;
- separate analytics.
Availability is security.
maxTimeMS
For untrusted/request-driven queries:
collection
.find(filter)
.maxTimeMS(2000)
API form depends driver.
Choose based on workload.
Timeout can fail legitimate slow queries; index/fix root cause.
Server-side scripting/map-reduce
Legacy features such as map-reduce have been superseded by aggregation in many cases.
Avoid enabling powerful scripting for user-controlled logic.
Common mistakes
- public DB;
- admin credentials in app;
- no TLS;
- invalid cert bypass;
- connection string in logs;
- no tenant scope;
- raw object query;
- backups unsecured;
- one credential across all envs/services;
- encryption at rest mistaken for field confidentiality;
- custom crypto;
- no patching;
- no query-cost limits.
Exercises
- Design least-privilege app DB role.
- Threat-model Atlas network access.
- Configure TLS verification conceptually.
- Compare at-rest vs CSFLE vs Queryable Encryption.
- Design DB credential rotation.
- Add tenant-scoped query.
- Fix NoSQL operator injection.
- Add max query limit/timeout to public search.
- Design business audit event.
- Write backup security checklist.
Mastery checklist
Explain:
- authentication;
- RBAC;
- least privilege;
- network/TLS;
- at-rest encryption;
- CSFLE;
- Queryable Encryption;
- X.509/Kerberos/LDAP awareness;
- auditing;
- connection-secret handling;
- tenant/operator injection;
- patching/query DoS.
Official references
- https://www.mongodb.com/docs/manual/security/
- https://www.mongodb.com/docs/manual/core/authorization/
- https://www.mongodb.com/docs/manual/core/security-transport-encryption/
- https://www.mongodb.com/docs/manual/core/csfle/
- https://www.mongodb.com/docs/manual/core/queryable-encryption/
- https://roadmap.sh/mongodb
