From ca94f2f48b339cb86235304bc4a760fe15d04cb8 Mon Sep 17 00:00:00 2001 From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com> Date: Sun, 11 Oct 2026 09:37:29 -0400 Subject: [PATCH] transfer actions --- app/Actions/Transfers/InitiateTransfer.php | 83 +++++++++++++++++++ .../Transfers/InitiatesTransfers.php | 7 ++ .../Api/Admin/Servers/TransferController.php | 6 +- .../Admin/Servers/TransferServerRequest.php | 55 ++---------- phpstan.neon | 1 - .../Transfers/InitiateTransferTest.php | 79 ++++++++++++++++++ .../Services/BackendWriteConsistencyTest.php | 13 ++- 7 files changed, 192 insertions(+), 52 deletions(-) create mode 100644 tests/Integration/Actions/Transfers/InitiateTransferTest.php diff --git a/app/Actions/Transfers/InitiateTransfer.php b/app/Actions/Transfers/InitiateTransfer.php index aab86bf46..c0e206c76 100644 --- a/app/Actions/Transfers/InitiateTransfer.php +++ b/app/Actions/Transfers/InitiateTransfer.php @@ -6,11 +6,16 @@ namespace Pterodactyl\Actions\Transfers; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Validator as ValidatorFactory; +use Illuminate\Validation\Rule; +use Illuminate\Validation\ValidationException; +use Illuminate\Validation\Validator; use Pterodactyl\Contracts\Transfers\FailsTransfers; use Pterodactyl\Contracts\Transfers\InitiatesTransfers; use Pterodactyl\Enum\JwtScope; use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Facades\Daemon; +use Pterodactyl\Http\Requests\Concerns\ValidatesArrayExistence; use Pterodactyl\Models\Allocation; use Pterodactyl\Models\Node; use Pterodactyl\Models\Server; @@ -20,11 +25,59 @@ use Throwable; final readonly class InitiateTransfer implements InitiatesTransfers { + use ValidatesArrayExistence; + public function __construct( private NodeJWTService $nodeJWTService, private FailsTransfers $failTransfer, ) {} + /** + * A transfer's fields: a node other than the server's own, the allocation the server + * takes as its default there, and any additional ones. The default allocation must + * exist and be no server's default; the additional ones are integers or numeric + * strings. Once these pass, validateAllocations() checks the allocations are free and + * on the node. + * + * @return NormalizedValidationRules + */ + public static function rules(Server $server): array + { + return [ + 'node_id' => ['required', 'integer', 'exists:nodes,id', Rule::notIn([$server->node_id])], + 'allocation_id' => ['required', 'bail', 'unique:servers', 'exists:allocations,id'], + 'allocation_additional' => ['nullable', 'array', 'list'], + 'allocation_additional.*' => ['required', Rule::anyOf([['integer:strict'], ['string']]), 'integer'], + ]; + } + + /** + * Once the rules pass, adds an allocation_id error unless every allocation chosen is + * unassigned and on the target node. They are counted in one query. + */ + public static function validateAllocations(Validator $validator): void + { + if ($validator->errors()->isNotEmpty()) { + return; + } + + $input = $validator->safe(); + $ids = array_unique([ + $input->integer('allocation_id'), + ...array_map(fn (int|string $key): int => $input->integer('allocation_additional.'.$key), array_keys($input->array('allocation_additional'))), + ]); + + $count = Allocation::query() + ->whereIn('id', $ids) + ->where('node_id', $input->integer('node_id')) + ->whereNull('server_id') + ->count(); + + if ($count !== count($ids)) { + $validator->errors()->add('allocation_id', 'The selected allocation must be an unassigned allocation on the target node.'); + } + } + /** * Records the transfer, reserves the target allocations, and tells the destination * node to begin pulling the server. Wings is called after the records commit; if it @@ -33,10 +86,13 @@ final readonly class InitiateTransfer implements InitiatesTransfers * @param list $additionalAllocations * * @throws DisplayException + * @throws ValidationException * @throws Throwable */ public function initiate(Server $server, Node $node, int $allocationId, array $additionalAllocations): ServerTransfer { + $additionalAllocations = $this->additionalAllocations($server, $node, $allocationId, $additionalAllocations); + $transfer = DB::transaction(function () use ($server, $node, $allocationId, $additionalAllocations): ServerTransfer { $server = $server->newQuery()->whereKey($server->getKey())->lockForUpdate()->firstOrFail(); throw_unless($node->isViable($server->memory, $server->disk), DisplayException::class, trans('admin/server.alerts.transfer_not_viable')); @@ -89,4 +145,31 @@ final readonly class InitiateTransfer implements InitiatesTransfers return $transfer->refresh(); } + + /** + * Validates the transfer of the server to the node and returns the additional + * allocations, as integers. Missing additional allocations fail `allocation_additional.N` + * as an exists rule would, all looked up in one query. + * + * @param list $additionalAllocations + * @return list + * + * @throws ValidationException + */ + private function additionalAllocations(Server $server, Node $node, int $allocationId, array $additionalAllocations): array + { + $validator = ValidatorFactory::make([ + 'node_id' => $node->id, + 'allocation_id' => $allocationId, + 'allocation_additional' => $additionalAllocations, + ], self::rules($server)); + $validator->after(function () use ($validator): void { + $this->validateArrayExistence($validator, 'allocation_additional', Allocation::query()); + self::validateAllocations($validator); + }); + + $input = $validator->safe(); + + return array_map(fn (int|string $key): int => $input->integer('allocation_additional.'.$key), array_keys($input->array('allocation_additional'))); + } } diff --git a/app/Contracts/Transfers/InitiatesTransfers.php b/app/Contracts/Transfers/InitiatesTransfers.php index a52698d25..d54f20270 100644 --- a/app/Contracts/Transfers/InitiatesTransfers.php +++ b/app/Contracts/Transfers/InitiatesTransfers.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pterodactyl\Contracts\Transfers; +use Illuminate\Validation\ValidationException; use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Models\Node; use Pterodactyl\Models\Server; @@ -16,9 +17,15 @@ interface InitiatesTransfers * Records the transfer, reserves the target allocations, and tells the destination * node to begin pulling the server. * + * The node and allocations are validated here, so they can come straight from any + * caller: the node must not be the server's own, the default allocation must be no + * server's default, and every allocation must exist, be unassigned and be on the node. + * Errors are reported under node_id, allocation_id and allocation_additional.N. + * * @param list $additionalAllocations * * @throws DisplayException + * @throws ValidationException * @throws Throwable */ public function initiate(Server $server, Node $node, int $allocationId, array $additionalAllocations): ServerTransfer; diff --git a/app/Http/Controllers/Api/Admin/Servers/TransferController.php b/app/Http/Controllers/Api/Admin/Servers/TransferController.php index 34980eec8..2ecfcadec 100644 --- a/app/Http/Controllers/Api/Admin/Servers/TransferController.php +++ b/app/Http/Controllers/Api/Admin/Servers/TransferController.php @@ -42,10 +42,10 @@ class TransferController extends AdminApiController #[ScribeResponse(self::TRANSFER_NOT_VIABLE_ERROR, status: 400, description: 'The destination node cannot fit the server or the server cannot currently be transferred.')] public function __invoke(TransferServerRequest $request, InitiatesTransfers $transfers, Server $server): Response { - $data = $request->payload(); - $node = Node::query()->findOrFail($data['node_id']); + $validated = $request->safe(); + $node = Node::query()->findOrFail($validated->integer('node_id')); - $transfers->initiate($server, $node, $data['allocation_id'], $data['allocation_additional']); + $transfers->initiate($server, $node, $validated->integer('allocation_id'), $request->additionalAllocations()); Activity::event('admin:server.transfer') ->subject($server) diff --git a/app/Http/Requests/Api/Admin/Servers/TransferServerRequest.php b/app/Http/Requests/Api/Admin/Servers/TransferServerRequest.php index c9bcf3646..794b7da6d 100644 --- a/app/Http/Requests/Api/Admin/Servers/TransferServerRequest.php +++ b/app/Http/Requests/Api/Admin/Servers/TransferServerRequest.php @@ -5,13 +5,12 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Admin\Servers; use Closure; -use Illuminate\Validation\Rule; use Illuminate\Validation\Validator; +use Pterodactyl\Actions\Transfers\InitiateTransfer; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Concerns\ValidatesArrayExistence; use Pterodactyl\Models\Allocation; use Pterodactyl\Models\Server; -use Pterodactyl\Support\JsonValueGuard; class TransferServerRequest extends ServerWriteRequest { @@ -29,23 +28,11 @@ class TransferServerRequest extends ServerWriteRequest */ public function rules(): array { - $server = $this->parameter('server', Server::class); - - return [ - 'node_id' => [ - 'required', - 'integer', - 'exists:nodes,id', - Rule::notIn([$server->node_id]), - ], - 'allocation_id' => ['required', 'bail', 'unique:servers', 'exists:allocations,id'], - 'allocation_additional' => ['nullable', 'array', 'list'], - 'allocation_additional.*' => ['required', Rule::anyOf([['integer:strict'], ['string']]), 'integer'], - ]; + return InitiateTransfer::rules($this->parameter('server', Server::class)); } /** - * Chosen allocations must belong to the target node and be unassigned. + * Chosen allocations must exist, belong to the target node and be unassigned. * * @return list */ @@ -53,43 +40,19 @@ class TransferServerRequest extends ServerWriteRequest { return [function (Validator $validator): void { $this->validateArrayExistence($validator, 'allocation_additional', Allocation::query()); - - // Skip cross-field checks if the basic rules already failed. - if ($validator->errors()->isNotEmpty()) { - return; - } - - $nodeId = $this->integer('node_id'); - $ids = array_unique([$this->integer('allocation_id'), ...$this->additionalAllocations()]); - $count = Allocation::query() - ->whereIn('id', $ids) - ->where('node_id', $nodeId) - ->whereNull('server_id') - ->count(); - - if ($count !== count($ids)) { - $validator->errors()->add('allocation_id', 'The selected allocation must be an unassigned allocation on the target node.'); - } + InitiateTransfer::validateAllocations($validator); }]; } /** - * Normalize the validated transfer payload for the controller. + * The validated additional allocation ids, as integers. * - * @return ServerTransferData + * @return list */ - public function payload(): array + public function additionalAllocations(): array { - return [ - 'node_id' => $this->integer('node_id'), - 'allocation_id' => $this->integer('allocation_id'), - 'allocation_additional' => $this->additionalAllocations(), - ]; - } + $validated = $this->safe(); - /** @return list */ - private function additionalAllocations(): array - { - return JsonValueGuard::normalizedIntegerList(JsonValueGuard::integerStringList($this->input('allocation_additional') ?? [])); + return array_map(fn (int|string $key): int => $validated->integer('allocation_additional.'.$key), array_keys($validated->array('allocation_additional'))); } } diff --git a/phpstan.neon b/phpstan.neon index 68cb30e56..446d825d7 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -83,7 +83,6 @@ parameters: DatabaseModelCreationData: 'array{database: string, remote: string, database_host_id: int, max_connections?: int|null, server_id: int, username: string, password: string}' MultipartUploadPart: 'array{etag: string, part_number: int}' SftpAuthenticationData: 'array{type: string|null, username: string, password: string}' - ServerTransferData: 'array{node_id: int, allocation_id: int, allocation_additional: list}' BackupUploadParts: 'array{parts: list, part_size: int}' GeneralSettingsData: "array{'app:name': string, 'pterodactyl:auth:2fa_required': int, 'app:locale': string}" AdvancedSettingsData: "array{'recaptcha:enabled': string, 'recaptcha:secret_key'?: string, 'recaptcha:website_key': string, 'pterodactyl:guzzle:timeout': int, 'pterodactyl:guzzle:connect_timeout': int, 'pterodactyl:client_features:allocations:enabled': string, 'pterodactyl:client_features:allocations:range_start': int|null, 'pterodactyl:client_features:allocations:range_end': int|null}" diff --git a/tests/Integration/Actions/Transfers/InitiateTransferTest.php b/tests/Integration/Actions/Transfers/InitiateTransferTest.php new file mode 100644 index 000000000..009d3089b --- /dev/null +++ b/tests/Integration/Actions/Transfers/InitiateTransferTest.php @@ -0,0 +1,79 @@ +create(['location_id' => $server->node->location_id, 'memory' => 102400, 'disk' => 102400]); +} + +test('transfers started without the http api meet the same rules', function (string $case, string $field): void { + $server = $this->createServerModel(); + $target = targetNode($server); + $free = Allocation::factory()->for($target)->create(['server_id' => null]); + $fake = new FakeDaemonTransfer; + + [$node, $allocationId, $additional] = match ($case) { + 'own node' => [$server->node, Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => null])->id, []], + 'missing default' => [$target, 0, []], + 'another default' => [$target, $this->createServerModel(['node_id' => $target->id])->allocation_id, []], + 'default on another node' => [$target, Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => null])->id, []], + 'assigned additional' => [$target, $free->id, [Allocation::factory()->for($target)->create(['server_id' => $server->id])->id]], + 'additional on another node' => [$target, $free->id, [Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => null])->id]], + 'missing additional' => [$target, $free->id, [$free->id, 999999]], + 'malformed additional' => [$target, $free->id, [1.5]], + 'additional not a list' => [$target, $free->id, ['selected' => $free->id]], + }; + + try { + $this->app->make(InitiatesTransfers::class)->initiate($server, $node, $allocationId, $additional); + $this->fail('The transfer was started.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + $fake->assertNothingHappened(); + $this->assertDatabaseMissing('server_transfers', ['server_id' => $server->id]); + expect($free->refresh()->server_id)->toBeNull(); +})->with([ + 'a transfer to the server\'s own node' => ['own node', 'node_id'], + 'a default allocation that does not exist' => ['missing default', 'allocation_id'], + 'a default allocation that is another server\'s default' => ['another default', 'allocation_id'], + 'a default allocation on another node' => ['default on another node', 'allocation_id'], + 'an additional allocation that is assigned' => ['assigned additional', 'allocation_id'], + 'an additional allocation on another node' => ['additional on another node', 'allocation_id'], + 'an additional allocation that does not exist' => ['missing additional', 'allocation_additional.1'], + 'an additional allocation that is not an integer' => ['malformed additional', 'allocation_additional.0'], + 'additional allocations that are not a list' => ['additional not a list', 'allocation_additional'], +]); + +test('additional allocations may be numeric strings, and every allocation is reserved', function (): void { + $server = $this->createServerModel(); + $target = targetNode($server); + $primary = Allocation::factory()->for($target)->create(['server_id' => null]); + $additional = Allocation::factory()->for($target)->create(['server_id' => null]); + $fake = new FakeDaemonTransfer; + + $transfer = $this->app->make(InitiatesTransfers::class)->initiate($server, $target, $primary->id, [(string) $additional->id]); + + $fake->assertNotified(); + expect($transfer->new_node)->toBe($target->id) + ->and($transfer->new_allocation)->toBe($primary->id) + ->and($transfer->new_additional_allocations)->toBe([$additional->id]) + ->and($primary->refresh()->server_id)->toBe($server->id) + ->and($additional->refresh()->server_id)->toBe($server->id); +}); diff --git a/tests/Integration/Services/BackendWriteConsistencyTest.php b/tests/Integration/Services/BackendWriteConsistencyTest.php index bc8276647..e40e65f77 100644 --- a/tests/Integration/Services/BackendWriteConsistencyTest.php +++ b/tests/Integration/Services/BackendWriteConsistencyTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pterodactyl\Tests\Pest\Integration\Services\BackendWriteConsistencyTest; +use Illuminate\Database\Events\QueryExecuted; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Notification; @@ -48,14 +49,22 @@ beforeEach(function (): void { }); }); -test('a transfer rejects an allocation claimed after request validation without reserving the rest', function (bool $claimPrimary): void { +test('a transfer rejects an allocation claimed after validation without reserving the rest', function (bool $claimPrimary): void { $server = $this->createServerModel(); $other = $this->createServerModel(); $node = Node::factory()->create(['location_id' => $server->node->location_id, 'memory' => 102400, 'disk' => 102400]); $primary = Allocation::factory()->for($node)->create(['server_id' => null]); $additional = Allocation::factory()->for($node)->create(['server_id' => null]); - ($claimPrimary ? $primary : $additional)->update(['server_id' => $other->id]); $fake = new FakeDaemonTransfer; + // The action checks the allocations are free before its transaction opens, so another + // server claims one right after that check. + $claimed = false; + DB::listen(function (QueryExecuted $query) use (&$claimed, $claimPrimary, $primary, $additional, $other): void { + if (! $claimed && str_contains($query->sql, 'from `allocations`') && str_contains($query->sql, '`server_id` is null')) { + $claimed = true; + ($claimPrimary ? $primary : $additional)->update(['server_id' => $other->id]); + } + }); expect(fn () => $this->app->make(InitiatesTransfers::class)->initiate($server, $node, $primary->id, [$additional->id])) ->toThrow(DisplayException::class, 'The selected allocations are no longer available on the target node.'); $this->assertDatabaseMissing('server_transfers', ['server_id' => $server->id]);