Authentication is off by default in a bare mongod, and a MongoDB instance reachable from the internet without authentication is a well-documented category of breach - there have been tens of thousands of them. --auth (or security.authorization: enabled) turns it on; SCRAM is the default mechanism; x.509 certificates and LDAP/Kerberos are available for enterprise deployments.
Roles. The built-ins cover most needs: read, readWrite, dbAdmin, clusterMonitor, backup, restore, and the ones to treat carefully - dbOwner, userAdmin, and root, which is everything. Custom roles let you grant specific actions on specific collections, which is how you build a genuinely narrow application role. The subtlety worth knowing: a user is defined in a specific database (its authentication database) and may hold roles on others, so {user: "app", db: "admin"} and {user: "app", db: "shop"} are different users.
TLS. --tlsMode requireTLS with a certificate and CA file, for both client and intra-cluster traffic. preferTLS is for a migration window, not a destination.
Network restriction is as important as authentication. bindIp should never be 0.0.0.0 on a reachable host; Atlas has IP access lists and private endpoints. The defence in depth that actually prevents the breach category above is: authentication on, bound to a private interface, and a firewall.
Encryption. At rest, WiredTiger encryption is an enterprise feature; cloud volume encryption is the common alternative. Client-side field level encryption is the interesting one: fields are encrypted by the driver, so the server never sees the plaintext and neither does anyone with database access. Queryable encryption extends this to equality and range queries on encrypted fields. The hard part is key management, as always.
Schema evolution without downtime is a document-database skill with no SQL equivalent. The pattern:
- Add the new field, write both old and new, read either (the application tolerates both shapes).
- Backfill existing documents in batches, throttled.
- Once the backfill completes, stop writing the old field and read only the new.
- Remove the old field, and only then tighten the validator.
A versioned schema - a schemaVersion field on each document - makes this explicit and lets a migration run for weeks safely.
Connection pooling. The driver maintains a pool, default maxPoolSize 100 per client. The mistakes are both common: creating a client per request, which makes a new pool every time and exhausts the server's connection limit, or running many application instances each with 100 connections against a server that cannot take the total. MongoClient is designed to be created once and shared for the process's lifetime.
Laboratory exercise 6 - make it defensible.
Enable authentication and TLS. Then demonstrate what the default costs: start a second mongod without --auth bound to a non-loopback interface and connect to it as an administrator from another machine with no credentials. This is the breach, performed in a lab, and it should be uncomfortable.
Implement least privilege: an application user with a custom role granting only the actions it needs on only its collections; a read-only reporting user; a monitoring user with clusterMonitor and no data access. Test every denial.
Configure client-side field level encryption on one sensitive field and show that a database administrator reading the collection directly sees ciphertext.
Perform a four-stage schema migration on a collection under live write load, with a schemaVersion field, and show that no request failed at any stage.
Configure monitoring: replication lag, election count, cache eviction, connection count against the limit, oplog window, slow queries from the profiler, and assertion counts.
Deliverable: the security configuration, the unauthenticated-access demonstration, the custom role definitions, a test script attempting every forbidden operation with its output, the field-level encryption evidence, the migration log showing zero failures, the alert definitions with thresholds, and a deployment and cost checklist.
// ================= Authentication is OFF by default ================
// A mongod reachable from the internet without auth is a documented
// breach category with tens of thousands of instances. Turn it on:
// mongod --auth --bind_ip 127.0.0.1,10.0.1.5
// ^^^^^^^^ never 0.0.0.0 on a reachable host
//
// Defence in depth, all three: auth on, bound to a private interface,
// firewalled.
use admin;
db.createUser({ user: "admin", pwd: passwordPrompt(),
roles: [{role: "userAdminAnyDatabase", db: "admin"}] });
// ================= TLS =============================================
// mongod --tlsMode requireTLS \
// --tlsCertificateKeyFile /etc/ssl/mongodb.pem \
// --tlsCAFile /etc/ssl/ca.pem \
// --clusterAuthMode x509
// preferTLS is a MIGRATION WINDOW, not a destination.
// ================= CUSTOM ROLES: actual least privilege ============
use shop;
db.createRole({
role: "orderService",
privileges: [
{ resource: {db: "shop", collection: "orders"},
actions: ["find", "insert", "update"] }, // no remove
{ resource: {db: "shop", collection: "order_line"},
actions: ["find", "insert", "update"] },
{ resource: {db: "shop", collection: "product"},
actions: ["find"] }, // read only
{ resource: {db: "shop", collection: "inventory"},
actions: ["find", "update"] }
],
roles: []
});
db.createUser({user: "ord_app", pwd: passwordPrompt(),
roles: [{role: "orderService", db: "shop"}]});
db.createUser({user: "reporter", pwd: passwordPrompt(),
roles: [{role: "read", db: "shop"}]});
// Monitoring with NO data access - what on-call actually needs:
use admin;
db.createUser({user: "monitor", pwd: passwordPrompt(),
roles: [{role: "clusterMonitor", db: "admin"}]});
// A user belongs to a SPECIFIC database. These are DIFFERENT users:
// {user: "app", db: "admin"} vs {user: "app", db: "shop"}
db.getSiblingDB("admin").system.users.find({}, {user:1, db:1, roles:1});
// Verify the denials. Every one must fail:
// mongosh -u ord_app -p --authenticationDatabase shop
// db.orders.deleteMany({}) -> not authorized
// db.orders.drop() -> not authorized
// db.customer.find() -> not authorized
// db.adminCommand({listDatabases:1})-> not authorized
db.runCommand({connectionStatus: 1}).authInfo.authenticatedUserPrivileges;
// ================= Client-side field level encryption ==============
// The SERVER never sees the plaintext. Neither does a DBA with full
// database access - which is the point.
const encryptedFieldsMap = {
"shop.customer": {
fields: [
{ path: "taxId", bsonType: "string",
queries: {queryType: "equality"} }, // queryable encryption
{ path: "dob", bsonType: "date" } // not queryable
]
}
};
// new MongoClient(uri, {autoEncryption: {
// keyVaultNamespace: "encryption.__keyVault",
// kmsProviders: {aws: {...}}, // or local, for the lab
// encryptedFieldsMap
// }})
//
// Then read the collection as an admin with a NORMAL client and show
// ciphertext. The hard part is key management, as always: lose the
// key and the data is gone.
// ================= SCHEMA EVOLUTION, four stages, no downtime ======
// Stage 1: write BOTH, read EITHER. The application tolerates both
// shapes, so deploy order does not matter.
db.customer.updateOne({_id: id}, {$set: {
name: "Ada Lovelace", // old shape
firstName: "Ada", lastName: "Lovelace", // new shape
schemaVersion: 2
}});
// Stage 2: backfill in THROTTLED batches. Never one updateMany over
// 50 million documents - that is a long write lock and a replication
// lag spike.
let processed = 0;
while (true) {
const batch = db.customer.find({schemaVersion: {$ne: 2}})
.limit(1000).toArray();
if (batch.length === 0) break;
const ops = batch.map(d => {
const [f, ...r] = (d.name || "").split(" ");
return {updateOne: {filter: {_id: d._id}, update: {$set: {
firstName: f, lastName: r.join(" "), schemaVersion: 2}}}};
});
db.customer.bulkWrite(ops, {ordered: false});
processed += batch.length;
sleep(50); // throttle: watch replication lag
}
// Stage 3: stop writing the old field; read only the new.
// Stage 4: remove it, and ONLY THEN tighten the validator.
db.customer.updateMany({}, {$unset: {name: ""}});
db.runCommand({collMod: "customer", validator: {$jsonSchema: {
required: ["firstName", "lastName", "schemaVersion"]
}}});
db.customer.countDocuments({schemaVersion: {$ne: 2}}); // must be 0
// ================= Connection pooling: both common mistakes ========
// MongoClient is created ONCE per process and shared. A client per
// request makes a new pool every time and exhausts the server.
// new MongoClient(uri, {
// maxPoolSize: 50, // per CLIENT. Multiply by instances
// minPoolSize: 5, // and compare with the server limit.
// maxIdleTimeMS: 60000,
// waitQueueTimeoutMS: 5000, // fail fast rather than queue forever
// retryWrites: true, // leave ON: survives an election
// retryReads: true
// })
db.serverStatus().connections;
// { current: 412, available: 51788, totalCreated: 90112 }
// current climbing steadily = a leak, usually a client per request.
// ================= Monitoring: what to alert on ====================
db.serverStatus().opcounters;
db.serverStatus().metrics.repl.apply.batches;
db.serverStatus().asserts; // rising = trouble
db.getSiblingDB("local").oplog.rs.find().sort({$natural:1}).limit(1).next().ts;
db.setProfilingLevel(1, {slowms: 100, sampleRate: 0.1});
db.system.profile.find().sort({millis: -1}).limit(10);
// ^^^^ the profiler WRITES TO A CAPPED COLLECTION in the
// database. Sample rather than capture everything.
// replication lag > 10 s secondaries falling behind
// election count > 0 unexpectedly instability
// cache evictions by app threads > 0 working set does not fit
// connections > 80% of limit a leak or under-sized pool
// oplog window < 24 h change streams cannot resume
// assertion count rising application errors
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.