Row-Level Security (RLS) is one of the most underrated features of
#Postgres.
I took challenge, writing a multi-tenant app with RLS, so you don't have to.
When writing applications for multiple customers, tenants, users, etc. our best friend is 𝑾𝑯𝑬𝑹𝑬 𝒄𝒖𝒔𝒕𝒐𝒎𝒆𝒓_𝒊𝒅 = ?, if we want it or not.
My issue is that it's way to easy to forget it on new queries. Not to talk about the cluttered source code all over the place. I just hate to repeat myself 🤣
Anyway, with Row-Level Security, it is super easy to teach PostgreSQL that a user can only access its own data. No potential leaking of information, no accidental forgetting of the WHERE-clause, no query forging. Just lock users into roles and apply access policies to the role.
Internally, Postgres will add the necessary filters to the query automatically while building and optimizing the query tree.
Create a policy, enable row-level security and query as if there is no tomorrow.
-----
CREATE POLICY customers_tenant_isolation
ON customers
FOR SELECT
TO customer
USING (customer_id::TEXT = CURRENT_SETTING('customer_id', FALSE));
ALTER TABLE customers ENABLE ROW LEVEL SECURITY;
SELECT customer_id, customer_name FROM customers;
-----
See my full blog post or find the demo app on GitHub for your convenience. I'd love to hear your thoughts on this! Please leave them in the comments 👇
- Example code:
sblk.xyz/rls-invoicing
- Blog post:
sblk.xyz/multi-tenancy-rls
Thank you to all the amazing friends and PG people that kept me in the Postgres community for years and taught me so much ❤️
I mentioned some of them on the image below. If you're looking for people to follow, here they are!
#security #rowlevelsecurity #database #dataleak #simplyblock #postgresql