Testing Tenant Isolation in Laravel: Leak Tests, Guard Tests and What They Still Miss: 06 of 08
How to prove company data stays separate in a multi-tenant Laravel app: two-company fixtures, a schema guard that catches unscoped models, job and cache checks, an allowlist for scope bypasses, and the limits.
Imagine a team with 300 green tests and a multi-tenant app in production. A developer adds a Receipt model, writes the migration with a company_id column, and forgets the BelongsToCompany trait. Every test still passes. Every test in the suite creates one company, one user and a handful of records, so there was never a second company to see the receipts of the first.
The scope from the first article of this series is only as good as the tests that try to break it. This article is about those tests: what to write, how to make forgetting impossible, and where tests stop being enough. It overlaps a little with the testing section of the delivery roadmap, and goes deeper on one topic.
The Test Suite That Only Knew One Company
A suite that creates one company proves that features work. It says nothing about isolation, because isolation is a statement about the other company. The first rule is simple: a leak test needs a second company with real data in it, and its assertion must be about that data.
It helps to list where tenant data can leak, because each place needs its own check:
- Reads: queries, lists, aggregates, route-model binding.
- Writes: the
company_idthat a new record receives. - Background work: jobs, listeners and scheduled tasks that run without a request.
- Shared storage: cache keys and file paths.
- Escape hatches: raw queries and anything that removes the scope.
The Fixture: Two Companies, Same Shape
Start with a helper that gives every test two companies, and put the foreign data inside the other one:
function twoCompanies(): array
{
return [Company::factory()->create(), Company::factory()->create()];
}
it('returns 404 for an invoice that belongs to another company', function () {
[$mine, $theirs] = twoCompanies();
$user = User::factory()->create();
$mine->users()->attach($user);
$foreign = app(TenantContext::class)->runAs(
$theirs->id,
fn () => Invoice::factory()->create(),
);
$this->actingAs($user)
->get("/{$mine->slug}/invoices/{$foreign->id}")
->assertNotFound();
$this->actingAs($user)
->get("/{$mine->slug}/invoices")
->assertDontSee($foreign->number);
});
it('returns 404 when the user is not a member of the company in the URL', function () {
[$mine, $theirs] = twoCompanies();
$user = User::factory()->create();
$mine->users()->attach($user);
$this->actingAs($user)->get("/{$theirs->slug}/invoices")->assertNotFound();
});
The relation names and factories are assumptions. What matters is the shape: the foreign record exists, the user is legitimately inside one company, and the test asks for the other one in two ways, by id and by URL. The first test covers route-model binding and the list. The second covers the middleware's membership check.
One trap: a test that asserts a 404 for an id that doesn't exist at all passes for the wrong reason. The foreign record has to be real.
A Guard Test for the Model You Haven't Written Yet
Hand-written leak tests only cover models somebody thought about. The opening scenario needs a different kind of test, one that fails when a new model forgets the trait, whether or not anyone wrote a test for it:
it('scopes every model that has a company_id column', function () {
$unscoped = collect(File::allFiles(app_path('Models')))
->map(fn ($file) => 'App\\Models\\'.$file->getBasename('.php'))
->filter(fn ($class) => is_subclass_of($class, Model::class))
->reject(fn ($class) => (new ReflectionClass($class))->isAbstract())
->reject(fn ($class) => in_array(BelongsToCompany::class, class_uses_recursive($class)))
->filter(fn ($class) => Schema::hasColumn((new $class)->getTable(), 'company_id'))
->values()
->all();
expect($unscoped)->toBe([]);
});
It walks the models directory, ignores anything that isn't a concrete model, and reports every model whose table has a company_id column but doesn't use the trait. When it fails, the diff names the class. It assumes a flat Models directory, so adjust the namespace mapping if you nest them. And if one model legitimately has the column without the scope (a pivot, say), put it in an explicit exception list inside the test, with a comment.
The companion check is that the scope fails closed. It is one short test, and it is the one that protects you from the day somebody queries from a context nobody thought of:
it('refuses to query tenant data without a company', function () {
Invoice::query()->count();
})->throws(MissingTenantContext::class);
Putting Escape Hatches on an Allowlist
Every system needs a few places that look across companies: an admin tool that moves a record between them, a nightly job that reads all tenants. Those are fine. The risk is the one nobody noticed. You can make every new bypass show up as a deliberate diff with a test that scans the source:
it('keeps scope bypasses on an allowlist', function () {
$needles = ['withoutGlobalScope', 'DB::table(', 'DB::select('];
$hits = collect(File::allFiles(app_path()))
->filter(fn ($file) => collect($needles)->contains(fn ($n) => str_contains($file->getContents(), $n)))
->map(fn ($file) => $file->getRelativePathname())
->sort()
->values()
->all();
expect($hits)->toBe([
'Console/Commands/ReassignInvoice.php',
'Tenancy/TenantScope.php',
]);
});
The list in the test is yours to decide. The point is friction: adding a file to it means writing it in a pull request, where a reviewer asks why. A text scan is crude and it will flag a comment that mentions a needle. For a list this short, that is an acceptable price.
Jobs, Cache and Files
Background work is where the tenant context is easiest to lose, because there is no request to carry it. Test the middleware that restores it, and that it restores the previous state afterwards:
it('runs a job inside its company and leaves no context behind', function () {
$company = Company::factory()->create();
$tenant = app(TenantContext::class);
$job = new class($company->id) { public function __construct(public int $companyId) {} };
(new RunsAsCompany)->handle($job, function () use ($tenant, $company) {
expect($tenant->id())->toBe($company->id);
});
expect($tenant->id())->toBeNull();
});
This assumes id() returns null when no company is set. For a stronger check, run the real job through the sync queue driver and assert on its effect for both companies.
Cache and files leak through naming. If keys are built by hand, a forgotten prefix puts two companies on the same key:
function tenantKey(string $key): string
{
return 'company:'.app(TenantContext::class)->id().':'.$key;
}
it('keeps cached values separate per company', function () {
[$a, $b] = twoCompanies();
$tenant = app(TenantContext::class);
$tenant->runAs($a->id, fn () => Cache::put(tenantKey('dashboard'), 'A'));
expect($tenant->runAs($b->id, fn () => Cache::get(tenantKey('dashboard'))))->toBeNull();
});
Be honest about what this proves: that tenantKey works. It can't stop a developer from calling Cache::put('dashboard', ...) directly. That part is a convention enforced in review, or by wrapping the cache in one small class that is the only thing allowed to call it. Files follow the same logic with a companies/{id}/ path prefix, and Storage::fake makes the test cheap.
What These Tests Still Miss
A green suite is evidence, not proof. Four gaps worth knowing:
- Raw queries. Global scopes apply to Eloquent models. A
DB::table()call bypasses them, which is why the allowlist above scans for it. - Joins. The scope filters the model you started from. A join to another tenant table is filtered only if you filter it yourself.
- Validation rules.
unique:invoices,numberruns a plain query across every company. It can reject a valid number because another company uses it, and it tells the user that the number exists. Scope the rule withRule::unique('invoices', 'number')->where('company_id', $companyId), and make the database index composite on(company_id, number). - Everything you didn't think of. For data where one leak would be a serious incident, add a second wall at the database. PostgreSQL's row-level security is the usual option. It adds a per-transaction company setting and a second set of database roles to manage, and the last article in the series covers it.
What This Costs
Two-company tests build more data, so they run slower than one-company tests. The guard and the allowlist add small rules the team has to maintain, and a developer in a hurry will find them annoying. That is the intended cost. The expensive failure is the one that reaches production, where a customer is the first to see another customer's invoice.
Conclusion
The suite in the opening failed because it only ever met one company. A second company in the fixture, a guard that fails when a model forgets the trait, and an allowlist for the places that cross the line turn isolation from a hope into something the build checks on every commit. Start with the guard test today: it takes ten minutes, and it tells you right away whether the scenario in the opening is already true in your app.
The next article moves from preventing leaks to seeing what each company is doing in production.