Row-Level Security (RLS) in SQLAlchemy.
Project description
FastAPI Row Security 🚣♂️
Row-Level Security (RLS) in SQLAlchemy for PostgreSQL with Row Security Policies:
- Restrict access to specific rows 🔒 minimizing unauthorized data exposure.
- Perfect for Scalability and Multi-Tenancy: keep the data playground organized 🏢, ensuring each tenant plays in their own sandbox.
Warning Understand that the database superuser bypasses all permission checks, except the right to log in. This is a dangerous privilege and should not be used in combination with RLS.
Installation
Use pip to install from PyPI:
pip install fastapi-rowsecurity
Basic Usage
In your SQLAlchemy model, create an attribute named __rls_policies__
that is a list of Permissive
or Restrictive
policies:
from fastapi_rowsecurity import Permissive, register_rls
from fastapi_rowsecurity.principals import Authenticated, UserOwner
Base = declarative_base()
register_rls(Base) # <- create all policies
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True)
title = Column(String, index=True)
owner_id = Column(Integer, ForeignKey("users.id"))
owner = relationship("User", back_populates="items")
__rls_policies__ = [
Permissive(expr=Authenticated, cmd="SELECT"),
Permissive(expr=UserOwner, cmd=["INSERT", "UPDATE", "DELETE"]),
]
The above implies that any authenticated user can read all items; but can only insert, update or delete owned items.
expr
: any Boolean expression as a string;cmd
: any command ofALL
/SELECT
/INSERT
/UPDATE
/DELETE
.
Next, attach the current_user_id
(or other runtime parameters that you need) to the user session:
# ... def get_session() -> Session:
session.execute(text(f"SET app.current_user_id = {current_user_id}"))
Find a simple example in the .
Backlog first release
- Change policies when model changes (prio!!)
- Documentation
then ...
- Support for Alembic
- When item is tried to delete, no error is raised?
- Python 3.11
- Coverage report
Final note
At the moment this module is work-in-progress and therefore experimental. All feedback and ideas are 100% welcome! So feel free to contribute or reach out to me!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for fastapi-rowsecurity-0.1b2.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5792b5d3e73edb1c418d1e67649a9ebecd2a20da44c2ef2ed5f25ce6a7e331f6 |
|
MD5 | 4e05d996e3e7987c1e5cf07722e7688d |
|
BLAKE2b-256 | 2e160418b4885ea44267bd1ce9c3966cc89cbb36b6111c948b9bae0d3920e848 |
Hashes for fastapi_rowsecurity-0.1b2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | eb1b99102c4820ce1e3199fe0f07ed4918777bfeb3da269294a2cdb7aef099d0 |
|
MD5 | fd0d86e9eaec8a163aa71e696b5a945b |
|
BLAKE2b-256 | 1aa377b72071153add040fa7fd48308f31ec7d2d1b0ddc39c2df5bbe19c1cbd3 |