AND binds tighter than OR: the tenant filter bug I fixed in three places
Single-database multi-tenancy in Laravel usually starts with one line: a global scope that adds where tenant_id = ? to every query. It works in the demo. Then someone writes a query with an OR in it.
I maintain laravel-tenancy, a single-database tenancy package that is meant to fail closed. While hardening it I found the same mistake in three different code paths, and all three come down to operator precedence. This post is about that one bug: why it happens, how much Eloquent protects you from it, and where that protection stops.
The bug in one line
SQL evaluates AND before OR. So this:
select * from invoices where status = 'draft' or status = 'void' and tenant_id = 5 is read as:
where status = 'draft' or (status = 'void' and tenant_id = 5) Every draft invoice from every tenant comes back. The tenant filter only applies to the void ones. Nothing errors, tests that only create one tenant pass, and the leak only shows up once a second tenant has matching rows.
What Eloquent already does for you
If you add the tenant filter with a normal global scope, Laravel handles the common case. When applyScopes() runs a scope that adds wheres, it calls groupWhereSliceForScope() on the wheres that were there before. If any of them was added with an or boolean, they get wrapped in a nested group:
if ($whereBooleans->contains(fn ($logicalOperator) => str_contains($logicalOperator, 'or'))) { $query->wheres[] = $this->createNestedWhere( $whereSlice, str_replace(' not', '', $whereBooleans->first()) ); } So ->where('status', 'draft')->orWhere('status', 'void') plus your scope becomes:
where (status = 'draft' or status = 'void') and tenant_id = 5 It's a small piece of framework code that a lot of apps depend on without knowing it. Worth reading once in Illuminate/Database/Eloquent/Builder.php.
Where the protection stops
Look at what that check inspects: the boolean of each where entry. That's or only when the clause was added with orWhere() and friends. Everything else slips past it:
- Raw SQL.
whereRaw("title = 'a' OR title = 'b'")is a single where entry with the booleanand. Laravel sees nothing to group. The database sees anOR. - Expressions. A
ConditionExpression, orDB::raw()used as a where value, can carry anORthe same way. - Anything outside
applyScopes(). If your tenancy code adds the predicate itself, the grouping never runs at all.
In my package that last point covered more than I expected. Write paths that don't go through global scopes, like forceDelete(), updateOrInsert() and updateFrom(), had the tenant predicate appended by the package directly. So did updates after withoutGlobalScopes(), where the package puts the tenant back. And the tenant-aware pivot relations added their own condition to the pivot table. Same mistake, three places.
If you have your own tenancy layer, search for anything that calls ->where('tenant_id', ...) on a builder that already has user conditions on it: macros, custom builders, repository base classes, pivot relations, and code that runs withoutGlobalScopes() and adds the tenant back by hand.
The fix
I stopped trying to decide when grouping is needed and group every time. Every path that adds a tenant condition now calls one helper first:
public static function group(Builder $query): void { if ($query->wheres === []) { return; } $group = $query->forNestedWhere(); $group->wheres = array_map(self::endRawClause(...), $query->wheres); $query->wheres = [['type' => 'Nested', 'query' => $group, 'boolean' => 'and']]; } It moves all existing wheres into one parenthesised group, and the tenant condition is added after it. Bindings stay correct because the nested group compiles in the same position as the clauses it replaced. A redundant pair of parentheses costs nothing; a missing pair leaks data.
One detail I didn't expect: raw SQL can end with a line comment.
->whereRaw("title = 'a' OR title = 'b' -- search") Wrap that in parentheses and add the tenant predicate, and the -- comments out the closing parenthesis and everything after it. So the helper appends a newline to every raw clause before grouping it:
private static function endRawClause(mixed $where): mixed { if (\is_array($where) && ($where['type'] ?? null) === 'raw' && \is_string($where['sql'] ?? null)) { $where['sql'] .= "\n"; } return $where; } Grouping in one helper also means the next code path someone adds doesn't have to remember any of this. It calls group() like the others.
Testing it so it stays fixed
A test with one tenant can't catch this bug. Every test here creates two tenants, gives the second one a row that matches the OR branch, and checks it can't be read or touched:
it('keeps raw OR updates and deletes inside the tenant', function (): void { Tenancy::initialize($this->a); expect(Post::query()->whereRaw("title = 'b-dummy' OR title = 'nope'")->update(['title' => 'x']))->toBe(0) ->and(Post::query()->whereRaw("title = 'b-dummy' OR title = 'nope'")->delete())->toBe(0) ->and(titlesOf($this->b))->toBe(['b-dummy']); }); Tenant A is active, and the query matches only tenant B's row. The update and delete must affect nothing, and B's row must still be there afterwards. I wrote this and the others before touching the code, and they failed first. There's one per path: raw wheres, condition expressions, the trailing comment, forceDelete(), updateOrInsert(), updateFrom(), and a global scope that itself contains a raw OR.
Fail closed, in practice
The point of a fail-closed tenancy package is that a mistake should produce no rows or an exception, never someone else's rows. Precedence bugs are the opposite: a wrong query that looks like it works. So the package's job isn't only to add a filter. It has to make sure nothing in the query can outvote the filter.
I'm working toward a stable v1.0.0 of the package, and this fix is part of it. If you've hit this in your own code, or you know another place where the grouping gets skipped, I'd like to hear about it in the comments.