Skip to content

supatype_mask

Per-column read masking and write rejection, driven by security labels and enforced in the planner.

SECURITY LABEL FOR supatype ON COLUMN public.posts.salary
IS 'MASK READ public.can_read_posts__salary WRITE public.can_write_posts__salary';

From then on, every reference to posts.salary is rewritten to the expression below. That covers the target list, a WHERE clause, a view, a subquery, COPY posts TO, and the column’s slot in a whole-row reference such as to_jsonb(posts):

CASE WHEN public.can_read_posts__salary(posts) THEN posts.salary ELSE NULL END

and every assignment to it is rewritten to preserve, accept or reject per row.

Reads mask, writes reject. A rejected write is an error the caller should see; an unauthorised read is a null.

Why a planner hook and not privileges or views

GET /posts with no select parameter sends SELECT posts.*. That names every column, so it succeeds only if the role holds SELECT on every column. A column REVOKE makes PostgREST answer 403 for the whole table rather than returning a filtered row. So a read restriction cannot be a privilege: the column has to be present and masked.

Masking is a per-row expression, and the only things in Postgres that put an expression where a column was are a view and a query rewrite. CREATE VIEW v AS SELECT * FROM t does not store *: Postgres expands it at creation and stores a fixed target list, so a column added later is invisible to the API until something re-runs CREATE OR REPLACE VIEW. Every view is a snapshot of the column list.

That leaves the rewrite, which also reaches psql, logical-decoding catch-up queries and anything else talking to the database rather than only what PostgREST is pointed at.

The rules live in SQL, not in C

The extension does not implement a rule language. It calls the predicate the label names. Those functions are generated by the Supatype schema engine from the same access AST that produces the RLS policies, so a UI, a policy and a mask are one expression rather than three that drift. This is what keeps a security-critical C extension small.

A predicate takes the table’s composite type and returns boolean:

CREATE FUNCTION can_read_posts__salary(posts posts) RETURNS boolean
LANGUAGE sql STABLE AS $$
SELECT author_id = auth.uid() FROM (SELECT ($1).*) AS posts;
$$;

Row-independent predicates (once per scan, not once per row)

The whole-row form above is called once per row per masked column. That is correct for a value-dependent rule (author_id = auth.uid()), but wasteful for the common case where the answer depends only on the session (a role- or claim-level rule that ignores the row). On a full scan of a masked table that is the dominant cost: a predicate doing a per-row lookup can make the scan ~100× the unmasked cost.

Declare such a predicate with no arguments and supatype_mask emits it as an uncorrelated (SELECT pred()), which the planner hoists to an InitPlan evaluated once per scan:

CREATE FUNCTION can_read_posts__salary() RETURNS boolean
LANGUAGE sql STABLE AS $$ SELECT auth.jwt_role() = 'hr' $$;

Measured on a 100k-row table, 3 masked columns, with a per-current_user table lookup as the predicate body: 1117 ms per-row → 18 ms row-independent (96× → 1.7×, i.e. the cost of the CASE branches alone). The InitPlan is still evaluated at run time on every execution, and IMMUTABLE is still refused, so a plan cached for one caller re-runs it for the next caller’s session. There is no cross-caller leak, the same guarantee as the per-row form.

The whole-row overload wins when both pred(t) and pred() exist, so making a rule row-independent is opt-in by the predicate’s signature and fully backward compatible.

Install

Bundled in the supatype/postgres image. Two halves, and both are needed:

# postgresql.conf -- registers the label provider and the hooks
shared_preload_libraries = '..., supatype_mask'
-- supplies the rejection function
CREATE EXTENSION supatype_mask;

Preloading without the extension still masks; a rejection then raises supatype_mask.deny() is not available instead of the intended error. The reverse, the extension without the preload, does nothing at all. Dropping the extension therefore does not unmask anything, which is the right way round.

shared_preload_libraries, not session_preload_libraries: see below.

Configuration

GUCDefaultContextNotes
supatype_mask.exempt_rolesservice_rolePGC_SIGHUPComma-separated. Read masked columns unmasked.
supatype_mask.enabledonPGC_SIGHUPBreak-glass. Logs at LOG level on every backend start while off.

Exemption is an explicit role list plus superusers, matched against the current effective role. Never “is the table owner”: ownership is incidental to whether a caller should read a masked column, and PostgREST connecting as the owner is precisely the case that would make the whole mechanism a no-op.

Tamper resistance

Both settings are PGC_SIGHUP and the library is in shared_preload_libraries, so there is no SQL statement that disables masking for a role, a database or a session, not even for a superuser. This is deliberate, and it is the same posture pg_guard takes with all of its own settings.

The reasoning is an asymmetry: every other way to stop a column being masked leaves a trace. Dropping a label or a predicate is a schema change the differ reports on the next push, and the push re-asserts it. A GUC leaves nothing. So the GUC is the weakest link and has to be the hardest to reach.

Two routes were open before and are now closed:

RouteWhy it matteredNow
ALTER ROLE authenticated SET supatype_mask.enabled = offPermanent, invisible, unmasks every column for the whole API surface in one statementPGC_SIGHUP, so refused
ALTER ROLE authenticated SET session_preload_libraries = 'pg_guard'Narrows the preload for just the data-plane role, so the library never loads for itLibrary is in shared_preload_libraries (PGC_POSTMASTER), which cannot be set per role or per database

What remains is ALTER SYSTEM SET shared_preload_libraries plus a server restart: superuser only, written to postgresql.auto.conf on disk, and it takes every other preloaded extension down with it. Loud and global rather than silent and targeted, which is the distinction that matters. A superuser is exempt from masking anyway, and can equally DISABLE ROW LEVEL SECURITY; this is no weaker than RLS against the same actor.

Behaviour

