Roles, TLS, Follower Reads and Cloud Cost

Article · 8:00

Certificate-based authentication and the insecure-mode warning, roles and privileges, row-level security by region, rolling upgrades, and what multi-region actually costs.

--insecure is for this course and nothing else. It disables TLS and authentication entirely: anyone who can reach the port is root. It is convenient for labs and it must never appear outside one. A secure cluster uses TLS for both node-to-node and client-to-node traffic, with certificates issued from a CA you control.

Certificates. cockroach cert generates a CA, node certificates (which must list every name and address a node is reachable by) and client certificates (whose Common Name is the SQL username). Client certificate authentication is the strongest option and the usual choice for services; password authentication exists for humans. The operational burden is rotation - certificates expire, and a cluster whose node certificates expire simultaneously is an outage that monitoring should have prevented.

Roles and privileges follow the PostgreSQL model closely: roles, inheritance, GRANT at database, schema, table and column level. Beyond that, CockroachDB has system privileges (VIEWACTIVITY, CANCELQUERY, VIEWCLUSTERSETTING) that let you give someone diagnostic access without making them an admin - exactly what an on-call engineer needs and what is usually over-granted instead.

Row-level security is available and is particularly apt here: a policy restricting rows by region pairs naturally with REGIONAL BY ROW, so that a tenant's data is both physically local and logically inaccessible to others.

Follower reads, used deliberately. AS OF SYSTEM TIME follower_read_timestamp() is a production architecture decision, not a trick. It converts a cross-region read from 170 ms to 2 ms at the cost of a few seconds of staleness, and the right design states, per query, whether that staleness is acceptable. Dashboards, reports, catalogue browsing and search: usually yes. Anything feeding a write: no.

Rolling upgrades. CockroachDB upgrades one node at a time with no downtime, and the cluster runs mixed versions during the process. Two things to know: the upgrade is finalised separately, after which you cannot downgrade, so leave time to validate before finalising; and cluster.preserve_downgrade_option is what holds finalisation back.

Cost. This is the module's least technical and most consequential subject. Self-hosted: nodes, storage, and inter-region network egress, which in a multi-region cluster is continuous rather than occasional - every write replicates across regions, forever. CockroachDB Cloud Serverless charges by request units and storage, which is excellent for spiky workloads and surprising if a scan goes wrong. CockroachDB Cloud Dedicated charges by provisioned capacity. The enterprise licence covers multi-region features, incremental backup, changefeeds and more, and a design that quietly depends on those has a price nobody has approved.

Laboratory exercise 6 - make it defensible.

Build a secure cluster: generate a CA, node and client certificates, start the cluster with TLS, and connect with a client certificate. Then prove --insecure is what it says by starting a second cluster insecurely and connecting to it as root with no credentials from another machine.

Implement least privilege: an application role with only the table privileges it needs, a read-only reporting role, and an on-call role with VIEWACTIVITY and CANCELQUERY and no data access at all. Test every denial.

Add a row-level security policy restricting rows by region and show it enforced.

Perform a rolling upgrade across the cluster under write load. Show the mixed-version state, show the writes never stopping, and hold finalisation using the downgrade option.

Configure monitoring: scrape the Prometheus endpoint and build alerts for unavailable ranges, under-replicated ranges, retry rate, admission control queueing, and certificate expiry.

Deliverable: the certificate procedure, the insecure-mode demonstration, the DDL, a test script attempting every forbidden operation with its output, the RLS demonstration, the rolling upgrade evidence, the alert definitions with thresholds, and a deployment and cost checklist including an egress estimate.

-- ================= TLS: --insecure is for labs only ================
--   cockroach cert create-ca --certs-dir=certs --ca-key=ca.key
--   cockroach cert create-node node1 node1.internal localhost 127.0.0.1 \
--       --certs-dir=certs --ca-key=ca.key
--       ^^^^ EVERY name and address the node is reachable by. A
--            missing SAN is a connection failure that looks like a
--            network problem.
--   cockroach cert create-client ord_app --certs-dir=certs --ca-key=ca.key
--       ^^^^ the client certificate's Common Name IS the SQL username.
--
--   cockroach start --certs-dir=certs --join=...
--   cockroach sql --certs-dir=certs --user=ord_app
--
-- --insecure disables TLS AND authentication. Anyone who can reach
-- 26257 is root. Demonstrate it once, in a lab, and never ship it.

SELECT * FROM crdb_internal.cluster_settings
WHERE variable LIKE '%ssl%' OR variable LIKE '%tls%';

-- Certificate expiry. A cluster whose node certs expire together is
-- an outage monitoring should have caught. Alert on this:
SELECT node_id, (metrics->>'security.certificate.expiration.node')::INT
       AS node_cert_expiry_epoch
FROM crdb_internal.kv_node_status;

