Multi-tenant SaaS in production
The tenant isolation the framework guarantees, the explicit escape hatches, and the review checklist that pins them.
If you sell one deployment to many tenants, one leaked row is a breach. This page states what the framework isolates for you, names the exact places that bypass it, and gives you a checklist to audit before you trust it. The guarantees are strong; the escape hatches are real and deliberate — you should know both.
Isolation starts where every request enters: bind the two guards on the controller, and the caller’s org scope flows through every layer below.
#[controller(path = "/users")]#[use_guards(AuthnGuard, AuthzGuard)]pub struct UsersController { #[inject] svc: Arc<UsersService>,}The guarantee
Section titled “The guarantee”Once the authz modules are imported, the caller’s ambient Ability is
non-optional. On every unit whose posture names what it reads, the one line a
handler writes, it does four things, and a unit naming nothing reads nothing a
grant guards:
- Pre-filters every read.
Repojoins the ability’s predicate into the SQLWHERE, so a member querying posts getsorg_id = $caller_org_idappended. - Stamps and checks every create. A column the caller’s
Creategrant pins —org_id = $caller_org_id— is filled when the input left it unset, and the fresh row is re-checked against the grant in SQL: a row outside the caller’s org is rolled back and answers403. - Gates every by-id write. A denied-but-existing row updates zero
rows and returns
403, not the row. - Judges each wire row. A column the caller cannot read is no value in
the row it is answered, which reads
nullthere.
One predicate AST is interpreted twice — as SQL and in memory — so the rows a query returns and the rows a reply may answer cannot diverge. The mechanics live on one canonical page: Row-level filtering. This page does not re-derive them; it covers what happens at the edges of that guarantee.
The escape hatches
Section titled “The escape hatches”The framework does not pretend the choke point is inescapable. Two paths reach the database around the ambient scope. Each exists for a reason, and each is a place a reviewer must look.
1. The named Repo escapes and injected Arc<DatabaseConnection>
Section titled “1. The named Repo escapes and injected Arc<DatabaseConnection>”Repo hands out no connection, so a service cannot run a query of its own on
the unit’s executor. A step around the scope goes through a method named
for it, whose rustdoc states the bar its caller must clear: Repo::unscoped and
unscoped_by_id read with no ability, insert_unscoped (and its on-conflict form,
insert_unscoped_or_existing) writes with none, and with_tombstones keeps the
ability and reads past soft deletion. The
credential lookup before sign-in is one, and it reads across every tenant:
async fn find_by_email(email: &str) -> Result<Option<entity::Model>, RepoError> { Repo::<Users>::unscoped() .filter(entity::Column::Email.eq(email.to_owned())) .one() .await}An injected Arc<DatabaseConnection> goes one step further — it has no
executor and no ability at all, the sanctioned bypass for a truly
contextless path such as a one-shot command run outside every unit of work:
#[injectable]pub struct SessionReaper { #[inject] db: Arc<DatabaseConnection>, // no executor, no ability — fully unscoped}Both are deliberate seams for system-level work, not the default path. Feature code that reaches for either owes a comment saying why the scope does not apply, and a reviewer who confirms it.
2. Worker and queue jobs run for a tenant, never under an ability
Section titled “2. Worker and queue jobs run for a tenant, never under an ability”A #[processor] runs with no ambient ability — and, by default, in one
transaction per attempt. A job is system work with no caller to scope, so the
row filter is a no-op there: nothing a job reads or writes is filtered for you.
What a job keeps is the tenant it was pushed for. Your claims name it once, off the verified token:
#[derive(Debug, Clone, Serialize, Deserialize, PrincipalIdentity)]pub struct Claims { // … #[principal(tenant)] pub org_id: Uuid, // …}The authentication guard makes that tenant ambient for the request. Every job
the request pushes seals it into its envelope beside the actor, and the worker
restores it, so nest_rs::core::current_tenant_id() answers in a processor
what it answered in the request that pushed the job. The ambient tenant comes
from a verified principal or a sealed envelope and nothing else — never a
header — and a record whose tenant_id names no tenant is dead-lettered
rather than run for none. An envelope is as trusted as
whoever can write the queue’s keys, so
the Redis rules that allow it are part of your tenant isolation.
A job’s own facts still travel in its payload. The demo’s publish notification belongs to the org of the post that was published — a fact the post names, in an org the publish was already scoped to — so its payload carries it, declared at the feature port beside the queue:
#[derive(Debug, Clone, Serialize, Deserialize)]pub struct NotifyCommand { pub org_id: Uuid, pub message: String,}
#[queue(name = "notifications", job = NotifyCommand)]pub struct NotifyQueue;The processor reaches no data itself; it hands the job to its service:
#[processor]impl NotificationsProcessor { #[process(queue = NotifyQueue, retries = 3)] async fn notify(&self, job: NotifyCommand) -> Result<()> { self.svc.persist(job).await?; Ok(()) }}The service writes the row under the payload’s org, through Repo; the key
and the creation time are the entity’s #[expose(…, timestamps)] to seed:
pub async fn persist(&self, command: NotifyCommand) -> Result<(), ServiceError> { let active = entity::ActiveModel { org_id: Set(command.org_id), message: Set(command.message), ..Default::default() }; let model = Repo::<Notifications>::insert_unscoped(active).await?; // … Ok(())}A read a job makes filters on its tenant itself. Repo::<E>::scoped(Action::Read)
in a job filters nothing, since no ability exists there, so the service adds
.filter(Column::OrgId.eq(tenant)) with the tenant current_tenant_id()
answers — and refuses when it answers None. Treat every #[processor] as its
own boundary: a service method a job calls that loads by id with no tenant
predicate is the bug to grep for.
Review checklist
Section titled “Review checklist”Run this before a tenant-facing release. Each step is one grep or one
read:
- Grep for
Repo::unscoped,unscoped_by_id,insert_unscoped(which findsinsert_unscoped_or_existingtoo) andwith_tombstonesin feature code. Confirm each call site clears the bar the method’s rustdoc states, and is not a forgotten scope. - Grep for
clippy::disallowed_,sea_query::Enumandimpl Idenin feature code. AReposelect hands out no statement, so nothing rewrites whatRepofiltered, and raw SQL in a filter is the one way past it: each#[expect]opens it, and its text must hold no value; the other two are what clippy cannot name (Raw SQL in a filter).with_abilityneeds no such read: it only narrows the ability the unit runs under, and nothing public widens one — no function installs an executor of its own, and a unit opened or work re-entered inside a request runs as that request. A test runs a service throughTestApp::unit. - Grep for
ExecutorScope::Jobin feature code. A job unit is an edge’s — a queue attempt, a tick — and one a feature opens on a task of its own reads unscoped. - Grep for
Arc<DatabaseConnection>outside the framework crates. Each injection should be a contextless path (a one-shot command), never a request handler or a lifecycle hook, which runs in a unit of work. - Confirm every
#[processor]re-scopes. Trace the tenant —current_tenant_id(), or the id a tick puts in the payload — into the service’s query. A load-by-id with noorg_idpredicate is the bug. - Confirm every controller carries
#[use_guards(AuthnGuard, AuthzGuard)]. A missing binding fails closed to empty results, but a negative-path test pins it.
Limits
Section titled “Limits”No database-side backstop exists in 7.0. The framework sets no database session or transaction setting, so a Postgres Row-Level Security policy keyed on one has nothing to read. Setting one yourself per connection leaks: a pooled connection keeps its session setting after the request and serves the next tenant that checks it out. Closing the gap takes the framework setting the tenant inside every transaction it opens — local to that transaction — on every path that reads, the pool’s included. Until it does, the application-layer filter above is the only control, and the checklist is how you hold it.
A job pushed outside a request runs for no tenant. A scheduled tick, a
boot task or main has no verified principal, so what it pushes carries none:
a tick fanning work out per tenant names each tenant in the job’s payload, and
the service filters on that.
Isolation of rows and fields is the framework’s job. Everything a production tenant boundary also depends on remains yours: key management, token revocation, TLS, and DDoS defense at the edge. The Threat model lists what each layer catches and where the responsibility falls back on your deployment. Read it before you go live.
Going further
Section titled “Going further”- Row-level filtering — how the ambient ability joins into every read.
- Threat model — what the layers cover and what stays your responsibility.
- Repo and executor — the choke point the escape hatches step around.