Skip to main content

Isolating your own data by tenant

Archenstack decides who may do what — a role, a feature, an access level. It deliberately does not filter your data rows. SPEC §9 says so outright: read filtering is an application concern, and moving it into the core would be a breaking wire change.

That leaves a gap you must close yourself, and it is a sharp one. If a single instance holds a Ministry of Health org and a Nakuru County org, Archenstack isolates its own tables — one org can never read another's matrix, roles, or assignments. But your cases, documents, patients tables are yours; Archenstack has never heard of them. Nothing in it stops a Ministry user's SELECT * FROM cases from returning County rows. The Ministry user is a perfectly authorized Ministry admin — they just asked a question you never scoped.

This page is the recipe for scoping it. Archenstack hands you the caller's org and the intra-tenant scope machinery; the tenant boundary on your own tables is the part you build, and this is how to build it so it holds.

What's universal, and what's shown in one stack

The concept and the database enforcement here are stack-agnostic — an owning_org column and a row-security policy work the same behind any language. In particular the load-bearing piece, Postgres RLS, is plain SQL. The ORM snippets are shown in Django, the reference multi-tenant adapter, as a worked example — a Spring/JPA, Express, Go, or Rust host writes the same six pieces in its own query layer. Where a code block is Django-specific it says so; translate it, don't assume it.

Who needs this: any deployment where one instance serves more than one tenant. That is the shape the persistent adapters — Django and Java — support directly, and both resolve the caller's org for you (below). The single-org adapters (Node, Go, Rust) serve one tenant per instance, so there is no second tenant in the same process to leak to; a host that multi-tenants on top of them supplies the tenant from its own auth layer and applies the identical column-and-RLS pattern.

Two different axes — don't conflate them
  • Cross-tenant (this page): which org owns this row? Ministry vs County. Enforced with an owning_org column on your tables. Archenstack does not do this for you.
  • Intra-tenant (object scopes): within one org, which of its rows may this caller touch? — own_record, own_department, own_subtree. Archenstack does help here, through the scope atoms and the write-scope evaluator.

They stack: a County caseworker is first pinned to County rows (cross-tenant), then narrowed to their own district's rows (own_subtree, intra-tenant). Build the cross-tenant boundary first; it is the one a leak crosses.

The recipe​

Six pieces, in build order. The first four are the working parts; the last two are what make it hold when a developer forgets.

1. Stamp every row with its owning org​

Add an owning_org column to every top-level table — the slug of the org that owns the row, the same slug Archenstack resolves. Add it nullable for now; piece 6 makes it mandatory once every existing row is backfilled.

In Django an abstract base captures it (a Spring host puts the column on a @MappedSuperclass, a Go or Rust host adds it to the row struct):

# yourapp/tenancy.py
from django.db import models

class OrgOwned(models.Model):
"""Abstract base for a tenant-owned table. `owning_org` is the org SLUG, matching
the value Archenstack resolves for the caller."""
owning_org = models.SlugField(max_length=64, null=True, db_index=True)

class Meta:
abstract = True

The index matters: every read below filters on this column, so it is on the hot path of every query.

2. Read the caller's org from Archenstack​

You already resolve the caller's org for Archenstack's own routing; reuse it — do not invent a second source, or the two can disagree and the disagreement is a leak. Both multi-tenant adapters hand it to you:

from archenstack_rbac_django.permissions import resolve_org

org = resolve_org(request.user) # the caller's org slug, or None

Whatever the source, an unresolvable org is deny, never "all orgs": resolve_org / resolveOrg returns None / null in that case, and the filters below turn that into no rows, not every row.

3. Filter every read​

Every list query on an org-owned table narrows to the caller's org. Centralise it so "remember the WHERE" is not a per-view decision — a Django manager here; a JPA @Filter / repository base, a query helper, or a base scope elsewhere:

class OrgScopedQuerySet(models.QuerySet):
def for_caller(self, user):
org = resolve_org(user)
if org is None:
return self.none() # fail closed: no org ⇒ no rows
return self.filter(owning_org=org)