-- ================= Roles and privileges ============================
CREATE ROLE app_role;
GRANT SELECT, INSERT, UPDATE ON TABLE orders, order_line TO app_role;
GRANT SELECT ON TABLE customer, product TO app_role;
GRANT USAGE ON SCHEMA public TO app_role;

CREATE ROLE report_role;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO report_role;

CREATE USER ord_app WITH LOGIN;        -- authenticates by certificate
GRANT app_role TO ord_app;
CREATE USER reporter WITH PASSWORD 'Str0ng#Reporter';
GRANT report_role TO reporter;

-- SYSTEM PRIVILEGES: diagnostic access WITHOUT admin. Exactly what
-- on-call needs, and what is usually over-granted to admin instead.
CREATE ROLE oncall_role;
GRANT SYSTEM VIEWACTIVITY TO oncall_role;       -- see running queries
GRANT SYSTEM CANCELQUERY TO oncall_role;        -- cancel one
GRANT SYSTEM VIEWCLUSTERSETTING TO oncall_role; -- read settings
CREATE USER oncall WITH PASSWORD 'Str0ng#Oncall';
GRANT oncall_role TO oncall;
-- oncall can now diagnose an incident and cannot read a single row of
-- customer data.

SHOW GRANTS FOR ord_app;
SHOW SYSTEM GRANTS FOR oncall;

-- Verify the denials. The assessed part - every one must fail:
--   \c - ord_app
--   DELETE FROM orders;                  -- permission denied
--   DROP TABLE orders;                   -- permission denied
--   SELECT * FROM crdb_internal.ranges;  -- permission denied
--   SET CLUSTER SETTING ...;             -- permission denied

-- ================= Row-level security, by region ===================
ALTER TABLE customer ENABLE ROW LEVEL SECURITY;
CREATE POLICY customer_region_policy ON customer
    USING (region::STRING = current_setting('app.current_region', true));
GRANT SELECT ON customer TO app_role;
-- Pairs naturally with REGIONAL BY ROW: a tenant's data is both
-- physically local and logically inaccessible to others.
--   SET app.current_region = 'europe-west1';
--   SELECT count(*) FROM customer;   -- European rows only

-- ================= Follower reads as ARCHITECTURE ==================
-- Not a trick. A per-query decision about staleness.
CREATE VIEW dashboard_revenue AS
SELECT date_trunc('day', ordered_at) AS day, sum(total) AS revenue
FROM orders AS OF SYSTEM TIME follower_read_timestamp()
GROUP BY 1;
--     cross-region read, leaseholder:  ~170 ms
--     the same read from a follower:     ~2 ms
--     staleness: ~4.8 s
--
-- Dashboards, reports, catalogue browsing, search: yes.
-- Anything feeding a write: no. State the decision per query.
SHOW CLUSTER SETTING kv.closed_timestamp.target_duration;

-- ================= Rolling upgrade =================================
SELECT DISTINCT version FROM [SHOW CLUSTER SETTING version];
SET CLUSTER SETTING cluster.preserve_downgrade_option = '24.1';
--    ^^^ holds FINALISATION back so you can still downgrade. Upgrade
--    the nodes one at a time; the cluster runs mixed versions and
--    keeps serving. Validate. THEN:
RESET CLUSTER SETTING cluster.preserve_downgrade_option;   -- no going back

SELECT node_id, build_tag FROM crdb_internal.kv_node_status;

-- ================= Monitoring: what to alert on ====================
--   Prometheus: http://<node>:8080/_status/vars
--
--   ranges_unavailable        > 0        PAGE. No quorum.
--   ranges_underreplicated    > 0 for 15m  a replica is missing
--   sql.txn.restarts.*        rising      contention or a hot row
--   admission.wait_durations  rising      shedding load
--   liveness.livenodes        < expected  a node is gone
--   cert expiry               < 30 days   a preventable outage
--   clock offset              > 400ms     CLOSE TO FATAL: a node
--                                         whose clock drifts too far
--                                         SHUTS ITSELF DOWN to protect
--                                         consistency. Run NTP.

SELECT node_id, (metrics->>'clock-offset.meannanos')::FLOAT/1e6 AS offset_ms
FROM crdb_internal.kv_node_status;

-- ================= Cost: the network is a LINE ITEM ================
--   Self-hosted:  nodes + storage + INTER-REGION EGRESS. In a
--                 multi-region cluster every write replicates across
--                 regions, continuously, forever. Estimate it from
--                 write volume x replica count x region distance,
--                 and do it before the architecture review.
--   Cloud Serverless: request units + storage. Excellent for spiky
--                 workloads; a runaway scan is a bill.
--   Cloud Dedicated: provisioned capacity.
--   Enterprise licence: multi-region features, incremental backup,
--                 changefeeds. A design that quietly needs these has
--                 a price nobody has approved.

Discussion

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