CouchDB 3 requires an admin. The older "Admin Party" mode, where an unconfigured server granted everyone full rights, is gone - and the breaches it caused are the reason. Server admins are configured in the node config or the _users database.
Users live in the _users database as documents of type user, each with a name, a password (hashed on write by the server) and a list of roles, which are arbitrary strings your application defines.
Authorisation is per database, through a security object. PUT /<db>/_security sets two groups - admins and members - each a list of names and roles. Members may read and write the database; admins may additionally change design documents and the security object itself. A database with no members list is readable by any authenticated user, which is a default worth knowing before you rely on it.
The granularity stops there: CouchDB has no per-document read permission. You cannot say "this user may read only their own documents" with the security object. The two real answers are a database per user or per tenant - which is idiomatic CouchDB and scales further than it sounds, since databases are cheap - and filtered replication to give each client only its own subset. Trying to implement per-document reads at the application layer in front of a shared database tends to leak.
validate_doc_update is CouchDB's most distinctive security feature. It is a JavaScript function in a design document that runs on every write, including every write arriving by replication, and can reject it by throwing. That last clause is what makes it powerful: a device replicating bad or malicious documents is stopped by the server, not by the client's good behaviour. It receives the new document, the old one, the user's context and the security object, so it can enforce schema, immutability, ownership and role rules in one place.
Its limits are real: it sees only the one document - no cross-document checks, no uniqueness constraints - and it runs on every write, so it must be fast.
Monitoring. /_node/_local/_stats exposes request rates, status code counts, view reads and replicator state. Beyond the usual, the CouchDB-specific alarms are: conflict count rising, file-to-active ratio rising (compaction behind), view updates_pending growing, replicator documents in crashing or failed, and doc_write_failures non-zero on a replication.
Upgrade planning. CouchDB upgrades are usually straightforward within a major version, and rolling upgrades across a cluster work. The things to plan: view index rebuilds, breaking changes between major versions (2 to 3 removed Admin Party and changed defaults), and the fact that a replication between different versions generally works, which gives you a migration path - stand up the new cluster, replicate into it, switch over.
Laboratory exercise 6 - make it defensible.
Configure TLS and an admin. Create users with roles in _users.
Implement least privilege: a database with an explicit members list, a collector role that may write responses, a reviewer role that may write reviews, and a read-only reporting user. Test every denial. Then demonstrate the default: create a database with no members list and show that any authenticated user can read it.
Write a validate_doc_update function enforcing: required fields and types; that a collector may only write documents whose collectorId is their own; that collectedAt is immutable once set; and that only the reviewer role may change reviewStatus. Then prove it holds against replication - attempt to replicate a document violating each rule from another database and capture the rejection.
Implement the database-per-tenant pattern for one tenant and show the isolation.
Configure monitoring with all five CouchDB-specific alarms.
Deliverable: the security configuration, the security objects, the no-members-list demonstration, the validation function, a test script attempting every forbidden operation and every forbidden replication with its output, the per-tenant isolation evidence, the alert definitions with thresholds, and a deployment, upgrade and cost checklist.
// ================= Users and roles =================================
// Users are documents in _users. The server hashes the password on
// write. Roles are arbitrary strings YOUR application defines.
// PUT /_users/org.couchdb.user:field-07
const user = {
_id: "org.couchdb.user:field-07",
name: "field-07",
type: "user",
roles: ["collector", "survey:site-14"], // your vocabulary
password: "Str0ng#Field07" // replaced by a hash
};
// ================= Per-database security object ====================
// PUT /survey/_security
const security = {
admins: { names: ["admin"], roles: ["_admin"] },
members: { names: [], roles: ["collector", "reviewer", "reporter"] }
};
// members: read and write. admins: also design documents and this
// object.
//
// THE DEFAULT WORTH KNOWING: a database with NO members list is
// readable by ANY AUTHENTICATED USER. Demonstrate it, then never
// rely on it.
// PUT /open_db (no _security)
// curl -u field-07:... http://.../open_db/_all_docs -> 200 OK
// AND THE LIMIT THAT SHAPES EVERY COUCHDB DESIGN:
// There is NO PER-DOCUMENT READ PERMISSION. You cannot express
// "this user may read only their own documents" here. The two real
// answers:
// 1. A DATABASE PER USER OR TENANT. Idiomatic CouchDB, and it
// scales further than it sounds - databases are cheap.
// 2. FILTERED REPLICATION, so each client holds only its subset.
// Enforcing per-document reads in an application layer in front of a
// shared database tends to leak.
// PUT /survey_tenant_acme
// PUT /survey_tenant_acme/_security
// {"members": {"roles": ["tenant:acme"]}}
// ================= validate_doc_update =============================
// CouchDB's most distinctive security feature. It runs on EVERY
// write, INCLUDING EVERY WRITE ARRIVING BY REPLICATION - so a device
// pushing bad or malicious documents is stopped by the SERVER, not by
// the client's good behaviour.
// PUT /survey/_design/validation
const validation = {
_id: "_design/validation",
language: "javascript",
validate_doc_update: function (newDoc, oldDoc, userCtx, secObj) {
// Deletions: only the owner or a reviewer.
if (newDoc._deleted) {
if (userCtx.roles.indexOf("reviewer") === -1 &&
(!oldDoc || oldDoc.collectorId !== userCtx.name)) {
throw({forbidden: "Only the collector or a reviewer may delete."});
}
return;
}
if (!newDoc.type) throw({forbidden: "type is required"});
if (newDoc.type === "response") {
// Schema.
if (typeof newDoc.surveyId !== "string")
throw({forbidden: "surveyId must be a string"});
if (!Array.isArray(newDoc.answers))
throw({forbidden: "answers must be an array"});
if (!/^\d{4}-\d{2}-\d{2}T/.test(newDoc.collectedAt || ""))
throw({forbidden: "collectedAt must be an ISO 8601 timestamp"});
// OWNERSHIP: a collector may only write their OWN documents.
// This is the rule that matters, and it is enforced against
// replication too.
if (userCtx.roles.indexOf("_admin") === -1 &&
userCtx.roles.indexOf("reviewer") === -1 &&
newDoc.collectorId !== userCtx.name) {
throw({forbidden: "A collector may only write their own responses."});
}
// IMMUTABILITY: collectedAt cannot change once set.
if (oldDoc && oldDoc.collectedAt &&
oldDoc.collectedAt !== newDoc.collectedAt) {
throw({forbidden: "collectedAt is immutable."});
}
// FIELD-LEVEL ROLE RULE.
if (oldDoc && oldDoc.reviewStatus !== newDoc.reviewStatus &&
userCtx.roles.indexOf("reviewer") === -1) {
throw({forbidden: "Only a reviewer may change reviewStatus."});
}
}
if (newDoc.type === "review" &&
userCtx.roles.indexOf("reviewer") === -1) {
throw({unauthorized: "Only a reviewer may write reviews."});
}
// forbidden -> 403 unauthorized -> 401
}.toString()
};
// THE LIMITS, both real:
// * it sees ONE document. No cross-document checks. NO UNIQUENESS
// CONSTRAINTS - CouchDB has none, anywhere.
// * it runs on EVERY write, so it must be fast. No loops over
// large arrays.
// PROVE IT HOLDS AGAINST REPLICATION. This is the assessed part:
// 1. create a document violating each rule in a second database
// 2. replicate that database in
// 3. capture the rejection in /_scheduler/docs:
// "doc_write_failures": 4
// 4. PouchDB clients see it as the 'denied' sync event
// ================= TLS =============================================
// [ssl]
// enable = true
// cert_file = /etc/couchdb/cert/couchdb.pem
// key_file = /etc/couchdb/cert/privkey.pem
// cacert_file = /etc/couchdb/cert/ca.pem
// In a cluster, terminate TLS at a proxy and keep node-to-node
// traffic on a private network - CouchDB's inter-node protocol is
// Erlang distribution, not HTTP.
// curl -s http://.../_node/_local/_config/ssl | jq
// ================= Monitoring: the FIVE CouchDB-specific alarms ====
// curl -s http://.../_node/_local/_stats | jq
// curl -s http://.../_node/_local/_system | jq
// 1. CONFLICT COUNT RISING - silent data loss in progress.
// GET /survey/_design/conflicts/_view/all?reduce=true
// 2. FILE / ACTIVE RATIO - compaction falling behind.
// GET /survey -> sizes.file / sizes.active > 2 investigate
// 3. VIEW updates_pending GROWING - the indexer cannot keep up.
// GET /survey/_design/reports/_info
// 4. REPLICATOR STATE - crashing or failed.
// GET /_scheduler/docs | select(.state != "running")
// 5. doc_write_failures NON-ZERO - validation rejecting replicated
// documents, which may be a client bug or an attack.
// GET /_scheduler/docs | .info.doc_write_failures
// Plus the usual: 5xx rate, request latency, disk free, open file
// descriptors (CouchDB uses many - one per shard per database).
// ================= Upgrades ========================================
// * rolling upgrades within a major version work
// * plan for VIEW INDEX REBUILDS, which can take hours
// * 2 -> 3 removed Admin Party and changed defaults: read the notes
// * REPLICATION BETWEEN VERSIONS generally works, which gives you
// the safest migration path: stand up the new cluster, replicate
// into it, verify, switch over, keep the old one until you are
// sure.
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.