Roles, Privileges, TLS, Query Limits and Monitoring

Article · 10:00

Authentication and the edition boundary, role-based access control including property and traversal rules, TLS, query limits as a safety mechanism, monitoring, and the Aura comparison.

Authentication is on by default, and the first login forces a password change on the neo4j user. That is a better default than several databases in this programme. Authorisation is where the edition boundary bites: Community has one effective user with full access and no role-based access control at all. Everything in this topic beyond authentication requires Enterprise or Aura, and for a Community deployment the honest answer is that authorisation is your application's responsibility - the database cannot help, and the design must say so.

Enterprise RBAC is unusually fine-grained for a graph database, and the graph-specific parts are the interesting ones. Beyond the familiar database, graph and schema privileges, you can grant or deny:

  • Traverse on specific labels and relationship types - so a role can be unable to see a node type at all.
  • Read on specific properties - so a role can traverse a node and not read its email.
  • Match, which combines traverse and read.
  • Write, create, delete, set property and merge, separately.

Property-level and label-level denies are genuinely useful and have a sharp edge: a role that cannot traverse a relationship type will get different query results, not an error. So a report that silently returns fewer rows for one role is the expected behaviour, and you must design and test for it rather than discover it. Deny takes precedence over grant, which is the right default and means a DENY is absolute.

Query limits are a safety mechanism, not a tuning option, and this is the module's most practical content. Given Module 3, the cluster needs protection against the unbounded traversal somebody will eventually write:

  • db.transaction.timeout kills a query after a wall-clock limit.
  • dbms.memory.transaction.max caps one transaction's memory.
  • dbms.memory.transaction.total.max caps all transactions together.
  • dbms.transaction.concurrent.maximum caps concurrency.

Set all four. They turn "a bad query took the database down" into "a bad query got an error", which is the difference between an incident and a bug report.

TLS covers both the Bolt and HTTP connectors, configured per connector with a certificate directory. In a cluster, the intra-cluster connector also deserves encryption.

Monitoring. The Neo4j-specific set: the page cache hit ratio (below about 0.98 means the working set does not fit, and in a graph database that is severe), heap and garbage collection pause times, transaction counts including rolled-back and terminated, active and longest-running transactions, store sizes against the page cache, index population state, and - in a cluster - the Raft leader, the last applied index per member and the replication lag. Add dbms.listQueries reviewed under load, because a long-running query is the signal that matters most here.

Aura against self-managed. Aura is managed Enterprise: automated backups, online upgrades, monitoring and no instance to operate, billed by instance size with a free tier for learning. Self-managed Community is free and gives up RBAC, clustering and online backup. Self-managed Enterprise is a commercial licence and gives full control. The honest comparison for most teams: Aura removes the operational work that Community cannot do at all and Enterprise requires a licence for - and the cost question is therefore less "is Aura expensive" than "what does the Community constraint actually cost us".

Laboratory exercise 6 - make it defensible.

If you have Enterprise or Aura, implement least privilege: a role that can read the graph but not traverse :Account; a role that can traverse :Person but cannot read the email property; a write role scoped to one label; and a monitoring role with no data access. Test every denial, and specifically demonstrate that a restricted role gets different query results rather than an error.

On Community, demonstrate the limitation: show that there is no RBAC, then document the application-layer design that compensates and its weaknesses.

Configure TLS on the Bolt connector and verify it.

Set all four query limits and prove they work: run the unbounded traversal from Module 3 against the configured instance and show it being terminated rather than taking the database down. This is the laboratory's most valuable artefact.

Configure monitoring with every metric above and a threshold for each, including the page cache hit ratio and a long-running query alert.

Then produce the Aura-against-self-managed comparison for the capstone, with costs at your sizing and an explicit statement of what the Community constraints would cost you.

Deliverable: the role definitions (or the Community limitation documented), a test script attempting every forbidden operation with its output, the different-results demonstration, the TLS verification, the four query limits with the unbounded traversal terminated, the alert definitions with thresholds, and the edition comparison with costs.

// ==================================================================
// AUTHENTICATION: on by default, and it forces a password change.
// A better default than several databases in this programme.
// ==================================================================
SHOW CURRENT USER;
ALTER CURRENT USER SET PASSWORD FROM 'old' TO 'Str0ng#NewPass';