class Case(OrgOwned):
objects = OrgScopedQuerySet.as_manager()
# …
# in the view — reads go through for_caller, never the bare manager
cases = Case.objects.for_caller(request.user)

4. Stamp and verify on write​

In Django: on create, set owning_org from the caller. On update, verify the row already belongs to the caller's org — otherwise a caller could mutate another tenant's row by guessing its id, since the object check never saw the wrong-org row was off-limits:

def create_case(request, **fields):
org = resolve_org(request.user)
if org is None:
raise PermissionDenied
return Case.objects.create(owning_org=org, **fields)

def update_case(request, pk, **fields):
case = Case.objects.for_caller(request.user).get(pk=pk) # for_caller already scopes it
for k, v in fields.items():
setattr(case, k, v)
case.save()

Loading the row through for_caller before touching it is what closes the guess-the-id hole: a row in another org simply is not in the queryset, so the .get raises DoesNotExist (404) rather than handing it over.

Java/Spring: the write-side of this is shipped (2.4.0)

The Spring adapter automates pieces 1, 2 and the create half of 4 with an opt-in write-side tenancy companion (archenstack-rbac.tenant-context=true): ArchenstackTenantContext publishes the request's active org — resolved through the same resolver as the caller's role, so the two can never drift — and a @PrePersist ArchenstackTenantListener stamps a TenantOwned row's tenant from it. Off a request (a job or consumer), bind it yourself with ArchenstackTenantContext.runAs(org, …), or set archenstack-rbac.tenant-default-org so a NOT NULL owning_org gets a home tenant on a non-HTTP path (empty by default — leave it null and let the column/RLS reject an untenanted write).

It is deliberately write-side only — it does not filter reads. A read filter enforced in application code fails silently the moment one query path forgets it, which is exactly why the read boundary belongs in the database. ArchenstackTenantContext.activeOrg() is also the value you feed piece 5's RLS session variable (SET LOCAL app.current_org = …), so reads still get a real boundary — in the database, where it holds.

Modular hosts: the three types your entities touch — TenantOwned, ArchenstackTenantContext, and the @PrePersist ArchenstackTenantListener — ship in a tiny, Spring-free jar, io.archenstack:archenstack-rbac-tenancy (jakarta.persistence only). Depend on that from your domain/entity modules to implements TenantOwned and attach the listener, without pulling the Spring-Boot starter (Security, Web, the authorizer) down into layers built to stay lean. Only ArchenstackTenantFilter — which reads the caller's org through the authorizer — lives in the starter. A monolith with its entities in the module that already has the starter gets all four transitively and needs no extra dependency.

5. Back it with the database — this is the real boundary​

Pieces 3 and 4 are forgettable. One .raw() query, one model that skipped OrgOwned, one report written in SQL, and the filter is gone with no error. So the boundary that actually holds is Postgres Row-Level Security, because the database enforces it under every query regardless of the code path:

