From 331df8e239ba22700cf1d7779aa66f34e5a27ae2 Mon Sep 17 00:00:00 2001 From: lukinovec Date: Wed, 26 Apr 2023 12:42:19 +0200 Subject: [PATCH] Update Postgres tests --- tests/PostgresTest.php | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/tests/PostgresTest.php b/tests/PostgresTest.php index 40914e04..9b186088 100644 --- a/tests/PostgresTest.php +++ b/tests/PostgresTest.php @@ -11,6 +11,10 @@ beforeEach(function () { DB::setDefaultConnection('pgsql'); config(['tenancy.models.tenant' => Tenant::class]); + + foreach (DB::select('select * from pg_policies') as $policy) { + DB::statement("DROP POLICY IF EXISTS {$policy->policyname} ON {$policy->tablename};"); + } }); test('postgres user can get created using the job', function() { @@ -43,14 +47,39 @@ test('postgres user can get deleted using the job', function() { test('correct rls policies get created using the command', function() { config([ - 'tenancy.models.rls' => $rlsModels = [ + 'tenancy.models.rls' => [ Post::class, // Primary model (directly belongs to tenant) - Comment::class, // Secondary model (belongs to tenant through Post) ], ]); + $getRlsPolicies = fn () => DB::select('select * from pg_policies'); + $getModelTables = fn () => collect(config('tenancy.models.rls'))->map(fn (string $model) => (new $model)->getTable()); + $getRlsTables = fn() => $getModelTables()->map(fn ($table) => DB::select('select relname, relrowsecurity, relforcerowsecurity from pg_class WHERE oid = ' . "'$table'::regclass"))->collapse(); expect($getRlsPolicies())->toHaveCount(0); pest()->artisan('tenants:create-rls-policies'); - expect($getRlsPolicies())->toHaveCount(count($rlsModels)); + expect($getRlsPolicies())->toHaveCount(count(config('tenancy.models.rls'))); // 1 + expect($getRlsTables())->toHaveCount(count(config('tenancy.models.rls'))); // 1 + // Check if tables with policies are RLS protected + foreach ($getRlsTables() as $table) { + expect($getModelTables())->toContain($table->relname); + expect($table->relforcerowsecurity)->toBeTrue(); + } + + config([ + 'tenancy.models.rls' => array_merge([ + ScopedComment::class, // Add secondary model to RLS protected models (belongs to tenant through Post) + ], config('tenancy.models.rls')), + ]); + + pest()->artisan('tenants:create-rls-policies'); + // Check if tables with policies are RLS protected (even the ones not directly related to the tenant) + // Models related to tenant through some model must use the BelongsToPrimaryModel trait to work properly + expect($getRlsPolicies())->toHaveCount(count(config('tenancy.models.rls'))); // 2 + expect($getRlsTables())->toHaveCount(count(config('tenancy.models.rls'))); // 2 + + foreach ($getRlsTables() as $table) { + expect($getModelTables())->toContain($table->relname); + expect($table->relforcerowsecurity)->toBeTrue(); + } });