From 1af195f8b819df727aa87c30743ac3fd04e618f7 Mon Sep 17 00:00:00 2001 From: lukinovec Date: Thu, 2 Jan 2025 15:49:36 +0100 Subject: [PATCH] Test ecnrypted casts --- tests/TenantDatabaseManagerTest.php | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tests/TenantDatabaseManagerTest.php b/tests/TenantDatabaseManagerTest.php index 0b5376d9..b10d5ac3 100644 --- a/tests/TenantDatabaseManagerTest.php +++ b/tests/TenantDatabaseManagerTest.php @@ -405,6 +405,42 @@ expect($manager->databaseExists($name))->toBeTrue(); }); +test('decrypted password can be used to connect to a tenant db while the password is saved as encrypted', function (string|null $tenantDbPassword) { + config([ + 'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class, + 'tenancy.database.template_tenant_connection' => 'mysql', + ]); + + Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) { + return $event->tenant; + })->toListener()); + + // Create a tenant, either with a specific password, or with a password generated by the DB manager + $tenant = TenantWithEncryptedPassword::create([ + 'tenancy_db_name' => $name = 'foo' . Str::random(8), + 'tenancy_db_username' => 'user' . Str::random(4), + 'tenancy_db_password' => $tenantDbPassword, + ]); + + $decryptedPassword = $tenant->tenancy_db_password; + $encryptedPassword = $tenant->getAttributes()['tenancy_db_password']; // Password encrypted using the TenantWithEncryptedPassword model's encrypted cast + expect($decryptedPassword)->not()->toBe($encryptedPassword); + + $passwordSavedInDatabase = json_decode(DB::select('SELECT data FROM tenants LIMIT 1')[0]->data)->tenancy_db_password; + expect($encryptedPassword)->toBe($passwordSavedInDatabase); + + app(DatabaseManager::class)->connectToTenant($tenant); + + // Check if we got connected to the tenant DB + expect(config('database.default'))->toBe('tenant'); + expect(config('database.connections.tenant.database'))->toBe($name); + // Check if the decrypted password is used to connect to the tenant DB + expect(config('database.connections.tenant.password'))->toBe($decryptedPassword); +})->with([ + 'decrypted' . Str::random(8), // Use this password as the tenant DB password + null, // Let the DB manager generate the tenant DB password +]); + test('path used by sqlite manager can be customized', function () { Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) { return $event->tenant; @@ -529,3 +565,13 @@ function createUsersTable() $table->timestamps(); }); } + +class TenantWithEncryptedPassword extends Tenant +{ + protected function casts(): array + { + return [ + 'tenancy_db_password' => 'encrypted', + ]; + } +}