ALTER TABLE cases ENABLE ROW LEVEL SECURITY;
-- FORCE binds the table OWNER too. Without it, the role that owns the table (often
-- your app's migration role) bypasses RLS entirely — a silent hole.
ALTER TABLE cases FORCE ROW LEVEL SECURITY;

CREATE POLICY cases_tenant_isolation ON cases
USING (owning_org = current_setting('app.current_org', true))
WITH CHECK (owning_org = current_setting('app.current_org', true));

USING filters reads and the rows an update/delete may touch; WITH CHECK refuses a write that would set owning_org to anything but the current tenant. The policy reads the tenant from a session variable you set per request, from the resolved org. Any framework can set it — the Django middleware below is the worked example; a Spring OncePerRequestFilter, an Express middleware, or a Go/Rust handler wrapper runs the same set_config on the request's connection:

# yourapp/middleware.py — set the tenant for the request's DB transaction
from django.db import connection
from archenstack_rbac_django.permissions import resolve_org

class CurrentOrgMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
org = resolve_org(getattr(request, "user", None)) or ""
with connection.cursor() as cur:
# is_local=true scopes it to the CURRENT TRANSACTION — see the warning.
cur.execute("SELECT set_config('app.current_org', %s, true)", [org])
return self.get_response(request)
The session variable must be transaction-scoped, or it leaks across requests

set_config(..., true) binds the value to the current transaction. Your web server reuses pooled database connections, so a value set with is_local=false (or set outside any transaction) survives onto the next request that reuses that connection — handing one tenant's setting to another. Run with ATOMIC_REQUESTS = True (or wrap each request in an explicit transaction.atomic()) so the whole request is one transaction and the setting cannot outlive it. An empty value (no resolvable org) makes the policy match nothing — fail closed.

RLS is the piece Archenstack cannot provide for you: the policy names your table and depends on your session convention, and it is Postgres-specific. That is precisely why the boundary lives here and not in the library.

6. Make the owner mandatory​

Once every existing row is backfilled, drop the nullability so no row can ever be created without an owner. Do it last, after the backfill, or the migration fails on existing null rows:

# after a data migration that backfills owning_org on every row
owning_org = models.SlugField(max_length=64, db_index=True) # null=True removed

A NOT NULL owning_org plus the RLS WITH CHECK means there is no way to write an unowned or wrong-owned row, from any code path.

Roll-up: when a parent tenant should see its children's rows​

The flat rule "owning_org = caller's org" is right for strict isolation — Ministry and County are peers, neither sees the other. But a government hierarchy usually is not flat: a Ministry that governs counties often needs to read across them for reporting. Flat equality breaks that — the Ministry sees nothing but its own rows.

If you want roll-up, filter by the caller's org and its descendants in Archenstack's tenant tree. Archenstack already models that tree (Organization.parent in Django, OrgEntity.parentSlug in Java), so you can walk it for the descendant slugs — shown here in Django:

from archenstack_rbac_django.models import Organization

def visible_orgs(user):
"""The caller's org plus every org beneath it — for a tenant that rolls up."""
org = resolve_org(user)
if org is None:
return []
root = Organization.objects.filter(slug=org).first()
if root is None:
return []
# breadth-first over children; a real deployment caches this per request.
slugs, frontier = {org}, [root]
while frontier:
children = Organization.objects.filter(parent__in=frontier)
frontier = [c for c in children if c.slug not in slugs]
slugs.update(c.slug for c in frontier)
return list(slugs)

# read: .filter(owning_org__in=visible_orgs(request.user))
# RLS: owning_org = ANY(string_to_array(current_setting('app.visible_orgs', true), ','))

Whether a tenant is a peer or a parent is your policy, not Archenstack's — which is the strongest reason this layer stays with you. Strict isolation and hierarchical roll-up are two different products of the same tree, and only you know which one this tenant is. Governance flows downward only here too: a county rolls up to nothing above it, exactly as a bounded platform grant — a cross-org admin authority scoped to one subtree of tenants — reaches descendants and never ancestors.

What this does and does not buy you​

  • It does stop a caller from reading or writing another tenant's rows, on every code path, once RLS is in place.
  • It does not replace archenstack-rbac. Archenstack still decides whether this caller may read cases at all (the feature check) and, within their tenant, which of their own rows they may write (the scope atoms). Tenant isolation answers a different question: whose rows are these?
The ORM filter is convenience; RLS is the guarantee

Do not treat the for_caller queryset as your security boundary. It is ergonomics — it keeps the common path clean. The boundary is RLS, because it is the only layer a raw query, a forgotten filter, or a model that skipped OrgOwned cannot slip past. If you ship only pieces 3–4 and skip 5, you have a leak waiting for the first developer who writes SQL.

Checklist​

  • owning_org on every top-level table, indexed.
  • Reads go through a for_caller-style filter that fails closed on no org.
  • Writes stamp owning_org from resolve_org, and updates load the row through the scoped queryset first.
  • ENABLE and FORCE ROW LEVEL SECURITY, with a USING + WITH CHECK policy.
  • The session variable is set per request from the resolved org, inside a transaction (ATOMIC_REQUESTS).
  • owning_org is NOT NULL after backfill.
  • Decided, per tenant, whether it is strict-isolation or rolls up to descendants.

See also​