// *** THE EDITION BOUNDARY: Community has ONE effective user with
// *** FULL ACCESS and NO role-based access control AT ALL. ***
// Everything below requires ENTERPRISE or AURA. For a Community
// deployment the honest answer is that AUTHORISATION IS YOUR
// APPLICATION'S RESPONSIBILITY - the database cannot help, and the
// design must SAY SO rather than imply otherwise.

// ==================================================================
// ENTERPRISE RBAC: and the GRAPH-SPECIFIC privileges are the
// interesting part.
// ==================================================================
CREATE USER fraud_app SET PASSWORD 'Str0ng#App' CHANGE NOT REQUIRED;
CREATE USER analyst   SET PASSWORD 'Str0ng#Ana' CHANGE NOT REQUIRED;
CREATE USER monitor   SET PASSWORD 'Str0ng#Mon' CHANGE NOT REQUIRED;

// An application role: read and write, scoped.
CREATE ROLE fraud_writer;
GRANT ACCESS ON DATABASE neo4j TO fraud_writer;
GRANT MATCH {*} ON GRAPH neo4j NODES Person, Account, Device, Address
  TO fraud_writer;
GRANT MATCH {*} ON GRAPH neo4j RELATIONSHIPS OWNS, TRANSFERRED,
  LIVES_AT, USED_DEVICE TO fraud_writer;
GRANT CREATE ON GRAPH neo4j NODES Person, Account TO fraud_writer;
GRANT SET PROPERTY {risk_score} ON GRAPH neo4j NODES Person TO fraud_writer;
//   SET PROPERTY on ONE named property. That is the granularity.
GRANT ROLE fraud_writer TO fraud_app;

// *** AN ANALYST WHO CANNOT SEE ACCOUNTS AT ALL: ***
CREATE ROLE analyst_restricted;
GRANT ACCESS ON DATABASE neo4j TO analyst_restricted;
GRANT MATCH {*} ON GRAPH neo4j NODES * TO analyst_restricted;
GRANT MATCH {*} ON GRAPH neo4j RELATIONSHIPS * TO analyst_restricted;
DENY TRAVERSE ON GRAPH neo4j NODES Account TO analyst_restricted;
//   *** THE SHARP EDGE: a role that cannot TRAVERSE a label gets
//   *** DIFFERENT QUERY RESULTS, NOT AN ERROR. ***
//     as fraud_app:  MATCH (p:Person)-[:OWNS]->(a:Account) RETURN count(*)
//       -> 500,000
//     as analyst:    the same query
//       -> 0.   No error. No warning.
//   So a report that silently returns fewer rows for one role is the
//   EXPECTED behaviour. DESIGN AND TEST FOR IT rather than discover
//   it, and demonstrate it in the lab.

// *** AND A ROLE THAT CAN TRAVERSE A PERSON AND NOT READ THEIR
// *** EMAIL: ***
DENY READ {email, phone} ON GRAPH neo4j NODES Person TO analyst_restricted;
//   MATCH (p:Person) RETURN p.name, p.email
//   -> name populated, EMAIL NULL. Again: no error.
GRANT ROLE analyst_restricted TO analyst;

// Monitoring, with NO DATA access:
CREATE ROLE observer;
GRANT SHOW TRANSACTION (*) ON DATABASE neo4j TO observer;
GRANT SHOW INDEX ON DATABASE neo4j TO observer;
GRANT SHOW CONSTRAINT ON DATABASE neo4j TO observer;
GRANT ROLE observer TO monitor;

SHOW ROLES;
SHOW PRIVILEGES;
SHOW USER analyst PRIVILEGES;
//   *** DENY TAKES PRECEDENCE OVER GRANT. *** Which is the right
//   default, and means a DENY is absolute - you cannot grant around
//   it.

// VERIFY THE DENIALS - every one must fail, or return less:
//   as fraud_app:  CREATE (:Device {fingerprint:'x'})   -> denied
//                  MATCH (n) DETACH DELETE n            -> denied
//                  SET p.name = 'x'                     -> denied
//                  SHOW USERS                           -> denied
//   as analyst:    any query touching :Account   -> SILENTLY EMPTY
//                  p.email                       -> SILENTLY NULL
//   as monitor:    MATCH (n) RETURN n            -> denied

