To test tenant isolation, create two look-alike tenants and try to reach tenant B's data as a user of tenant A. Try every path your product has: routes, database queries, queued jobs, caches, files, exports, webhooks, broadcasts and support tools. Each attempt must end in a defined denial, with no data returned and nothing changed. This guide gives you our test matrix and tests from ClinicTek's suite. ClinicTek is the clinic management system BarmajTek builds and runs on Laravel and PostgreSQL.
A tenant is one customer organization, such as one clinic. Multi-tenant authorization is the set of checks that keeps each tenant's users inside their own organization's data. The runtime role is the database role that serves your users' requests. The database section explains why it must not own the tables.
The test matrix
Write one row per layer, then one test per row for every tenant table or feature.
| Layer | Attack to try as tenant A | Pass when |
|---|---|---|
| Routes and actions | Open, edit, delete, download or bulk-update tenant B's record by its ID | 403 or 404, as your policy says, and the database is unchanged |
| Nested routes | /projects/{project}/tasks/{task} with A's project and B's task | The task is checked against its project and its tenant |
| Create, import, copy | Send B's tenant_id, or B's customer ID on a new invoice | Rejected, or the tenant is taken from the session |
| Counts, reports, search | Compare totals for two tenants with known, different values | Each tenant gets its exact total |
| Database | Query as the runtime role with B's context, then with no context | None of A's rows in either case |
| Queued jobs | Run A's job, then B's job, in the same worker process | Each job sees only its tenant; context is cleared after each |
| Caches, locks, rate limits | Use the same record ID or slug in both tenants | Separate keys and separate allowances |
| Files and exports | A copied URL, a guessed object key, an expired signed link, a file path swapped in the database | Denied; every exported row belongs to the tenant |
| Broadcasts and notifications | Subscribe to B's channel; revoke a membership between queueing and sending | Subscription refused; nothing sent after the revocation |
| Inbound webhooks | A correctly signed event for another provider account | The tenant comes from the verified account, and the other tenant's data is untouched |
| Support access | A platform user without the support role tries to impersonate | Refused; approved sessions record actor, reason, expiry and exit |
Treat any 500 in this matrix as a failed release, because a server error can hide a missing check. The OWASP Authorization Cheat Sheet states the rule behind the route and object rows. It says to deny by default and to validate permissions on every request for the specific object being accessed.
Two look-alike tenants in every test
Create at least two tenants with users and similar records in every isolation test. Give them adjacent IDs and sometimes identical names, so a lookup cannot pass just by finding the only row in the database. Add a pending membership, a revoked membership and one user who belongs to both tenants with different roles. Then test switching between tenants as well as signing in. Keep these factories cheap, so every new feature gets its own cross-tenant case.
List the genuinely global resources too, such as a public plan catalog, and keep them apart from tenant data. A vague line between the two tempts a developer to remove a boundary to make a feature work.
Routes: deny by ID
Choose 403 or 404 once for the whole product and keep it. ClinicTek answers 404, which does not confirm that the other record exists. Repeat the test for show, update, delete, download, bulk actions, search, filters and exports. For nested routes, assert that the child belongs to the parent and the tenant. Hiding a button in Vue changes nothing on the server.
Create, import and mass assignment
Take the tenant from the authorized session and never from the request body. Submit another tenant's ID on create, update, import and copy, and assert rejection or server-side replacement.
Then try to attach a record to a parent in another tenant. For example, create an invoice for tenant B's customer, or add a user to a project in another tenant. Check this in the form request, the policy class and the service class. Add a composite foreign key where the database can refuse the cross-tenant link itself.
Counts, reports, search and caches
A count, a sum, an exists check or a chart can reveal another tenant's data without returning a single row. Give the two tenants different known values and assert exact results.
Put the tenant in every cache key that holds tenant data, including dashboards, permissions, feature state, search results, locks and idempotency keys. An idempotency key lets the server apply a repeated request only once. Give each tenant its own rate limit unless a documented global limit applies. Search indexes and analytics stores need the tenant on every document and a filter applied on the server. Test reindexing, deletion and a membership change.
The database: row-level security under the runtime role
Policies in application code can be skipped by a raw query or a forgotten relationship. A global scope has the same weakness, because code can remove it and an unusual relationship can miss it. Limit withoutGlobalScopes to named, reviewed operations.
Test that a normal web request with no tenant context fails instead of returning every row. Document each exception for console commands, system jobs and support tools.
PostgreSQL row-level security (RLS) adds a second boundary inside the database. The PostgreSQL documentation names two traps. Superusers and roles with BYPASSRLS always bypass it, and table owners bypass it too unless the table uses FORCE ROW LEVEL SECURITY.
ClinicTek runs its migrations as an owner role and serves requests as a separate runtime role that RLS applies to. Every tenant table outside a documented exempt list has RLS enabled and forced. Ordinary tenant tables have four policies (tenant_isolation_select, _insert, _update, _delete). Platform-only tables are forced with no tenant policy, so tenant requests are denied, and one table allows reads only. A list of central tables is exempt, each with a written reason.
Each policy compares the row's tenant_id with the session setting app.current_tenant_id. When that setting is empty, the policy matches nothing, so a request with no tenant context sees no rows.
Run your RLS tests as a role without BYPASSRLS, or they pass whatever the policies say. Our shared test harness creates such a role and switches to it. Its fail-closed variant also refuses to continue if the active role is a superuser or can bypass RLS.
Make a new table fail until it is covered
Hand-written denial tests miss the table someone adds next month. ClinicTek's coverage test reads the PostgreSQL catalog for every table in the public schema that has a tenant_id column. It fails the test run when a table lacks enabled or forced RLS, or lacks any of its four policies.
Every exempt table sits in a named list with its reason. Custom domains, for example, are exempt because the app must read them before it knows the tenant. A second test fails if an exempt table no longer exists.
Apply the same idea to application code. An architecture test can assert that every business model implements your tenant contract. A static search can flag withoutGlobalScopes, raw queries, generic cache keys and files in public storage. These checks do not replace behavior tests, but they catch a layer nobody wrote a test for. Point every approved exception to a negative test that proves its boundary.
Queued jobs and long-lived workers
A job runs after the request that dispatched it has finished, inside a worker process that stays up between jobs. The Laravel 13 queue documentation warns that workers keep the booted application in memory. Static state your application creates is not reset between jobs. The same page notes that a model passed to a queued job is fetched again from the database when the job runs. Relationship constraints applied before queueing are not applied again.
So put an immutable tenant reference in the job, with the user who triggered it or, for a system job, the reason it runs. Restore the tenant before loading any record, check permissions again at execution, and clear the context afterwards. Limit who can see sensitive job payloads.
ClinicTek's queue workers clear the in-memory tenant and the PostgreSQL tenant setting before and after every job. They do this through the shared core library all our SaaS products use, and that library's tests assert that the setting is empty afterwards.
In your own suite, run tenant A's job and tenant B's job one after the other in the same worker process. Assert that the second job sees nothing of the first. Cover retries, failed-job replay, chains, batches and scheduled commands that loop over tenants.
Files and exports
A tenant prefix on a storage path helps, but the download route must still check ownership before it issues the file. Try a copied URL, a guessed object key, an expired signed link and a database row whose path was changed to another tenant's file. Test thumbnails and other generated files too, because a private original can leak through a derivative written to public storage. A shared bucket needs deliberate policies and scoped credentials.
Exports join many tables outside the usual screens, so assert that every exported row and attachment belongs to the tenant. Keep the export private and short-lived, and log each download.
Webhooks, broadcasts and notifications
Resolve the tenant of an inbound event from the verified provider account after the signature check, never from a tenant_id field in the payload. Then send a correctly signed event for a different account and prove it cannot update another tenant.
For outbound calls, check that the callback URL, the credential and the log entries belong to the selected tenant. Test a retry after that tenant changes its configuration or is deleted. If your product calls URLs that customers enter, such as outbound webhooks, refuse private, loopback and cloud metadata addresses. Otherwise one tenant could reach your internal services. Our guide to webhooks and polling covers signatures and replays.
For realtime channels, the authorization callback must match the channel to the user's current membership, so try subscribing to tenant B's channel. Knowing a channel name must never be enough to subscribe. Keep payloads to the fields the recipient needs. Mail and notifications must pick the recipient, language and links inside the right tenant. Test a user who belongs to two tenants, and a membership revoked between queueing and sending.
Support access and impersonation
Cross-tenant support is the one deliberate exception to isolation, so it is the riskiest path. Require a separate role, a reason, a target tenant, an expiry and an audit record for each session. Test that tenant administrators and ordinary platform users cannot start one. Then test that removing the role takes effect at once, and that the session ends with a clear exit and a new session ID.
Search results and exports in a support session should show only what the task needs. Actions taken during support must stay attributed to the real operator, so do not use shared support accounts.
Run it on production-shaped infrastructure
Run isolation tests on PostgreSQL. Your policies are PostgreSQL row-level security, so a test on another database engine tells you nothing about them. A skipped RLS test looks green in a report. Our shared harness has a variant that fails instead of skipping when PostgreSQL is missing, and your CI should use one like it.
ClinicTek's own RLS tests skip themselves on a non-PostgreSQL connection. They rely on a CI workflow that is set up to start PostgreSQL 16 and create the runtime role before the tests. Keep fixtures synthetic and keep sensitive values out of failure output.
Release checklist
- Every tenant table passes the coverage test, and every exemption has a written reason.
- Each matrix row has a passing allowed case and a passing cross-tenant denial.
- RLS tests ran as a role without
BYPASSRLS, on PostgreSQL. - Migrations ran as the owner role; the runtime role has no owner rights on tenant tables.
- The two-tenant worker test passed, including retries and scheduled commands.
- No 500 appeared anywhere in the denial suite.
- After deployment, a small smoke run passed with synthetic tenants, without touching real tenant data.
Next step
Describe how your product separates tenants and name two sensitive user journeys, without customer data or secrets. Send it through the project brief, or use the WhatsApp button on this page. In a free first conversation we talk through how your tests compare with this matrix.
If you decide to close the gaps, we offer a discovery phase for a fixed fee agreed in writing before we start. It gives you a written scope, an estimate and a timeline in about 5 working days. The fee is credited to the project. No sales tax is added.
For the architecture behind these tests, read designing multi-tenant SaaS architecture in Laravel and how to choose an MVP tech stack. To have the platform built and run with these checks in place, see SaaS development.




