Postgres Row Level Security (RLS)

950 views
Skip to first unread message

Open Ocean

unread,
Mar 4, 2021, 12:21:36 PM3/4/21
to sqlalchemy
I'm trying to figure out how to add RLS to tables using sqlalchemy and alembic.

I'm changing from schema per tenant to row per tenant in a multi-tenant db.

My approach is:
- use pg setting 'tenant.id' to identify the current tenant
- add tenant column to tables with server_default=func.current_setting('tenant.id') to automatically set the tenant on insert.
- enable rls on tables: ALTER TABLE table ENABLE ROW LEVEL SECURITY
- create rls policy on tables: CREATE POLICY xxx ON table USING (tenant = current_setting('tenant.id'))
- set tenant.id at start of transaction: SET LOCAL tenant.id = current_tenant;

I don't know how to enable rls or create rls policy on the tables without adding custom sql to the alembic version file.

Is there another/better way to do this?

Thanks,

Brian Hill

Mike Bayer

unread,
Mar 4, 2021, 12:24:39 PM3/4/21
to noreply-spamdigest via sqlalchemy
this is a highly postgresql-specific set of commands so using op.execute() with the ALTER commands you need seems to be the most direct and obvious way to achieve this, I'm not sure what the downside would be?    if it's the redundancy, simply create a function in your applicaiton that is given the operations context and then runs the required functions, then Alembic version files can import that function and run it as needed.
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

Open Ocean

unread,
Mar 4, 2021, 4:20:31 PM3/4/21
to sqlalchemy
that worked great. i used the rewriter with process_revision_directives to look for tenant columns in create table, add/drop column operations and add the alter table and policy commands to the version upgrade/downgrade.
thanks,
brian
Reply all
Reply to author
Forward
0 new messages