Roadmap¶
Last updated: 2026-11-11
Priorities may shift based on community feedback. Have a suggestion? Open an issue.
Status markers: [ ] Planned | [~] In Progress | [x] Done
v1.2.1 — Housekeeping & Debuggability¶
Quick wins that improve the debugging and development experience.
-
[x] Fix:
TENANT_FK_FIELDsignal handler — The_add_tenant_fkhandler hardcodes"tenant"when checking whether a model already defines the FK field, but uses the configuredTENANT_FK_FIELDwhen adding it. This causes duplicate FK attempts when a custom field name is configured and the model already defines that field. Why: Real bug affecting anyone using a customTENANT_FK_FIELDname. -
[x] Public API surface cleanup — Remove internal helpers from
__all__and_LAZY_IMPORTS: raw state functions (get_current_tenant_id,set_current_tenant_id,get_rls_context_active, etc.) and exception classes (NoTenantContextError,RLSConfigurationError,RLSTenantError). Keep them importable from their actual modules but stop re-exporting from the top-level package. Why: These are internal implementation details. Exporting them encourages direct state manipulation instead of using the safe context manager APIs. -
[x] Docs accuracy pass — Correct inaccuracies in CHANGELOG, SECURITY.md, and README that reference features differently from the actual implementation. Why: Misleading docs erode trust and cause integration mistakes.
-
[x] Code comment consistency — Add module docstrings to management package
__init__.pyfiles, safety comments on f-string SQL incheck_rlscommand, and explanatory text totype: ignorecomments inmanagers.py. Why: Makes the codebase easier to audit and contribute to. -
[x]
__repr__on key classes — Add__repr__()toRLSConstraint,RLSM2MConstraint, andRLSTenantsConfigfor better output in tracebacks, Django shell sessions, and test failures. Why: These objects currently show as<RLSConstraint object>which tells you nothing when debugging migration or configuration issues. -
[x] DEBUG-level logging — Add
logger.debug()calls to middleware (GUC set/clear),tenant_context/admin_context(entry/exit), andregister_m2m_rls()(skip reasons). Uses Django's logging framework — zero output unless the user enables DEBUG. Why: When things go wrong, there is no trace of what RLS context was set or why a model was skipped during M2M auto-detection. -
[x] Type annotation completeness — Add missing return type annotations on
RLSManager.get_queryset(),RLSManager.for_user(),set_guc(), and tighten the@with_rls_contextdecorator signature. Why: Improves IDE auto-complete and type checker support for library users.
v1.2.2 — Management Commands & System Checks¶
Better CLI tooling and earlier misconfiguration detection.
-
[x]
check_rls --verbose— Show full RLS policy SQL for each table, not just pass/fail status. Why: When policies exist but behave unexpectedly, seeing the actual SQL is the fastest way to diagnose the issue. -
[x]
check_rls --quiet— Suppress success output, only show errors. Why: CI/CD pipelines need clean output — success should be silent. (shipped in v1.2.1) -
[x]
setup_m2m_rls --verbose— Show the generated SQL before execution. Why: DBAs and security reviewers need to audit what SQL will run before approving it. -
[x] New system checks —
W008: verifyTENANT_MODELresolves to an installed model at startup;W009: verifyTENANT_FK_FIELDexists on allRLSProtectedModelsubclasses. Why: These misconfigurations currently fail at query time with cryptic errors instead of being caught at startup. -
[x] Documentation: Celery quick-start — Minimal pattern for wrapping Celery tasks with
tenant_context()before full Celery integration lands in v1.3.0. Why: Celery is the most common question from new users — a docs page unblocks them immediately without waiting for library-level support.
v1.3.0 — Django Admin & Developer Experience¶
Highest adoption impact, no new dependencies.
-
[x] Tenant-aware Django Admin —
RLSTenantModelAdminmixin that auto-sets tenant context from the admin user, hides the tenant FK field on forms, scopes changelists to the current tenant, and adds a tenant filter dropdown for admin users. Why: Every Django project uses the admin — tenant-unaware admin is a daily friction point. -
[x] Celery task integration —
@rls_taskdecorator andRLSTaskbase class that serialize tenant context into Celery task headers and restore it on the worker side. Supports task chains and groups. Why: Background tasks without tenant context are a data-leak risk. Users currently must manually wrap every task body intenant_context(). -
[x] Raw SQL helpers —
safe_tenant_sql()utility for injectingcurrent_setting()calls into raw SQL strings safely. Why: Raw SQL is sometimes unavoidable (reports, bulk operations), and there is no safe, documented pattern for it today. -
[x] Better error messages — Add solution suggestions to
NoTenantContextError(e.g., "did you forget to wrap this intenant_context()?") and make system check hints more actionable. Why: Reduces time-to-fix for new users hitting common misconfiguration. -
[x] CODE_OF_CONDUCT.md — Adopt the Contributor Covenant. Why: Standard open-source practice that signals project maturity and welcoming community.
v1.3.x — Patch cycle¶
No new library features; each patch tightens what v1.3.0 shipped. Details for every item are in the changelog.
-
[x] 1.3.1 — Example project and docs front door — the
example/admin showcasesRLSTenantModelAdmin, the README and docs landing page list the v1.3.0 features,W005also flagsBYPASSRLSroles, and CI builds the docs withmkdocs build --strict. See 1.3.1. Why: The first thing a new user opens must match what the library does. -
[x] 1.3.2 — Bug fixes —
override_settings(RLS_TENANTS=...)is honoured (#100), nested-nullableselect_related()keeps its rows (#79), nested context managers restore the outer scope and preserve database errors (#94, #102), and the middleware owns theSET LOCALtransaction and the request rollback (#95). See 1.3.2. Why: Each one let a test or a request pass for the wrong reason. -
[x] 1.3.3 — Demos, docs accuracy, test backfill, CI gates — committed example migrations and a Celery demo (#80, #81), docs accuracy fixes and this roadmap in the site nav (#82), a performance guide (#83), a troubleshooting page (#109), v1.3.0 test backfill (#84) and a PostgreSQL matrix with release gates in CI (#110). See 1.3.3. Why: Closes the gap between what is documented and what is verified.
-
[x] 1.3.4 — ASGI middleware fix —
RLSTenantMiddlewareno longer fails every authenticated ASGI request withToken was created in a different Context, never skips the GUC clear, and cleans up cancelled requests (#58). See 1.3.4. Why: The sync middleware must work on async deployments until the native async path lands in v1.4.0.
v1.4.0 — Async Support¶
First-class support for async Django (ASGI, async views, async ORM).
Tenant state already lived in contextvars.ContextVars, the right primitive for async,
but every public API that touches the database (GUC operations, context managers,
middleware, decorator) was synchronous. Django has no asynchronous database cursor: every
async ORM call is a sync_to_async(..., thread_sensitive=True) hop, and under ASGI all
such hops of one request run on one thread, and so on one connection. The async APIs below
therefore make thread hops too; what they add is async with ergonomics, and tenant state
set and reset in the calling coroutine, in one contextvars.Context (#58). The real
connection-affinity problems are code on other threads (thread_sensitive=False hops,
the error pages Django builds on a worker thread; #130, #41), sibling tasks sharing one
connection (#41), and pooled connections that keep a previous borrower's GUCs (#96).
This release addresses the full async stack, from low-level GUC operations up through middleware and context managers, and the connection lifecycle under it. See 1.4.0.
Tier 0: Platform¶
- [x] Supported-versions policy and matrix refresh (#114) — A written policy (every
Django series upstream supports; the Python versions all of them support; an explicit
PostgreSQL list), applied: drop Django 4.2/5.0/5.1 and Python 3.11, add Django 6.1,
PostgreSQL 15–18 with CI on 15 and 18, a psycopg 3 CI leg. On Django 6.1 the
select_related()-without-arguments deprecation names the caller.tests/test_support_matrix.pyfails when any file states a different matrix, and a weekly canary runs Djangomain, the next Python and the next PostgreSQL. Why: The matrix had drifted (EOL Django series, a coverage gate pinned to one, an example image on 5.1), and nothing would have noticed the next drift. - [x]
for_user()applies the user's context to every SQL method, and a plain-role CI leg (#131) —count(),exists(),aggregate(),iterator(), the writes and their async variants ran without the GUCs. Each now runs in a scope that sets them on the alias the SQL uses and restores the previous values afterwards. A new CI job runs the library suite as a non-superuser role. Why: Every other CI leg connects as a superuser, which bypasses RLS, so the bug passed every test.
Tier 1: Async GUC primitives (rls/guc.py)¶
- [x]
aset_guc(),aget_guc(),aclear_guc(),arestore_guc()— Async counterparts to the existing sync functions (#36). Each runs the sync function in onesync_to_async(..., thread_sensitive=True)hop: Django has no asynchronous database cursor (every async ORM call is the same kind of hop), so these are not non-blocking, but they run on the thread that owns the task's connection. Why:await-able building blocks for async code that manages GUCs directly. The win is ergonomics and the correct connection, not a non-blocking database call.
Tier 2: Async context managers (tenants/context.py, rls/context.py)¶
-
[x]
async_tenant_context()—@asynccontextmanagervariant oftenant_context()(#37). One thread hop on entry (snapshot and set the GUCs) and one on exit (restore), instead of one per GUC call; the tenantContextVars are set and reset in the coroutine, so the async ORM is scoped and strict mode applies. Why:tenant_context()uses@contextmanager(sync generator) and cannot be used withasync with. Wrapping it insync_to_asyncbreaks the generator protocol. -
[x]
async_admin_context()—@asynccontextmanagervariant ofadmin_context()(#37). Why: Same issue astenant_context()— sync generators are not async-compatible. -
[x]
async_rls_context()andasync_bypass_flag()— Async variants of the genericrls_context()andbypass_flag()context managers. Why: Completes the async context manager surface area so users never need to manually bridge sync/async for RLS operations.
Tier 3: Async middleware (tenants/middleware.py)¶
- [x] Async-native
RLSTenantMiddleware— A hand-written__acall__replacesMiddlewareMixin.__acall__under ASGI (#38). One thread-sensitive hop readsrequest.userand sets the GUCs, the tenantContextVars are set and reset with their own tokens in the request coroutine, and one hop clears the GUCs. Django has no async cursor, so the GUC work still needs those hops. Why:MiddlewareMixin.__acall__ran the hooks in separate hops, each in its own copy of the request context, which broke the token resets (#58; 1.3.4 added a fallback). Setting the state in the request coroutine fixes that by construction and restores an outer context instead of clearing it. The gain is correctness, not throughput. Constraint: Sync WSGI deployments work exactly as before.USE_LOCAL_SET=Truestayed WSGI-only here until #96, which made it work on this async path without a request transaction (the GUC affinity guard applies the context to each statement).
Tier 4: Async-safe decorator and testing helpers¶
-
[x] Async-aware
@with_rls_context— Anasync deffunction gets anasync defwrapper that entersasync_tenant_context()/async_admin_context()around the awaited body (#39). Generator functions are rejected at decoration time, and a sync-wrapped function that returns a coroutine raisesTypeError. Why: The sync wrapper left the context before the coroutine ran, so the body ran under the caller's context: inside an outer admin context, a coroutine decorated for a tenant user saw every tenant. -
[x] Async testing helpers —
async_rls_bypass(),async_rls_as_tenant(),aassert_rls_enabled(),aassert_rls_policy_exists()andaassert_rls_blocks_without_context()forasync deftests (#40). Why: The sync helpers cannot run in anasync deftest (their database calls raiseSynchronousOnlyOperation), and wrapping a@contextmanagerinsync_to_asyncbreaks the generator protocol. First-class async helpers remove that boilerplate and ensure correct usage. -
[x]
assert_rls_blocks_without_context()underSTRICT_MODE(#126) — The helper (and its async counterpart) counts the rows with raw SQL and the GUCs cleared, so it no longer raisesNoTenantContextErrorunder strict mode and works insiderls_bypass()/rls_as_tenant(). Why: The isolation check every test suite should have failed in exactly the configuration that asks for the strictest checking.
Tier 5: Connection-affinity safety net¶
-
[x] ASGI error pages no longer leave GUCs on a worker thread's connection (#130) — Django builds some ASGI error responses on a worker thread. A connection opened there during an authenticated request got the request's GUCs and kept them for later requests on that thread, anonymous ones included. The
connection_createdhandler now applies the request's GUCs only on the thread that set them and clears them elsewhere. Why: A 404 page whose template or context processors query tenant data could show another tenant's rows, to anonymous visitors too. -
[x] Clear RLS GUCs on every checkout from Django's connection pool (#96) — The
connection_createdhandler clears every GUC the policies read when a pooled connection is checked out, with or without a request context, and fails closed if it cannot.django_rls_tenants.pool.reset_rls_gucsclears them again as the connection goes back, and system checkW010asks for it. Why: Django's pool keeps session GUCs between borrowers, andW004never fires for a pool (Django rejects a non-zeroCONN_MAX_AGEwith one). -
[x] GUC-to-connection affinity guard (#41) — The
connection_createdhandler installs an execute wrapper on every connection that applies the active context's GUCs before a statement whenever the connection holds other values: async_to_asynchop inherits a live context, sibling tasks keep their own, and a connection loses a context before the next statement that runs without it. See GUC Affinity Guard. Why:django.db.connectionsis per thread. Work on another thread (thread_sensitive=Falsehops,asyncio.to_thread(), the error pages Django builds on a worker thread) ran on a connection without the context's GUCs, or with an earlier request's. Sibling tasks of one request share a connection, so one task's context could change the GUCs between another task's statements. -
[x] Transaction-local mode without a transaction (#96) — With
USE_LOCAL_SET=Truethe guard writes the context's GUCs transaction-locally: once per transaction, or around each autocommit statement in a transaction of its own. The middleware's async path, the context managers andfor_user()no longer needtransaction.atomic()on a configured alias, and a request on the async path works in this mode instead of raisingRLSConfigurationError. Why: PgBouncer in transaction mode needs transaction-local GUCs, and Django has no async transactions, so requests on the middleware's async path could not use the mode at all. -
[x] Documentation: async deployment guide (#42) — The Async Deployment guide covers ASGI server configuration (Uvicorn, Daphne, Hypercorn), connection pooling considerations with async (
CONN_MAX_AGE, Django's pool, PgBouncer) with a table of safe settings combinations,ContextVarpropagation semantics acrosssync_to_async/async_to_syncboundaries, and the interaction betweenSET LOCAL(transaction-scoped) and Django's lack of async transactions. Why: Async deployment has different failure modes than WSGI. Users need guidance on connection lifecycle, GUC scoping, and which settings combinations are safe.
v1.5.0 — DRF Integration & Query Improvements¶
First-class support for the most popular Django API framework, the ORM-level gaps the 1.4.0 cycle left open, and checks and tooling for the mistakes a project makes around a correct policy. See 1.5.0.
-
[x] Django REST Framework integration (#43,
contrib/drf.py) —RLSTenantAPIViewMixin(opens the context after DRF authenticates, for anyAPIView, generic view or viewset),RLSTenantPermission,RLSTenantSerializerMixin/RLSTenantModelSerializerwithCurrentTenantDefault(an auto-hidden tenant FK serializer field). The plannedTenantContextAuthenticationwas dropped: an authentication class is never called back when the request ends, so it could not exit its context. Installable aspip install django-rls-tenants[drf]. Why: DRF is the dominant API framework for Django. Library-level integration removes boilerplate and prevents misconfiguration. -
[x]
prefetch_relatedtenant filter propagation (#44) — Extend ORM-level tenant filtering to prefetched querysets, matching the existingselect_relatedbehavior. Why: Completes defense-in-depth at the ORM layer. RLS still protects at the database level, but ORM filters enable composite index usage and make the isolation visible in query logs. -
[x] Granular strict mode (#45) —
RLS_TENANTS["STRICT_MODE_EXCLUDE"], a list of"app_label.ModelName"labels that strict mode does not guard (a proxy follows its concrete model), with system checkW015for an entry that names no installed RLS-protected model. Only the strict-mode check is skipped: the RLS policies, the auto-scope filter andfor_user()are unchanged, so a listed model with no context still fails closed at the database. The main case is a user model read underbypass_flag()in an authentication backend, which sets a GUC but establishes no context. Models without anRLSConstraint(shared lookup tables) are never guarded and need no entry. Why: Current strict mode is all-or-nothing, which forces workarounds for legitimately unscoped models. -
[x] Migration helpers (#46) —
check_rls --generatewrites anAddM2MRLSPolicymigration for every auto-created M2M through table that no migration covers (migratenever creates those policies), with--dry-runand--name. Models with anRLSConstraintalready get their policy frommakemigrations, so the flag covers through tables only. A failingcheck_rlsnow also prints aHow to fix:line per table, and system checkW014reports a model whoseMetadropped theRLSConstraint.AddM2MRLSPolicy.deconstruct()was fixed so a migration Django writes with it imports. Why: The policy of an M2M through table came only from a hand-written migration or fromsetup_m2m_rls, so a fresh database built from the migrations had none, and a failingcheck_rlsnamed the table without naming the cause. -
[x] Guard-only transaction-local mode inside
atomic()(#137) — WithUSE_LOCAL_SET=True, context blocks, thefor_user()scope and the middleware write nothing inside a transaction either; the GUC affinity guard sets both GUCs in oneset_config()before the first statement that needs them and puts the enclosing values back when a block exits. The middleware also sets and clears both GUCs in one statement per alias in session mode. Why: 1.4.0 made this the path outsideatomic(); inside it each block still cost sixSET LOCAL/current_setting()statements. -
[x] Checks that fail loudly (#108) —
E001(theW005bypassing-role warning becomes an error withDEBUGoff),W013when a database check could not run, andW005/W011on every alias inRLS_TENANTS["DATABASES"]. Why: A superuser connection in production, or a check that swallowed its own error, let a project believe it was protected. -
[x]
W012andUNIQUE_ACROSS_TENANTS(#98) — A warning for each unique field,unique_togetherentry orUniqueConstrainton an RLS-protected model that omits the tenant field, with an allowlist for intended cross-tenant uniqueness. Why: PostgreSQL checks unique indexes outside the policies, so theIntegrityErroris a cross-tenant existence oracle. -
[x] Cross-tenant foreign key validation (#107) —
validate_cross_tenant_fks(), called fromRLSProtectedModel.clean_fields()and the DRF serializer mixin, rejects a foreign key to a row of another tenant with Django's "not a valid choice" error. A proxy of anRLSProtectedModelcan now be defined. Why: RLS checks a row's own tenant column; referential integrity runs outside row security, so nothing stopped tenant A's row from pointing at tenant B's. -
[x]
enforce_rlsas a pytest plugin,assert_rls_enforced()(#97) — Therls_role,enforce_rlsandenforce_rls_on_other_threadsfixtures ship with the package through thepytest11entry point, withrls_role/rls_role_aliasesini options; the library suite and the example project use the shipped plugin. Why: Isolation tests on a superuser connection pass whether or not the policies work; every project had to copy the fixture from the docs. -
[x]
run_as_tenantandrun_for_all_tenants(#111) — Run any management command insidetenant_context()/admin_context(), or once per tenant with--filter,--fail-fast,--jsonand--parallel. Why: Nightly reports, re-indexes and backfills needed hand-written context handling in every command.
v1.6.0 — Multi-Tenant Users & Observability¶
Common SaaS patterns and compliance tooling, plus RLS for rows and tables the model inheritance design could not reach. See 1.6.0.
-
[x] Multi-tenant user support (#47,
tenants/selection.py) —MultiTenantUser, aTenantUserwithrls_tenant_ids; a per-request selection with theRLS_TENANTS["TENANT_HEADER"]header (X-Tenant) or a session selection made withswitch_tenant()/clear_tenant_selection(), honoured by the middleware, the DRF mixin and the admin (whose switcher a member may use for their own tenants). A selection that is not one of the user's is a 403, never a fallback; with no selection the request runs inrls_tenant_id.for_user(),@with_rls_contextand Celery propagation are unchanged. Why: Many SaaS applications need users that operate across tenants (consultants, support staff, partner accounts). TheTenantUserprotocol assumed a singlerls_tenant_id. -
[x] Audit logging (#48,
tenants/audit.py) — Structured records on thedjango_rls_tenants.auditlogger:context.entered/context.exitedandtenant.switchedatINFO,context.denied,fk.cross_tenant_rejectedandgucs.clearedatWARNING, each withrls_*record attributes (event, source, tenant, admin flag, user pk) for JSON formatters. No library setting: Django'sLOGGINGturns it on. Why: Compliance requirements (SOC 2, GDPR) often mandate audit trails for data access boundaries. -
[x] Connection pooling guide expansion (#49) — PgBouncer transaction and session mode in detail (
server_reset_query, prepared statements,DISABLE_SERVER_SIDE_CURSORS), a pgpool-II section (connection cache,reset_query_list, load balancing), and a "Troubleshooting GUC Leaks" section with the diagnosis queries. Why: Connection pooling with session-scoped GUCs is the most common operational footgun — better docs prevent production incidents. -
[x] Cross-tenant sharing through policy predicates (#59,
rls/predicates.py) —RLSConstraint(extra_predicates=[SharedWith(...), TenantField(...), RawPredicate(...)])adds a second,FOR SELECTpolicy that lets a tenant read rows other tenants share with it; writes still go through the tenant policy alone.Model.objects.including_shared()reads them through the ORM (reading only). System checksW017,W018andW019report predicates that cannot work. Why: Data shared between tenants (partner and consultant accounts, support staff) had to be handled in the application layer, outside the database-level guarantee. -
[x] RLS for tables the project does not own (#112,
operations.AddRLSPolicy) — A reversible migration operation withapp_labeltargeting that creates the same policyRLSConstraintdoes on a third-party app's table, andRLS_TENANTS["EXTERNAL_MODELS"]so the runtime,check_rlsand the checks (W016) treat the table as protected. RLS-only: no auto-scope or strict mode for a model with its own manager. Why: The smallest step toward protecting tables the project cannot subclass, and the prerequisite of the v2.0.0 adoption operation. -
[x]
RLSTenantPermissionaccepts the contextget_rls_context()entered (#150) — The DRF permission trusts the tenant context the view's own override validated for the request, so per-request tenant selection works with the permission listed inDEFAULT_PERMISSION_CLASSES. Why: The documented hook and the permission contradicted each other for a non-admin user. -
[x] CI: psycopg 3 on the oldest Django and PostgreSQL 17 (#151) — A psycopg 3 leg on Django 5.2 and one on PostgreSQL 17, and the support-matrix test requires a leg for every supported PostgreSQL major. Why: The supported-versions policy promised combinations no leg ran.
v1.6.x — Patch cycle¶
No new library features; each patch tightens what v1.6.0 shipped. Details for every item are in the changelog.
- [x] 1.6.1 — Two fail-closed fixes —
@with_rls_contextwith aNoneuser (or a signature without the user parameter) runs the function with no RLS context instead of the caller's (#160), andcheck_rls,register_m2m_rls()and theW001/W002/W009checks cover a model protected by anRLSConstraintwithout inheritingRLSProtectedModel, its automatic M2M through tables included (#159). Both were found by an independent read of 1.6.0. See 1.6.1. Why: The documentation promised fail-closed in both places; the code did not deliver it. - [x] 1.6.2 — The
None-user exit on other aliases — in session mode with more than one configured alias, aNone-user@with_rls_contextcall left the enclosing context's GUCs on the other alias after the enclosing block had exited, in autocommit (#163, PR #164) and after a transaction committed on that alias (PR #169); outside any context the call's exit now clears every connected alias at once. Found by an outside reader (#164); the transaction case by its review (#169). Also: the ASGI error-page tests follow Django 6.2's thread-sensitive error pages andaiterator(chunk_size=None)(#165), and the bug report template asks forcheck_rlsoutput, the role and the deployment shape, with aSUPPORT.md(#166). See 1.6.2. Why: A second alias is where SQL the guard does not see runs with a context that has ended; the exit must leave what the enclosing block's exit can take off again. - [x] 1.6.3 — Lockfile refresh —
certifi2026.7.22 → 2026.10.19 in the development lockfile (#177, Dependabot PR #176); an indirect dependency of thedocsgroup, so the library code is identical to 1.6.2. See 1.6.3. Why: Dependabot bumps ride along with the next release instead of waiting for one.
v1.7.0 — Django Ninja & Strict-Mode Tooling¶
A second API framework on the same contract as DRF, and the per-query and observability pieces strict mode was missing. See 1.7.0.
-
[x] Django Ninja integration (#167,
contrib/ninja.py, extraninja) —RLSTenantNinjaAPIenters the tenant context after Ninja'sauth=and throttling and keeps it through serialization and error rendering, for sync andasync defoperations;RLSTenantGuard,RLSTenantModelSchemaandrls_save()/arls_save()matchRLSTenantPermissionand the DRF serializer mixin (cross-tenant foreign keys get the same 422 as a missing row). Why: Ninja authenticates inside the operation, so a token client reached the library as an anonymous request; it is the API framework async deployments pick. -
[x] Per-query strict mode override (#168) —
Model.objects.rls_skip_strict()for a one-off query that intentionally runs without a context. Python-side only: the database still fails closed. Why: Complements the per-model exclude list (v1.5.0); such queries were wrapped in anadmin_context()they did not need. -
[x] No-context audit record (#178) — opt-in
RLS_TENANTS["AUDIT_NO_CONTEXT_QUERIES"]: withSTRICT_MODE=False, a query on a protected model with no context logscontext.denied(reasonno_context, sourcequeryset) and still runs. Why: In production a code path that lost its context answered with an empty result and nothing to alert on. -
[x] Local-mode session writes cleared at exit (#173) — with
USE_LOCAL_SET=True, a session-level write of the admin or tenant GUC the guard saw inside a block is cleared when the block, thefor_user()call or the request exits; sessions with no such write get no extra statement. Follow-up: #181 (a transaction on another alias still failed at the enclosing exit). Why:USE_LOCAL_SET=Trueis the mode for PgBouncer transaction pooling; an admin bypass left on a session there should not depend on application code never callingset_guc().
v2.0.0 — Advanced Features¶
Architectural changes that may require migration effort.
-
[ ] Soft-delete awareness — Optional
AND (deleted_at IS NULL)clause in RLS policy expressions so soft-deleted rows are invisible even to the owning tenant. Why: Soft-delete is a common pattern; pushing it to RLS ensures deleted data cannot be accessed through any code path. -
[ ] Cross-tenant relationships beyond read sharing — 1.6.0's
extra_predicates(#59) let a tenant read rows another tenant shares with it. Still open: rows two tenants may both write (inter-tenant messaging), and shared catalogs with no tenant column at all (anRLSSharedModelorshared=Trueflag that the auto-scope filter, strict mode and the checks understand). Why: Real-world multi-tenant systems often need shared reference data that does not belong to a single tenant. -
[ ] Row-level permissions beyond tenant/admin — Additional GUC-based roles (viewer, editor, owner) with custom policy expressions. Why: The current binary admin/non-admin split is insufficient for applications with fine-grained access control needs.
-
[ ] Explicit through model helpers — Templates and mixins for creating manually defined M2M through tables that are RLS-protected. Why:
register_m2m_rls()only handles auto-generated through tables; explicit through models require manual constraint setup today.
Future / Under Consideration¶
No committed timeline. Community interest drives prioritization.
- [ ] GraphQL integration helpers (Strawberry, Graphene)
- [ ] Benchmarking suite (100k+ rows, 1000+ tenants)
- [ ] Index-friendly policy shape -- the
CASE WHEN <admin> THEN true ELSE tenant_id = ...policy can only be a post-scan filter; a baretenant_id = current_setting(...)::intpredicate is indexable (see the Performance & Indexing guide). A shape that keeps the admin bypass yet stays indexable would only help policy-only scans (raw SQL without its own predicate), would need every deployment to recreate its policies, and risks mis-estimated admin scans. Not planned unless a concrete case appears. - [ ] PostgreSQL 17+ RLS feature adoption
- [ ] Citus distributed table compatibility