Security, Partitioning and Upgrades

Article · 7:00

Roles and grants done properly, row-level security, TLS and SCRAM, declarative partitioning, and planning an upgrade that does not require a maintenance window you cannot afford.

Least privilege, concretely. The application role should not own its tables. Separate the owner - which runs migrations and holds DDL rights - from the runtime role, which has only the DML it needs. A compromised application credential then cannot drop a table.

Grants apply to objects that exist now, which is why a new table created next month is invisible to the role you granted last month. ALTER DEFAULT PRIVILEGES fixes this, and leaving it out is the commonest permission bug in PostgreSQL.

Revoke CREATE on public and revoke CONNECT on the database from PUBLIC, then grant it to the roles that need it. The defaults are permissive for historical reasons.

Row-level security pushes an authorisation rule into the table itself. With RLS enabled and a policy defined, a tenant's query returns only that tenant's rows even if the application's WHERE clause is wrong or missing. It is the difference between multi-tenancy that is enforced and multi-tenancy that is intended. Note that the table owner bypasses RLS unless you FORCE it - another argument for the application not owning its tables.

Authentication and transport. scram-sha-256 is the current password method; md5 is deprecated and should be gone. pg_hba.conf is evaluated top to bottom and the first matching line wins, which is why a permissive rule above a restrictive one silently disables it. Require TLS with hostssl and sslmode=verify-full on the client - require alone encrypts without authenticating the server, which does not protect you from the attacker who is in the path.

Declarative partitioning splits one logical table into physical partitions by range, list or hash. The benefits that justify the complexity are that dropping a partition is instantaneous where deleting the equivalent rows is not, autovacuum works per partition, and the planner prunes partitions a query cannot match. The cost is that the partition key must be in your WHERE clauses, and every unique constraint must include it.

Upgrades. Minor versions are a restart. Major versions are a project: pg_upgrade --link is fast but has a difficult rollback; logical replication to a new-version instance allows a near-zero-downtime cutover and a quick reversal, at the cost of a more complex setup. Test the restore of production-sized data before you schedule either.

Laboratory exercise 6 - make it defensible.

Implement least privilege for your capstone: a migration owner, a read-write runtime role, a read-only reporting role, and default privileges so new objects inherit the design. Test the denials - connect as each role and prove the operations it must not perform fail.

Enable RLS for a multi-tenant table and demonstrate a tenant being unable to read another's rows even with a deliberately broken query. Configure TLS, require it in pg_hba.conf, and show a non-TLS connection being refused.

Partition one large table by time, demonstrate partition pruning in EXPLAIN, and drop an old partition.

Deliverable: the role and policy DDL, a test script that attempts every forbidden operation and shows it failing, your pg_hba.conf with its reasoning, a monitoring configuration naming the metrics you would alert on and their thresholds, and a deployment and cost checklist covering instance sizing, storage, backups, replicas and the upgrade path.

-- ================= Least privilege =================
-- The application does not own its tables. A compromised runtime
-- credential should not be able to drop anything.
CREATE ROLE ledger_owner NOLOGIN;
CREATE ROLE ledger_rw    LOGIN PASSWORD 'x';   -- the application
CREATE ROLE ledger_ro    LOGIN PASSWORD 'y';   -- reporting

ALTER SCHEMA ledger OWNER TO ledger_owner;
ALTER TABLE ledger.account OWNER TO ledger_owner;
ALTER TABLE ledger.entry   OWNER TO ledger_owner;

-- Close the permissive defaults.
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON DATABASE workshop FROM PUBLIC;
GRANT CONNECT ON DATABASE workshop TO ledger_rw, ledger_ro;
GRANT USAGE ON SCHEMA ledger TO ledger_rw, ledger_ro;

GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA ledger TO ledger_rw;
GRANT SELECT                 ON ALL TABLES IN SCHEMA ledger TO ledger_ro;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA ledger TO ledger_rw;
-- Note: no DELETE and no TRUNCATE for the application. A ledger does
-- not delete; it posts a reversing entry.

-- THE ONE PEOPLE FORGET. The grants above cover tables that exist
-- TODAY. Without this, every table created next month is invisible.
ALTER DEFAULT PRIVILEGES FOR ROLE ledger_owner IN SCHEMA ledger
    GRANT SELECT, INSERT, UPDATE ON TABLES TO ledger_rw;
