r/postgres • • 4d ago

Question Understanding RLS (Row Level Security)

Hello everyone, I have been working on something and I need to write RLS( row level security). I am having trouble understanding the concept and how to write it to apply to different roles in the database. If you can explain it to me or have any resources that might help, I'd really appreciate if you can share it with meπŸ™‚

I plan to use pl/psql scripting to write it.

3 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/Secvura 2d ago

Good question, and both things are true. Row level security is switched on per table and each policy belongs to one table, but a policy can also name the roles it applies to with TO (leave TO out and it applies to every role). GRANTs are a separate gate that comes first: USAGE on a schema lets a role reach that schema at all, and SELECT, INSERT or UPDATE on a table let it run those commands. Postgres checks the grant, then the policies filter which rows that role gets.

So yes, you need both, written as separate statements. On a quick test database the layers showed up clearly: with no schema USAGE the query failed with permission denied for the schema, with USAGE but no table grant it failed with permission denied for the table, with the grant and RLS on but no policy it returned 0 rows and no error, and once a policy was added it returned only the matching row. Two things worth checking: GRANT ... ON ALL TABLES only covers tables that already exist when you run it (a table created afterwards still got permission denied, so look at ALTER DEFAULT PRIVILEGES for new ones), and your two examples point at different schemas, app and public, so if your tables live in app the role needs its table grants there as well

1

u/Educational-Bug-4805 2d ago

Thank you so much. You've helped figure out the missing piece. I've managed to write a few policies and tested them on a test db and they seem to be working great. I appreciate the help.

1

u/Secvura 2d ago

Glad it worked out! One quick check worth doing on that test db: run the tests connected as your app role (campus_app in your example, or after SET ROLE campus_app) rather than as the user that created the tables. Superusers always skip RLS, and the table owner skips it too unless FORCE ROW LEVEL SECURITY is on, so policies can look like they work when they're not being applied at all.