Multi-Tenant Security for FastAPI
Building a multi-tenant SaaS requires more than just adding a tenant_id column; it requires a bulletproof architecture that prevents data leaks by design. This skill generates a production-ready multi-tenancy core for FastAPI and SQLAlchemy that implements row-level isolation at the database layer.
What it does
- Automatic Row-Level Isolation: Uses a SQLAlchemy event listener to automatically inject
WHERE tenant_idinto every query. Developers literally cannot forget to scope a read. - "Secure by Default" Failure: The system defaults to a null tenant context. If a tenant isn't identified, queries return zero rows instead of leaking data across tenants.
- Auditable Escape Hatches: Provides an explicit
no_tenant_scope()context manager for cross-tenant admin operations, requiring a logged reason for every bypass. - Cloudflare Access Integration: Bundles JWT authentication with fallbacks for local development and trusted-network header modes.
- Role-Based Access Control (RBAC): Includes three pre-defined roles (Owner, Partner, Client Viewer) with logic to handle global vs. scoped access permissions.
Why use this skill?
Instead of manually writing .filter(tenant_id=...) on every single endpoint—a process prone to human error—this skill applies isolation globally. It solves the "noisy neighbor" problem and data leakage concerns before you write your first business logic route. It is based on the proven architecture used in high-scale SaaS products.
Supported Stack
- FastAPI (Async)
- SQLAlchemy 2.0+ (Async)
- Pydantic v2 (Settings & Validation)
- Cloudflare Access (Auth)
- PostgreSQL (Shared database, row-level isolation)
Built by Nex AI. More skills and info at nex-ai.be and slopsome.com.