// ==================================================================
// TLS
// ==================================================================
//   server.bolt.tls_level=REQUIRED
//   dbms.ssl.policy.bolt.enabled=true
//   dbms.ssl.policy.bolt.base_directory=certificates/bolt
//   dbms.ssl.policy.bolt.client_auth=NONE
//   server.https.enabled=true
//   dbms.ssl.policy.https.enabled=true
//   -- and in a cluster, the INTRA-CLUSTER connector too:
//   dbms.ssl.policy.cluster.enabled=true
//
//   neo4j+s://host:7687   (TLS, verified)
//   neo4j+ssc://          (TLS, self-signed - development only)

// ==================================================================
// *** QUERY LIMITS ARE A SAFETY MECHANISM, NOT A TUNING OPTION. ***
// ==================================================================
// Given Module 3, the instance needs protection against the
// unbounded traversal somebody WILL eventually write. SET ALL FOUR:
//
//   db.transaction.timeout=60s
//     -> kills a query after a wall-clock limit
//   dbms.memory.transaction.max=1g
//     -> caps ONE transaction's memory
//   dbms.memory.transaction.total.max=4g
//     -> caps ALL transactions together
//   dbms.transaction.concurrent.maximum=200
//     -> caps concurrency
//
// *** THEY TURN "A BAD QUERY TOOK THE DATABASE DOWN" INTO "A BAD
// *** QUERY GOT AN ERROR" - the difference between an incident and
// *** a bug report. ***
//
// PROVE IT. Run Module 3's unbounded traversal against the
// configured instance:
//   MATCH (a)-[*]-(b) RETURN count(*);
//   -> Neo.ClientError.Transaction.TransactionTimedOut
//   or Neo.TransientError.General.MemoryPoolOutOfMemoryError
//   ... and the database is still serving every other query.
// This is the laboratory's most valuable artefact.

SHOW TRANSACTIONS;
CALL dbms.listQueries() YIELD queryId, query, elapsedTimeMillis, status
WHERE elapsedTimeMillis > 5000 RETURN queryId, query, elapsedTimeMillis;
TERMINATE TRANSACTION 'neo4j-transaction-42';

// ==================================================================
// MONITORING: the Neo4j-specific set.
// ==================================================================
//   metrics endpoint: /metrics  (server.metrics.prometheus.enabled)
//
//   *** neo4j_page_cache_hit_ratio      < 0.98 = THE WORKING SET
//       DOES NOT FIT, and in a graph database that is SEVERE -
//       every hop becomes a disk read and index-free adjacency
//       stops being an advantage. The single most important Neo4j
//       metric. ***
//   neo4j_page_cache_evictions          rising
//   neo4j_vm_heap_used / max            > 80%
//   neo4j_vm_gc_time_total              long pauses
//   neo4j_transaction_active            concurrency
//   neo4j_transaction_rollbacks         deadlocks, failures
//   neo4j_transaction_terminated        YOUR QUERY LIMITS FIRING -
//                                       which is good, and worth
//                                       knowing the rate of
//   neo4j_transaction_peak_concurrent
//   neo4j_store_size_total              vs the page cache
//   index population state              a half-built index is a
//                                       scan
//   CLUSTER: the Raft leader, last applied index per member,
//            replication lag
//
//   AND: dbms.listQueries reviewed UNDER LOAD. A long-running query
//   is the signal that matters most here, and it is the one a
//   dashboard of averages hides.
CALL db.stats.retrieve('GRAPH COUNTS');

// ==================================================================
// AURA vs SELF-MANAGED. The honest comparison.
// ==================================================================
//   AURA (managed Enterprise)
//     + automated backups, ONLINE upgrades, monitoring, no instance
//       to operate, and RBAC and clustering INCLUDED
//     + a free tier, genuinely usable for learning
//     - instance-size billing, less control, provider-specific
//
//   SELF-MANAGED COMMUNITY
//     + free
//     - NO RBAC, NO CLUSTERING, NO ONLINE BACKUP
//     -> single instance, backed up only with downtime, and
//        authorisation entirely in your application
//
//   SELF-MANAGED ENTERPRISE
//     + full control, everything available
//     - a commercial licence, and you operate it
//
// *** THE HONEST FRAMING FOR MOST TEAMS: Aura removes the
// *** operational work that Community CANNOT DO AT ALL and
// *** Enterprise REQUIRES A LICENCE FOR. So the cost question is
// *** less "is Aura expensive" than "WHAT DOES THE COMMUNITY
// *** CONSTRAINT ACTUALLY COST US" - in downtime for backups, in
// *** application-layer authorisation, and in having no failover. ***
// Put both numbers in the checklist.

Discussion

No questions on this topic yet. Sign in to ask the first one.