lin
lin

Reputation: 187

postgresql row level security with session variable

I am learning postgres row level security with session variables.

create table user_table (
    username text,
    idx integer
);
alter table user_table enable row level security;
create policy user_p on user_table for select
using (idx <= (current_setting('my.idx',true)::int));

insert into user_table values('1',1),('2',2),('3',3);

output:

# set my.idx = 2;
SET
# select * from user_table;
 username | idx
----------+-----
 1        |   1
 2        |   2
 3        |   3
(3 rows)

it should display user_table with username '1' and '2', but it shows everything. what am I missing to cause the problem?

Upvotes: 3

Views: 2540

Answers (1)

Vao Tsun
Vao Tsun

Reputation: 51446

https://www.postgresql.org/docs/current/static/ddl-rowsecurity.html

When row security is enabled on a table (with ALTER TABLE ... ENABLE ROW LEVEL SECURITY), all normal access to the table for selecting rows or modifying rows must be allowed by a row security policy. (However, the table's owner is typically not subject to row security policies.)

(emphasis mine)

checking:

db=# grant select on user_table to ro;
GRANT
Time: 24.374 ms
db=# set role ro;
SET
Time: 0.305 ms
db=> select * from user_table;
 username | idx
----------+-----
 1        |   1
 2        |   2
(2 rows)

Time: 10.557 ms
db=> set my.idx = 1;
SET
Time: 8.595 ms
db=> select * from user_table;
 username | idx
----------+-----
 1        |   1
(1 row)

Upvotes: 4

Related Questions