In PostgreSQL, why can a query on a row-level-security table stop using an index, and how do LEAKPROOF functions and security_barrier views relate?
answer
- the policy runs before untrusted code
- errors can leak hidden values
- jsonb @> is not leakproof
- a superuser-only function flag
- same rule as barrier views
basics
~20 sPolicy conditions run before any user condition using a non-LEAKPROOF function, so that condition cannot drive an index scan: jsonb @> loses its GIN index for a role subject to RLS, while leakproof uuid equality keeps its index.
solid answer
~50 sPostgreSQL places policy expressions ahead of the query's own conditions, so a user-supplied function never sees a row the policy hides. Only functions marked `LEAKPROOF` (`pg_proc.proleakproof`), or ones that receive no column values, may run earlier. A function that can raise an error or log depending on its input could reveal hidden values, so it is not leakproof. The planner therefore cannot use an index for a condition whose operator is in the index's operator family but whose function is not leakproof. `jsonb_contains`, behind `@>`, is not, so a GIN index on `tasks.metadata` is skipped and the condition becomes a filter after the policy. Most equality and comparison operators (`uuid_eq`, `texteq`, `int8lt`) are leakproof. Views created `WITH (security_barrier)` follow the same rule. Only a superuser can mark a function `LEAKPROOF`. Check plans with `EXPLAIN` as the application role. In PostgreSQL 18, psql's `\do+` and `\dAo+` show the flag.
code
sql · 12 linesCREATE INDEX tasks_metadata_gin ON tasks USING gin (metadata);
SET ROLE app_rw;
EXPLAIN SELECT id, title FROM tasks
WHERE metadata @> '{"priority": "urgent"}';
-- expect no scan on tasks_metadata_gin: @> shows up as a Filter
RESET ROLE;
SELECT p.proname, p.proleakproof
FROM pg_operator o
JOIN pg_proc p ON p.oid = o.oprcode
WHERE o.oprname = '@>' AND o.oprleft = 'jsonb'::regtype;go deeper
Know that RLS policies run before your own WHERE conditions, and that this can change the plan.
Explain what LEAKPROOF promises, why error-raising functions fail it, and how security_barrier views apply the same ordering rule.
Diagnose a lost index as the application role, read proleakproof for the operator, and fix it by indexing the policy predicate rather than flagging functions.
Weigh the performance cost of barrier semantics against the leak risk of LEAKPROOF flags, and own who may set them.
## Why evaluation order is a security rule The planner normally evaluates cheap conditions first. On a protected table that would be dangerous. Suppose a role may see only its organization's `tasks` and writes: ```sql SELECT * FROM tasks WHERE leaky(title, org_id); ``` If `leaky` were a cheap PL/pgSQL function that runs `RAISE NOTICE` on its arguments and returns true, and the planner ran it before the policy, every hidden row would be printed. Built-in functions can leak the same way: many casts put the input value into their error message. PostgreSQL therefore treats policy predicates as **security quals** and evaluates them before any user condition that passes the table's columns to untrusted code. ## What LEAKPROOF promises `LEAKPROOF` is a function property, stored in `pg_proc.proleakproof`. It promises that the function has no side effects and reveals nothing about its arguments except through its return value. A function that errors for some inputs and not others, or that includes its input in an error message, is **not** leakproof. Leakproof functions may run before the policy, because calling them on hidden rows tells the caller nothing. | Function (operator) | Leakproof in 18 | Why it matters | |---|---|---| | `uuid_eq` (`uuid = uuid`) | yes | the tenant predicate stays index-friendly | | `texteq` (`text = text`) | yes | equality lookups on names keep their index | | `int8lt` (`bigint < bigint`) | yes | range conditions on ids still use a B-tree | | `jsonb_contains` (`jsonb @> jsonb`) | no | GIN containment searches lose the index | | `textlike` (`text LIKE text`) | no | pattern conditions wait for the policy | | `int4div` (`int / int`) | no | division by zero raises an error that depends on the input | Two rules limit the damage: - A function that receives **no column values** from the protected table, such as `now()` or `current_setting(...)`, needs no flag to run early. - **Only a superuser** can set `LEAKPROOF`, with `CREATE FUNCTION` or `ALTER FUNCTION`. A wrong flag silently breaks every barrier that relies on it. ## The index consequence The manual spells out the cost. An index scan cannot be chosen for a condition whose operator belongs to the index's operator family when the operator's function is not leakproof. In a multi-tenant project-management app: - `tasks_metadata_gin` indexes `tasks.metadata` (`jsonb`). - As the owner, `WHERE metadata @> '{"priority": "urgent"}'` can use the GIN index. - As `app_rw`, a role subject to policies, the same query applies the policy first and evaluates `@>` as a filter on the rows the policy admits. The GIN index goes unused. The policy predicate itself is usually fine, because `org_id = ...` uses leakproof uuid equality and can drive an index on `org_id`. ## security_barrier views: the same rule for views A view whose `WHERE` hides rows can be bypassed by the same trick: the planner pushes a cheap user function below the view's own condition. `CREATE VIEW ... WITH (security_barrier)` forbids that. The view's conditions run before any non-leakproof user condition, exactly as a table's policies do. The manual warns that such views may perform far worse, and that is why the option is off by default. Whose privileges a view checks, the `security_invoker` option, is a separate subject owned by the views leaf. ## Diagnosing and fixing 1. Reproduce as the application role (`SET ROLE app_rw`). The owner and superusers bypass the policies, so their plans are misleading. 2. Run `EXPLAIN` and look for the user condition as a `Filter` instead of an index condition. 3. Check the operator's function: `pg_proc.proleakproof`, or in 18 psql's `\do+` and `\dAo+`. 4. Prefer a fix that leaves the barrier intact. Make the **policy** predicate selective and indexed (an index leading with `org_id`), so the non-leakproof filter runs over one tenant's rows only. 5. Mark a function `LEAKPROOF` only after reading its code paths for input-dependent errors. That is a superuser's audited decision, not a tuning knob. ## What the barrier does not hide The guarantee is narrow. Hidden rows' contents are not passed to untrusted functions, but a user can still learn something from `EXPLAIN` output, from timings, or from statistics-driven plan choices. Policies were never meant to stop those covert channels.
- Why not simply mark jsonb_contains LEAKPROOF to get the GIN index back?Only a superuser can, and the flag promises that the function never reveals anything about its arguments except through its result, errors included. A wrong flag weakens every RLS table and `security_barrier` view at once, and nothing reports the leak. Prefer making the policy predicate itself indexed and selective, so the filter runs over one tenant's rows.
- Does the planner refuse every function in a user's WHERE clause on an RLS table?No. Leakproof functions may run before the policy, and so may functions that receive no column values from the protected table, such as `now()` or `current_setting(...)`. Only conditions that pass the table's columns to non-leakproof code must wait for the policy.
- Row-level security never changes the plan, only which rows come back
- Any IMMUTABLE function is automatically treated as leakproof
- A function's owner can mark it LEAKPROOF
- security_barrier makes a view check the caller's privileges
- EXPLAIN as the table owner shows the plan the application gets
Assumes PostgreSQL 18; psql's \df+, \do+, \dAo+ and \dC+ show the leakproof flag only from 18, so on 17 query pg_proc.proleakproof directly.