PHP Laravel

Enhancing Tenant Isolation in Laravel Queues

Introduction

In multi-tenant applications, ensuring data isolation between tenants is paramount. We encountered an issue in our Reimpact/platform project where queue jobs and dashboard caching mechanisms weren't properly respecting the tenant context, leading to errors and potential data leakage.

The Problem: Missing Tenant Context

Two key areas were affected:

  1. Queue Jobs: Certain queue jobs, such as RefreshRecipeWeights and WarmCompanyDashboardCache, were executed without setting the proper tenant search path. This resulted in "relation does not exist" errors because the jobs were attempting to access tables in the default schema instead of the tenant-specific schema.
  2. Dashboard Cache: The DashboardCacheHelper was filtering massive_uploads based on a company_id column, which doesn't exist on tenant-specific tables. This caused incorrect data to be included in the dashboard cache.

The Solution: Enforcing Tenant Context

The fix involved two main steps:

  1. Adding Tenant Context to Queue Jobs: We modified the queue jobs to ensure that the TenantContext is properly set before execution. This guarantees that the jobs operate within the correct tenant's database schema. An example of setting the tenant context might look like this:
class RefreshRecipeWeights implements ShouldQueue
{
    public function handle()
    {
        $tenant = Tenant::current();
        DB::connection('tenant')->setSchema($tenant->schema);

        // ... job logic ...
    }
}
  1. Removing company_id Filtering: We removed the unnecessary filtering by company_id from the DashboardCacheHelper. Since the tenant context is now correctly set, the queries will automatically operate on the correct tenant's data.

Benefits

  • Improved Data Isolation: Ensures that queue jobs and caching mechanisms operate within the correct tenant context, preventing data leakage and errors.
  • Increased Reliability: Eliminates "relation does not exist" errors caused by missing tenant context.
  • Simplified Code: Removes unnecessary filtering logic, making the code cleaner and easier to maintain.

Conclusion

Ensuring proper tenant isolation in multi-tenant applications requires careful attention to detail. By adding the TenantContext to queue jobs and removing unnecessary filtering, we've significantly improved the reliability and security of our Reimpact/platform application. Always double-check that background processes respect tenant boundaries to prevent unexpected issues in production.

Enhancing Tenant Isolation in Laravel Queues
GERARDO RUIZ

GERARDO RUIZ

Author

Share: