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…
The bug in question arises from the way Laravel's Eloquent ORM handles the precedence of AND and OR operators in SQL queries. When a tenant filter is applied using a global scope, Eloquent automatically groups OR conditions in parentheses to ensure the tenant filter is applied correctly. However, this protection fails when the tenant filter is added in other ways, resulting in a vulnerability that can expose sensitive data.
The issue occurs when a query is constructed using OR conditions and a tenant filter, but the OR operation takes precedence over the AND operation. For example, the query `select * from invoices where status = 'draft' or status = 'void' and tenant_id = 5` is interpreted as `where status = 'draft' or (status = 'void' and tenant_id = 5)`. Consequently, all draft invoices from every tenant are retrieved, while only the void invoices from the specified tenant are intended.
Laravel's applyScopes() method, which is responsible for adding where clauses to query builders, already wraps OR conditions in parentheses to maintain the correct logical grouping. However, this safeguard does not apply to all instances where a tenant filter is added. The helper function group() was introduced to address these overlooked scenarios, ensuring that all tenant conditions are grouped together with AND operators, preventing unintended data leakage.
The fix involves modifying the code paths that add tenant conditions to ensure they always use this helper function to properly group the WHERE clauses. This simple yet effective solution prevents the bug from affecting any code that adds tenant predicates, whether through macros, custom builders, repository base classes, or custom pivot relations. By grouping all tenant conditions in one helper function, the solution maintains the integrity of SQL queries and ensures data security.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to