diff --git a/app/Services/Databases/DatabasePasswordService.php b/app/Services/Databases/DatabasePasswordService.php index ebee37bca..69510ed6a 100644 --- a/app/Services/Databases/DatabasePasswordService.php +++ b/app/Services/Databases/DatabasePasswordService.php @@ -32,7 +32,10 @@ class DatabasePasswordService $password = Utilities::randomStringWithSpecialCharacters(24); $this->connection->transaction(function () use ($database, $password) { - $database->sharedLock()->update([ + // Lock the row to serialize concurrent rotations of the same database. + $database->newQuery()->whereKey($database->getKey())->lockForUpdate()->firstOrFail(); + + $database->update([ 'password' => $this->encrypter->encrypt($password), ]); diff --git a/tests/Integration/Services/Databases/DatabasePasswordServiceTest.php b/tests/Integration/Services/Databases/DatabasePasswordServiceTest.php new file mode 100644 index 000000000..26f72c592 --- /dev/null +++ b/tests/Integration/Services/Databases/DatabasePasswordServiceTest.php @@ -0,0 +1,77 @@ +repository = $this->mock(DatabaseRepository::class); + } + + /** + * Test that a database password is rotated correctly. + */ + public function testDatabasePasswordCanBeRotated() + { + $server = $this->createServerModel(); + $host = DatabaseHost::factory()->create(['node_id' => $server->node_id]); + + $database = Database::factory()->create([ + 'server_id' => $server->id, + 'database_host_id' => $host->id, + 'password' => encrypt('original'), + ]); + + $other = Database::factory()->create([ + 'server_id' => $server->id, + 'database_host_id' => $host->id, + 'password' => encrypt('unchanged'), + ]); + + $password = null; + + $this->repository->expects('dropUser')->with($database->username, $database->remote); + $this->repository->expects('createUser')->with( + $database->username, + $database->remote, + \Mockery::on(function ($value) use (&$password) { + $password = $value; + + return true; + }), + $database->max_connections + ); + $this->repository->expects('assignUserToDatabase')->with($database->database, $database->username, $database->remote); + $this->repository->expects('flush')->withNoArgs(); + + $response = $this->getService()->handle($database); + + // The new password is returned, set on the host, and stored. + $this->assertSame(24, strlen($response)); + $this->assertSame($response, $password); + $this->assertSame($response, decrypt($database->refresh()->password)); + + // Other databases are untouched. + $this->assertSame('unchanged', decrypt($other->refresh()->password)); + } + + private function getService(): DatabasePasswordService + { + return $this->app->make(DatabasePasswordService::class); + } +}