Skip to content

Commit

Permalink
Test ecnrypted casts
Browse files Browse the repository at this point in the history
  • Loading branch information
lukinovec committed Jan 2, 2025
1 parent 6b38a35 commit 1af195f
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions tests/TenantDatabaseManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -529,3 +565,13 @@ function createUsersTable()
$table->timestamps();
});
}

class TenantWithEncryptedPassword extends Tenant
{
protected function casts(): array
{
return [
'tenancy_db_password' => 'encrypted',
];
}
}

0 comments on commit 1af195f

Please sign in to comment.