ALTER DEFAULT PRIVILEGES FOR ROLE ledger_owner IN SCHEMA ledger
    GRANT SELECT ON TABLES TO ledger_ro;

-- ================= Row-level security =================
ALTER TABLE ledger.account ENABLE ROW LEVEL SECURITY;
ALTER TABLE ledger.account FORCE  ROW LEVEL SECURITY;
--                         ^^^^^ without FORCE the table OWNER bypasses
--                         every policy, which quietly defeats the point.

CREATE POLICY tenant_isolation ON ledger.account
    USING      (tenant_id = current_setting('app.tenant_id')::bigint)
    WITH CHECK (tenant_id = current_setting('app.tenant_id')::bigint);
--  USING      filters what can be READ
--  WITH CHECK validates what can be WRITTEN - without it a tenant can
--             insert rows belonging to another tenant.

-- The application sets this per transaction, from its own session:
-- SET LOCAL app.tenant_id = '42';
--
-- Now this returns only tenant 42's rows, even though the query asks
-- for everything:
-- SELECT * FROM ledger.account;

-- ================= Verify the denials =================
-- The assessed part of the laboratory. Every one of these must fail.
SET ROLE ledger_ro;
--   INSERT INTO ledger.entry ... ;   -- ERROR: permission denied
--   DROP TABLE ledger.account;       -- ERROR: must be owner
SET ROLE ledger_rw;
--   DELETE FROM ledger.entry;        -- ERROR: permission denied
--   ALTER TABLE ledger.entry ... ;   -- ERROR: must be owner
RESET ROLE;

-- ================= pg_hba.conf =================
--   # TYPE   DATABASE  USER       ADDRESS        METHOD
--   hostssl  workshop  ledger_rw  10.0.0.0/8     scram-sha-256
--   hostssl  workshop  ledger_ro  10.0.0.0/8     scram-sha-256
--   host     all       all        0.0.0.0/0      reject
--
-- FIRST MATCHING LINE WINS. A permissive rule above a restrictive one
-- silently disables it, and nothing warns you.
-- On the client: sslmode=verify-full. `require` encrypts but does not
-- authenticate the server, so it does not stop the attacker in the path.
SELECT name, setting FROM pg_settings
 WHERE name IN ('ssl', 'password_encryption');
SELECT usename, passwd FROM pg_shadow WHERE passwd LIKE 'md5%';  -- must be empty

-- ================= Partitioning =================
CREATE TABLE ledger.entry_p (
    id          bigint GENERATED ALWAYS AS IDENTITY,
    account_id  bigint NOT NULL,
    amount_minor bigint NOT NULL,
    created_at  timestamptz NOT NULL,
    PRIMARY KEY (id, created_at)
    --           ^^^^^^^^^^^^^^^ the partition key MUST be in every
    --           unique constraint. This is the main design constraint.
) PARTITION BY RANGE (created_at);

CREATE TABLE ledger.entry_2026_11 PARTITION OF ledger.entry_p
    FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE ledger.entry_2026_12 PARTITION OF ledger.entry_p
    FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');

-- Pruning: the plan should touch ONE partition. If it touches all of
-- them, the partition key is missing from the WHERE clause.
EXPLAIN (ANALYZE)
SELECT count(*) FROM ledger.entry_p
WHERE created_at >= '2026-11-15' AND created_at < '2026-11-20';

-- Retention in milliseconds rather than a long DELETE that bloats:
DROP TABLE ledger.entry_2026_11;
-- or keep it, detached, for archival:
-- ALTER TABLE ledger.entry_p DETACH PARTITION ledger.entry_2026_11;

-- ================= What to alert on =================
SELECT now() - pg_last_xact_replay_timestamp() AS replication_lag;
SELECT count(*) FROM pg_stat_activity
 WHERE state = 'idle in transaction'
   AND now() - state_change > interval '5 minutes';   -- holds locks, blocks vacuum
SELECT max(age(datfrozenxid)) FROM pg_database;       -- wraparound risk
SELECT last_archived_time, failed_count FROM pg_stat_archiver;
SELECT round(100.0 * sum(blks_hit) / nullif(sum(blks_hit + blks_read), 0), 2)
       AS cache_hit_pct FROM pg_stat_database;        -- want > 99

Discussion

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