COPY FROM with RLS

Поиск
Список
Период
Сортировка
Искать

COPY FROM with RLS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
hi.

While working on other COPY related patches, I wonder
whether it's doable to implement RLS for COPY FROM.

COPY FROM is more simple that INSERT. we don't need to consider
INSERT RETURNING and INSERT ON CONFLICT DO UPDATE,
also no need to worry about MERGE ... INSERT.
we also don't need to consider SELECT privilege.
security policy only applies to table and partitioned tables, so don't
need to worry about
VIEW INSTEAD OF TRIGGER and foreign tables.

However, there's another complication that makes implementation difficult — a
policy can contain a subquery.
I'm not sure how to handle that properly, so error out whenever a policy
contains a sublink/subquery. (maybe it's doable, seems hard....).


If we don’t need to handle policies containing subquery cases, then the
implementation seems pretty straightforward:
1. get_row_security_policies to get all these WCO
2. initialize these WCO exprstate and pass WCO, WCO exprstate to
resultRelInfo->ri_WithCheckOptions and
resultRelInfo->ri_WithCheckOptionExprs
3. call ExecWithCheckOptions in CopyFrom

to get get_row_security_policies work, I need to invent a Query and
RangeTblEntry node.
similar to ExecInsert, i placed ExecWithCheckOptions right above
ExecConstraints.

To support partitioned tables, I needed to produce a ModifyTable node.  so that
ExecInitPartitionInfo can populate each leaf partition’s ResultRelInfo with the
relevant ri_WithCheckOptions and ri_WithCheckOptionExprs.
(this part feels like a hack, but since we only care about
ModifyTable.withCheckOptionLists so the implication is limited, i think).

anyway, please check the attached patch for COPY FROM with RLS.

Re: Re: COPY FROM with RLS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Tue, Jun 30, 2026 at 9:20 AM Yilin Zhang  wrote:
>
> Hi, I found another issue with the v2 patch.
> When running COPY FROM against a partitioned table with RLS enabled, ExecSetupPartitionTupleRouting gets invoked twice,
> which creates two separate sets of PartitionTupleRouting structures.
> One of these sets never gets cleaned up, and PostgreSQL’s ResourceOwner mechanism catches this and emits the following warnings:
>
>   WARNING:  resource was not closed: relation "rls_part_1"
>   WARNING:  resource was not closed: relation "rls_part_2"
>
> Best regards,
> --
> Yilin Zhang
>

Hi.
While v2 has extensive failure test cases, it doesn't have a single
successful test case,
that's why this issue wasn't found.
The 2 issues you reported are fixed in the attached v3.

Also, previously in v2:
+COPY r1 FROM STDIN WITH (DELIMITER ','); -- fail
+ERROR:  new row violates row-level security policy "p2" for table "r1"
+CONTEXT:  COPY r1, line 1: "4"

it's better to remove the CONTEXT line.
because ExecWithCheckOptions has comments like:
/*
 * For WITH CHECK OPTIONs coming from views, we might be
 * able to provide the details on the row, depending on
 * the permissions on the relation (that is, if the user
 * could view it directly anyway).  For RLS violations, we
 * don't include the data since we don't know if the user
 * should be able to view the tuple as that depends on the
 * USING policy.
 */



--
jian
https://www.enterprisedb.com/

Re: COPY FROM with RLS

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Fri, Sep 11, 2026 at 1:21 AM Bryan Green  wrote:
>
> v15 checks out on the v3 items.  Crash is gone on both an assert and a
> non-assert build, context is right, the rule cases error instead of
> redirecting, and quoting is fixed.
>
> The new one is the result of a forgotten guard.  The WCO quals aren't in
> the volatile test that forces CIM_SINGLE, so under multi-insert a
> self-referential policy doesn't see the still-buffered rows and accepts
> ones a plain INSERT would reject.
>
>   CREATE FUNCTION under_quota(o text) RETURNS bool LANGUAGE plpgsql VOLATILE
>     AS $$ BEGIN RETURN (SELECT count(*) FROM q WHERE owner = o) < 3; END $$;
>   CREATE POLICY ins ON q FOR INSERT WITH CHECK (under_quota(owner));
>
> INSERT of ten rows stops at the fourth.  COPY takes all ten.  A no-op
> BEFORE ROW trigger makes COPY stop at four as well, so it's the
> batching.  Probably wants ri_WithCheckOptions in that CIM_SINGLE test,
> or just forced under RLS.
>

+ foreach_node(WithCheckOption, wco, resultRelInfo->ri_WithCheckOptions)
+ {
+ if (contain_subplans(wco->qual) ||
+ contain_volatile_functions(wco->qual))
+ {
+ volatile_wco = true;
+ break;
+ }
+ }
Make volatile expression and sub-select fall back to CIM_SINGLE should be fine.

> The  wording "any rule that would apply to an INSERT" isn't quite right
> either.  A conditional DO INSTEAD NOTHING stays one QSRC_ORIGINAL query
> and slips the three screens, so COPY inserts the row that would have
> dropped under INSERT with the rule.
>

We can use RelationData->rd_rules to check if a relation has rules
defined on it or not.

> Also, relname_only wraps the whole ExecWithCheckOptions call, so a
> non-violation error from a policy expression loses the "line x".  This
> is because relname_only is true for anything the call raises, including
> errors that are not due to policy rejection.  Maybe set the flag only
> around the violation report instead of the whole evaluation?
>
I am not sure about "non-violation error from a policy expression".
Currently check constraint violations produce an error line, but RLS
violations do not.



--
jian
https://www.enterprisedb.com/

Re: COPY FROM with RLS

От:
Kirill Reshke <reshkekirill@gmail.com>
Дата:
On Thu, 24 Sept 2026 at 00:06, jian he  wrote:
>
> On Fri, Sep 11, 2026 at 1:21 AM Bryan Green  wrote:
> >
> > v15 checks out on the v3 items.  Crash is gone on both an assert and a
> > non-assert build, context is right, the rule cases error instead of
> > redirecting, and quoting is fixed.
> >
> > The new one is the result of a forgotten guard.  The WCO quals aren't in
> > the volatile test that forces CIM_SINGLE, so under multi-insert a
> > self-referential policy doesn't see the still-buffered rows and accepts
> > ones a plain INSERT would reject.
> >
> >   CREATE FUNCTION under_quota(o text) RETURNS bool LANGUAGE plpgsql VOLATILE
> >     AS $$ BEGIN RETURN (SELECT count(*) FROM q WHERE owner = o) < 3; END $$;
> >   CREATE POLICY ins ON q FOR INSERT WITH CHECK (under_quota(owner));
> >
> > INSERT of ten rows stops at the fourth.  COPY takes all ten.  A no-op
> > BEFORE ROW trigger makes COPY stop at four as well, so it's the
> > batching.  Probably wants ri_WithCheckOptions in that CIM_SINGLE test,
> > or just forced under RLS.
> >
>
> + foreach_node(WithCheckOption, wco, resultRelInfo->ri_WithCheckOptions)
> + {
> + if (contain_subplans(wco->qual) ||
> + contain_volatile_functions(wco->qual))
> + {
> + volatile_wco = true;
> + break;
> + }
> + }
> Make volatile expression and sub-select fall back to CIM_SINGLE should be fine.
>
> > The  wording "any rule that would apply to an INSERT" isn't quite right
> > either.  A conditional DO INSTEAD NOTHING stays one QSRC_ORIGINAL query
> > and slips the three screens, so COPY inserts the row that would have
> > dropped under INSERT with the rule.
> >
>
> We can use RelationData->rd_rules to check if a relation has rules
> defined on it or not.
>
> > Also, relname_only wraps the whole ExecWithCheckOptions call, so a
> > non-violation error from a policy expression loses the "line x".  This
> > is because relname_only is true for anything the call raises, including
> > errors that are not due to policy rejection.  Maybe set the flag only
> > around the violation report instead of the whole evaluation?
> >
> I am not sure about "non-violation error from a policy expression".
> Currently check constraint violations produce an error line, but RLS
> violations do not.
>
>
>
> --
> jian
> https://www.enterprisedb.com/

Hi!
Looks like Bryan point about losing line num is still present in v16?

reshke=# -- run as superuser
CREATE ROLE u1 LOGIN;
CREATE TABLE t7 (id int, v text);
CREATE FUNCTION t7_div(id int) RETURNS int LANGUAGE sql STABLE
  AS $$ SELECT 1/(id-3) $$;
ALTER TABLE t7 ENABLE ROW LEVEL SECURITY;
CREATE POLICY t7_p ON t7 FOR INSERT WITH CHECK (t7_div(id) IS NOT NULL);
GRANT INSERT ON t7 TO u1;
GRANT EXECUTE ON FUNCTION t7_div(int) TO u1;

SET SESSION AUTHORIZATION u1;
COPY t7 FROM STDIN WITH (DELIMITER ',');

CREATE ROLE
CREATE TABLE
ERROR:  function "t7_div" already exists with same argument types
ALTER TABLE
CREATE POLICY
GRANT
GRANT
SET
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself, or an EOF signal.
>> 1,a
>> 3,boom
>> \.
ERROR:  division by zero
CONTEXT:  COPY t7

Line number is missing

Also looks like the rule guard is broader than needed.

RLS table with a single ON DELETE rule  ->  COPY FROM rejected

CREATE TABLE t (id int);
ALTER TABLE t ENABLE ROW LEVEL SECURITY;
CREATE POLICY p ON t FOR INSERT WITH CHECK (id > 0);
GRANT INSERT ON t TO u1;
CREATE RULE r_del AS ON DELETE TO t DO INSTEAD NOTHING;   -- never
applies to COPY

SET SESSION AUTHORIZATION u1;
COPY t FROM STDIN;
1
\.

ERROR:  cannot copy to table "t"
DETAIL:  COPY FROM is not supported on tables with rules when
row-level security is enabled.
HINT:  Use INSERT statements instead.

Without RLS it works

db3=# CREATE TABLE t (id int);
CREATE TABLE
db3=# CREATE RULE r_del AS ON DELETE TO t DO INSTEAD NOTHING;
CREATE RULE
db3=# GRANT INSERT ON t TO u1;
GRANT
db3=# SET SESSION AUTHORIZATION u1;
COPY t FROM STDIN;
SET
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself, or an EOF signal.
>> 1
>> \.
COPY 1

Is there reason for such restriction?

-- 
Best regards,
Kirill Reshke


Re: COPY FROM with RLS

От:
Joao Rito <joaovictor.rito@gmail.com>
Дата:
Hi Jian,

I reviewed v16 and ran some tests. I tried to look at areas that were not
covered in the thread yet.

Setup: master at 952bab8b74, Debian bookworm container, built with
--enable-cassert --enable-debug. v16 applies with small offsets, the build
has no warnings, and make check passes (243 tests). I ran the same probe
script on master and on the patched build. As expected, on master every
non-owner COPY FROM below fails with "COPY FROM not supported with row-level
security".

Things that work the same as INSERT:
- Triggers: with BEFORE/AFTER ROW, BEFORE STATEMENT and an AFTER STATEMENT
  trigger with REFERENCING NEW TABLE, a 3-row COPY fires each row trigger 3
  times, each statement trigger once, and the transition table has 3 rows.
  INSERT gives the same counts.
- A BEFORE ROW trigger that changes the owner column so the row fails the
  policy: COPY fails with the RLS error, same as INSERT. So the check runs
  on the row after the triggers.
- Partitioned table with a permissive policy on the parent and a stricter
  INSERT policy on the leaf: COPY into the parent succeeds and COPY into the
  leaf fails, the same as INSERT through the parent and the leaf.
- FORCE ROW LEVEL SECURITY: the owner's COPY is checked. A BYPASSRLS role is
  not checked.
- Column privileges: with only INSERT (a), COPY t (a) works and COPY t (a,
  secret) fails with "permission denied", same as master. So the DEFAULT
  VALUES statement does not need extra privileges.
- COPY ... WHERE: a row removed by WHERE that would fail the policy does not
  raise an error.
- A deferred constraint trigger fires at commit.

1. The internal INSERT is visible to monitoring extensions

With pg_stat_statements.track = 'all', one COPY FROM on an RLS table leaves
two entries:

 toplevel | calls | rows |                query
----------+-------+------+-------------------------------------
 t        |     1 |    3 | COPY t (a) FROM STDIN
 f        |     1 |    0 | INSERT INTO public.t DEFAULT VALUES

With auto_explain.log_nested_statements = on, the server log also gets a
plan for it:

LOG:  duration: 0.000 ms  plan:
Query Text: INSERT INTO public.t DEFAULT VALUES
Insert on t  (cost=0.00..0.01 rows=0 width=0)
  ->  Result  (cost=0.00..0.01 rows=1 width=36)

This comes from running the query through
ExecutorStart/ExecutorFinish/ExecutorEnd, which call the executor hooks.
With track = 'top' only the COPY entry is there. It is not wrong, but a DBA
who sees "INSERT INTO public.t DEFAULT VALUES" with rows = 0 may think some
application ran it. Maybe this is fine and only needs a comment in the code.
Or maybe the query should not get a queryId, so pg_stat_statements skips it.
I am not sure which is better, so I wanted to mention it.

2. ON_ERROR ignore and the missing line number

COPY ... WITH (ON_ERROR ignore) skips a bad input value, but an RLS
violation still aborts the whole COPY. I think that is right, because
ON_ERROR only covers soft input errors. But the error only shows "CONTEXT:
COPY t", without the line number, so with a large file there is no easy way
to find the row that failed. This is the same point Kirill raised for errors
inside a policy function. I think it applies to the violation error too, and
it is probably the most common error users will see from this feature.

3. Performance

1M rows from a file, fsync = off, a simple stable policy (owner =
current_user), times for one COPY:
- table owner, RLS not applied: 329 ms
- non-owner, RLS applied: 440 ms
- non-owner, INSERT ... SELECT of the same rows: 1170 ms

So multi-insert batching still works with a non-volatile policy, and COPY
stays much faster than the INSERT workaround.

Regards,
Joao Rito


FAQ