StatementResult
SELECT, any referencemasked to NULL per row
WHERE, ORDER BY, GROUP BY, joins, subqueriesmasked, so a qual cannot be used as an oracle
sum(salary), max(salary), string_agg(salary::text, ',') etc.rejected per unreadable row, so a total is either correct or an error, never quietly partial
aggregate over a subquery (jsonb_agg((SELECT q.salary FROM t q ...)))the subquery’s own reads mask to NULL; the aggregate consumes what the subquery returns
window aggregate (sum(salary) OVER (...), count(*) FILTER (WHERE salary > 0) OVER ())rejected per unreadable row, like sum(salary)
window PARTITION BY / ORDER BY on the column, ranking functions, lag, first_valuemasked to NULL: unreadable rows tie, so no rank or order reaches the caller
UPDATE, caller may writeaccepted
UPDATE, caller cannot readold value preserved silently
UPDATE, caller can read but not writerejected
INSERT, caller may write the valueaccepted
INSERT, caller may not write the valuerejected, unless it equals the column default
INSERT, column left out, DEFAULT, NULL, or the default’s own valuethe column default
COPY t TOrewritten through the planner, so masked
COPY t FROMrefused
MERGErefused
whole-row reference (to_jsonb(t), SELECT t FROM t, f(t))the masked row: each masked column in it masked as above
whole-row reference inside an aggregate (jsonb_agg(t))rejected per unreadable row, like sum(salary)

The UPDATE round-trip is the case this exists for. A client GETs a row, salary comes back null because it is masked, the user edits the title, and the client PATCHes the whole object back including salary: null. Without coercion the real salary is gone, silently, with a 200. “Could not read it” and “saw it and changed it” have to be distinguishable, or one of them destroys data and the other breaks whole-object clients.

An aggregate is scoped to its own query level. A column consumed by an aggregate directly, or read from inside a subquery the aggregate wraps but owned by the aggregate’s level, is rejected per unreadable row. A column a subquery reads for itself is masked like any other read, because the aggregate only sees what the subquery returns. That is the shape pg_graphql uses for a nested relation (the child connection is a subquery inside the parent’s jsonb_agg), and it is why nested relations work over masked tables. The cost is that sum((SELECT q.salary FROM t q WHERE ...)) skips the rows the subquery masked rather than erroring; nothing the role may not read is disclosed either way.

A whole-row reference is rebuilt from its columns. t becomes ROW(t.id, <mask of t.salary>, ...)::t, so a PostgREST computed column f(t), to_jsonb(t) and SELECT t FROM t see exactly what a column-by-column select would. On the nullable side of an outer join an unmatched row stays a NULL row.

INSERT judges the values stored. There is no old row, so the write predicate is called with the row the statement stores, ROW(<each stored value>)::t, as an RLS WITH CHECK judges a new row. A rule that reads the row (Owner<"author_id">) therefore lets a user set a guarded column on a row they own, and a value filled in by a default (owner_id DEFAULT auth.uid(), a gen_random_uuid() or serial key) is what the rule reads. To judge exactly what is stored, the statement’s values are moved into a LATERAL subquery and each masked column’s default into a second one, so every value is evaluated once per row: nothing is drawn from a sequence twice.

A value the caller wrote that the rule refuses is an error (42501, naming the table and column), never quietly replaced: replacing it with the default lost every value such a rule guards. A column the caller did not write takes its default and is not judged: one left out, named as DEFAULT, sent as NULL, or sent as the default’s own value. The last is what PostgREST’s Prefer: missing=default sends for a key a row leaves out, so an admin-only verified DEFAULT false left out of a bulk POST, or sent as false, is accepted from anyone, while true is refused. A volatile default is never equal to a value sent, so it is not compared.

Fail-closed states

Every undecidable case masks rather than exposes:

  • a label naming a predicate that does not exist
  • a predicate that does not return boolean
  • a predicate declared IMMUTABLE (see below)
  • an unparseable label

Each logs a WARNING naming the column. A malformed label is normally rejected at SECURITY LABEL time by the provider’s validation callback, so these states mean the label was written while the library was not loaded.

Why IMMUTABLE is refused. A masking predicate reads the caller’s claims, so it is STABLE at best. Declared immutable, the planner is entitled to fold it wherever its arguments are constant (as they are on an INSERT of literal values), and a folded answer baked into a cached plan is a cross-caller leak. Five lines of catalog check; the whole design rests on them.

What this does not cover

  • Logical replication. WAL records are not query results, so nothing here filters them. Realtime evaluates the same can_read_* functions against the WAL record cast to the table’s composite type, in the subscriber’s transaction.
  • Inference through error messages. A non-leakproof operator applied to the predicate’s own inputs can still disclose something through an error. References to the masked column itself are safe: the substitution happens at the Var, so the real value never reaches any operator.
  • Exempt roles. service_role and superusers see everything, by design.
  • Postgres before 17. The rewrite touches Var, Query and the node walkers, which are not stable across majors.

Tests

Terminal window
docker build -t supatype-mask-build -f test/Dockerfile test
docker run --rm -v "$PWD:/src" -w /src supatype-mask-build bash -c \
"make install && chown -R postgres /tmp && su postgres -c 'SKIP_INSTALL=1 bash test/run-tests.sh supatype_mask'"

The server cannot run as root, hence the two-step: install as root, test as postgres.

The suite asserts the things the design was gated on, including a prepared statement executed under force_generic_plan as two different identities giving two different answers. That one is non-negotiable: a plan built for an admin and reused for a non-admin would leak the column with no error and no log line.

Licence

Apache 2.0, see LICENSE. Deliberately not the repository root’s PostgreSQL License: this directory is original work intended to be publishable to PGXN on its own terms, the same arrangement pg_guard has.