server details action

This commit is contained in:
robert dennis
2026-10-12 05:18:56 -04:00
parent f4eee5e3f6
commit ac79b03483
17 changed files with 284 additions and 91 deletions
+4 -3
View File
@@ -52,14 +52,15 @@ final readonly class CreateServer implements CreatesServers
* A new server's fields. The default allocation and any additional ones must exist and
* belong to no server. Memory, disk, CPU and the feature limits take 0 for unlimited,
* and swap takes -1. The CPU threads are a pattern of cores such as "0-1,3", which a
* bare number also matches.
* bare number also matches. Pass a server being updated so its own external id is not
* taken for a duplicate.
*
* @return NormalizedValidationRules
*/
public static function rules(): array
public static function rules(?Server $ignore = null): array
{
return [
'external_id' => ['sometimes', 'nullable', 'string', 'between:1,191', Rule::unique('servers', 'external_id')],
'external_id' => ['sometimes', 'nullable', 'string', 'between:1,191', Rule::unique('servers', 'external_id')->ignore($ignore)],
'name' => ['required', 'string', 'min:1', 'max:191'],
'description' => ['nullable', 'string'],
'owner_id' => ['required', 'integer', 'exists:users,id'],
+48 -11
View File
@@ -5,8 +5,8 @@ declare(strict_types=1);
namespace Pterodactyl\Actions\Servers;
use Illuminate\Foundation\Bus\PendingDispatch;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Pterodactyl\Contracts\Servers\UpdatesServerDetails;
use Pterodactyl\Jobs\RevokeSftpAccessJob;
use Pterodactyl\Models\Server;
@@ -19,21 +19,58 @@ final readonly class UpdateServerDetails implements UpdatesServerDetails
public function __construct(private ExtensionFields $extensions) {}
/**
* @param ServerDetailsModificationData $data
* A server's details: its external id, name, owner and description, checked as they
* are when a server is created. Pass the server being updated so its own external id
* is not taken for a duplicate.
*
* @return NormalizedValidationRules
*/
public static function rules(?Server $server = null): array
{
$rules = CreateServer::rules($server);
return [
'external_id' => $rules['external_id'],
'name' => $rules['name'],
'owner_id' => $rules['owner_id'],
'description' => $rules['description'],
];
}
/**
* Validates details input for the server and returns the details it describes. Every
* detail is replaced: an external id left out or empty is cleared, and a description
* left out or null becomes empty.
*
* @param ActionInput $input
* @return array{external_id: string|null, owner_id: int, name: string, description: string}
*/
public static function attributes(array $input, ?Server $server = null): array
{
$input = Validator::make($input, self::rules($server))->safe();
return [
'external_id' => $input->filled('external_id') ? $input->string('external_id')->toString() : null,
'owner_id' => $input->integer('owner_id'),
'name' => $input->string('name')->toString(),
'description' => $input->string('description')->toString(),
];
}
/**
* @param ActionInput $input
*
* @throws Throwable
*/
public function update(Server $server, array $data): Server
public function update(Server $server, array $input): Server
{
return DB::transaction(function () use ($data, $server): Server {
$attributes = self::attributes($input, $server);
$extensions = ValidatedExtensionValues::of($input['extensions'] ?? null);
return DB::transaction(function () use ($server, $attributes, $extensions): Server {
$original = $server->user;
$server->forceFill([
'external_id' => Arr::get($data, 'external_id'),
'owner_id' => Arr::get($data, 'owner_id'),
'name' => Arr::get($data, 'name'),
'description' => Arr::get($data, 'description') ?? '',
])->saveOrFail();
$this->extensions->save($server, ValidatedExtensionValues::of($data['extensions'] ?? null));
$server->forceFill($attributes)->saveOrFail();
$this->extensions->save($server, $extensions);
// Revoke the previous owner's Wings SFTP token after an ownership change.
if ($server->owner_id !== $original->id) {
@@ -10,9 +10,15 @@ use Throwable;
interface UpdatesServerDetails
{
/**
* @param ServerDetailsModificationData $data
* Update a server's details. The input is validated here, so it can come straight from
* any caller. Every detail is replaced: an external id left out is cleared and a
* description left out becomes empty. A new owner takes the server's SFTP access from
* the previous one. Extension field values go under `extensions` as
* ValidatedExtensionValues.
*
* @param ActionInput $input name and owner_id, and optionally external_id and description
*
* @throws Throwable
*/
public function update(Server $server, array $data): Server;
public function update(Server $server, array $input): Server;
}
@@ -33,7 +33,7 @@ class DetailsController extends AdminApiController
{
$updated = $details->update(
$server,
$request->payload()
$request->actionInput()
);
Activity::event('admin:server.details')
@@ -49,7 +49,7 @@ class ServerDetailsController extends ApplicationApiController
{
$updated = $details->update(
$server,
$request->payload()
$request->actionInput()
);
return Fractal::item($updated)
@@ -51,13 +51,13 @@ class SettingsController extends ClientApiController
$previousName = $server->name;
$previousDescription = $server->description;
// The action writes owner and external ID too, so pass the current values
// through unchanged; only the name and description come from the request.
// The action replaces the owner, external ID and description too, so pass the
// current values through; the name, and a description if sent, come from the request.
$server = $details->update($server, [
'external_id' => $server->external_id,
'owner_id' => $server->owner_id,
'name' => $request->string('name')->toString(),
'description' => $request->has('description') ? $request->description() : $server->description,
'description' => $server->description,
...$request->actionInput(),
]);
if ($previousName !== $server->name) {
@@ -4,10 +4,10 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Admin\Servers;
use Pterodactyl\Actions\Servers\UpdateServerDetails;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Http\Requests\Concerns\ValidatesExtensionFields;
use Pterodactyl\Models\Server;
use Pterodactyl\Validation\ServerRules;
class UpdateServerDetailsRequest extends ServerWriteRequest
{
@@ -25,30 +25,7 @@ class UpdateServerDetailsRequest extends ServerWriteRequest
*/
public function rules(): array
{
$rules = ServerRules::rules($this->parameter('server', Server::class));
return [
'external_id' => $rules['external_id'],
'name' => $rules['name'],
'owner_id' => $rules['owner_id'],
'description' => array_merge(['nullable'], $rules['description']),
];
}
/**
* Normalize the validated data for the service.
*
* @return ServerDetailsModificationData
*/
public function payload(): array
{
return [
'external_id' => $this->filled('external_id') ? $this->string('external_id')->toString() : null,
'name' => $this->string('name')->toString(),
'owner_id' => $this->integer('owner_id'),
'description' => $this->filled('description') ? $this->string('description')->toString() : null,
'extensions' => $this->extensionValues(),
];
return UpdateServerDetails::rules($this->parameter('server', Server::class));
}
/** Rename fields to be more clear in error messages. */
@@ -6,7 +6,6 @@ namespace Pterodactyl\Http\Requests\Api\Admin\Servers;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Http\Requests\Concerns\ParsesServerStartupData;
use Pterodactyl\Models\Server;
use Pterodactyl\Validation\ServerRules;
class UpdateServerStartupRequest extends ServerWriteRequest
@@ -25,7 +24,7 @@ class UpdateServerStartupRequest extends ServerWriteRequest
*/
public function rules(): array
{
$data = ServerRules::rules($this->parameter('server', Server::class));
$data = ServerRules::rules();
return [
'startup' => $data['startup'],
@@ -4,46 +4,46 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Application\Servers;
use Pterodactyl\Actions\Servers\UpdateServerDetails;
use Pterodactyl\Http\Requests\Concerns\ValidatesExtensionFields;
use Pterodactyl\Models\Server;
use Pterodactyl\Validation\ServerRules;
class UpdateServerDetailsRequest extends ServerWriteRequest
{
use ValidatesExtensionFields;
use ValidatesExtensionFields {
actionInput as private inputWithExtensions;
}
/**
* Rules to apply to a server details update request.
* Rules to apply to a server details update request. The Application API keeps its own
* field names; actionInput() hands the values to the action under its names.
*
* @return ValidationRules
*/
public function rules(): array
{
$rules = ServerRules::rules($this->parameter('server', Server::class));
$rules = UpdateServerDetails::rules($this->parameter('server', Server::class));
return [
'external_id' => $rules['external_id'],
'name' => $rules['name'],
'user' => $rules['owner_id'],
'description' => array_merge(['nullable'], $rules['description']),
'description' => $rules['description'],
];
}
/**
* Convert the posted data into the correct format that is expected
* by the application.
* The validated input under the action's field names: user is its owner_id.
*
* @return ServerDetailsModificationData
* @return ActionInput
*/
public function payload(): array
public function actionInput(): array
{
return [
'external_id' => $this->filled('external_id') ? $this->string('external_id')->toString() : null,
'name' => $this->string('name')->toString(),
'owner_id' => $this->integer('user'),
'description' => $this->filled('description') ? $this->string('description')->toString() : null,
'extensions' => $this->extensionValues(),
];
$input = $this->inputWithExtensions();
$input['owner_id'] = $input['user'] ?? null;
unset($input['user']);
return $input;
}
/**
@@ -6,7 +6,6 @@ namespace Pterodactyl\Http\Requests\Api\Application\Servers;
use Pterodactyl\Http\Requests\Api\Application\ApplicationApiRequest;
use Pterodactyl\Http\Requests\Concerns\ParsesServerStartupData;
use Pterodactyl\Models\Server;
use Pterodactyl\Services\Acl\Api\AdminAcl;
use Pterodactyl\Validation\ServerRules;
@@ -25,7 +24,7 @@ class UpdateServerStartupRequest extends ApplicationApiRequest
*/
public function rules(): array
{
$data = ServerRules::rules($this->parameter('server', Server::class));
$data = ServerRules::rules();
return [
'startup' => $data['startup'],
@@ -4,11 +4,10 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Client\Servers\Settings;
use Pterodactyl\Actions\Servers\UpdateServerDetails;
use Pterodactyl\Contracts\Http\ClientPermissionsRequest;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
use Pterodactyl\Validation\ServerRules;
use UnexpectedValueException;
class RenameServerRequest extends ClientApiRequest implements ClientPermissionsRequest
{
@@ -29,17 +28,11 @@ class RenameServerRequest extends ClientApiRequest implements ClientPermissionsR
*/
public function rules(): array
{
$rules = UpdateServerDetails::rules();
return [
'name' => ServerRules::rules()['name'],
'description' => ['string', 'nullable'],
'name' => $rules['name'],
'description' => $rules['description'],
];
}
public function description(): ?string
{
$description = $this->input('description');
throw_if($description !== null && ! is_string($description), UnexpectedValueException::class, 'The validated server description must be a string or null.');
return $description;
}
}
+4 -11
View File
@@ -4,25 +4,18 @@ declare(strict_types=1);
namespace Pterodactyl\Validation;
use Illuminate\Validation\Rule;
use Pterodactyl\Models\Server;
final class ServerRules
{
/**
* Validation rules for the requests that update a server's details and startup.
* Creating a server uses CreateServer::rules(), and its build UpdateServerBuild::rules().
* Validation rules for the requests that update a server's startup. Creating a server
* uses CreateServer::rules(), its build UpdateServerBuild::rules() and its details
* UpdateServerDetails::rules().
*
* @param Server|null $ignore the server being updated
* @return NormalizedValidationRules
*/
public static function rules(?Server $ignore = null): array
public static function rules(): array
{
return [
'external_id' => ['sometimes', 'nullable', 'string', 'between:1,191', Rule::unique('servers', 'external_id')->ignore($ignore)],
'owner_id' => ['required', 'integer', 'exists:users,id'],
'name' => ['required', 'string', 'min:1', 'max:191'],
'description' => ['string'],
'egg_id' => ['required', 'exists:eggs,id'],
'startup' => ['required', 'string'],
'image' => ['required', 'string', 'max:191', 'regex:/^~?[\w\.\/\-:@ ]*$/'],
-1
View File
@@ -87,7 +87,6 @@ parameters:
ServerTransferData: 'array{node_id: int, allocation_id: int, allocation_additional: list<int>}'
BackupCompletionData: 'array{successful: bool, checksum: string|null, checksum_type: string|null, size: int, parts: list<MultipartUploadPart>|null}'
BackupUploadParts: 'array{parts: list<string>, part_size: int}'
ServerDetailsModificationData: 'array{external_id: string|null, name: string, owner_id: int, description: string|null, extensions?: \Pterodactyl\Services\Extensions\ValidatedExtensionValues}'
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}"
MailSettingsData: "array{'mail:mailers:smtp:host': string, 'mail:mailers:smtp:port': int, 'mail:mailers:smtp:encryption': string|null, 'mail:mailers:smtp:username': string|null, 'mail:from:address': string, 'mail:from:name': string|null, 'mail:mailers:smtp:password'?: string}"
@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Integration\Actions\Servers\UpdateServerDetailsTest;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Bus;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use Pterodactyl\Contracts\Servers\UpdatesServerDetails;
use Pterodactyl\Jobs\RevokeSftpAccessJob;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\User;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
uses(IntegrationTestCase::class, DatabaseTransactions::class);
/** @return array<string, mixed> */
function details(Server $server, array $overrides = []): array
{
return [...[
'external_id' => 'ext-details',
'name' => 'Updated Server',
'owner_id' => $server->owner_id,
'description' => 'An updated description.',
], ...$overrides];
}
test('details updated without the http api meet the same rules', function (array $input, string $field): void {
$server = $this->createServerModel()->refresh();
$before = $server->getAttributes();
try {
$this->app->make(UpdatesServerDetails::class)->update($server, details($server, $input));
$this->fail('The details were updated.');
} catch (ValidationException $validationException) {
expect(array_keys($validationException->errors()))->toBe([$field]);
}
expect($server->fresh()->getAttributes())->toBe($before);
})->with([
'a missing name' => [['name' => null], 'name'],
'a name that is too long' => [['name' => str_repeat('a', 192)], 'name'],
'a missing owner' => [['owner_id' => null], 'owner_id'],
'an owner id that is not an integer' => [['owner_id' => '10.5'], 'owner_id'],
'an owner that does not exist' => [['owner_id' => 0], 'owner_id'],
'an external id that is too long' => [['external_id' => str_repeat('a', 192)], 'external_id'],
'an external id that is not a string' => [['external_id' => ['ext']], 'external_id'],
'a description that is not a string' => [['description' => ['text']], 'description'],
]);
test('an external id another server holds is refused, but the server keeps its own', function (): void {
$this->createServerModel(['external_id' => 'ext-taken']);
$server = $this->createServerModel(['external_id' => 'ext-own']);
try {
$this->app->make(UpdatesServerDetails::class)->update($server, details($server, ['external_id' => 'ext-taken']));
$this->fail('The details were updated.');
} catch (ValidationException $validationException) {
expect(array_keys($validationException->errors()))->toBe(['external_id']);
}
expect($this->app->make(UpdatesServerDetails::class)->update($server, details($server, ['external_id' => 'ext-own']))->external_id)->toBe('ext-own');
});
test('every detail is replaced, so an external id and description left out are cleared', function (): void {
$server = $this->createServerModel(['external_id' => 'ext-old', 'description' => 'Old description.']);
$updated = $this->app->make(UpdatesServerDetails::class)->update($server, ['name' => 'Renamed', 'owner_id' => $server->owner_id]);
expect($updated->name)->toBe('Renamed')
->and($updated->owner_id)->toBe($server->owner_id)
->and($updated->external_id)->toBeNull()
->and($updated->description)->toBe('');
$updated = $this->app->make(UpdatesServerDetails::class)->update($server, details($server, ['external_id' => '', 'description' => null]));
expect($updated->external_id)->toBeNull()
->and($updated->description)->toBe('');
});
test('values are coerced the way laravel validates them, and a new owner loses sftp access', function (): void {
Bus::fake();
$server = $this->createServerModel();
$previous = $server->user;
$owner = User::factory()->create();
$updated = $this->app->make(UpdatesServerDetails::class)->update($server, details($server, ['owner_id' => (string) $owner->id]));
expect($updated->owner_id)->toBe($owner->id)
->and($updated->external_id)->toBe('ext-details')
->and($updated->description)->toBe('An updated description.');
Bus::assertDispatched(RevokeSftpAccessJob::class, fn (RevokeSftpAccessJob $job): bool => $job->user === $previous->uuid);
});
test('an unchanged owner keeps sftp access', function (): void {
Bus::fake();
$server = $this->createServerModel();
$this->app->make(UpdatesServerDetails::class)->update($server, details($server, ['owner_id' => (string) $server->owner_id]));
Bus::assertNotDispatched(RevokeSftpAccessJob::class);
});
test('extension values must come from a request that validated them', function (): void {
$server = $this->createServerModel()->refresh();
$before = $server->getAttributes();
expect(fn () => $this->app->make(UpdatesServerDetails::class)->update($server, details($server, ['extensions' => ['billing' => ['plan' => 'pro']]])))
->toThrow(InvalidArgumentException::class, 'must come from a request that validated them');
expect($server->fresh()->getAttributes())->toBe($before);
});
@@ -104,6 +104,32 @@ test('update server details', function (): void {
$this->assertDatabaseHas('servers', ['id' => $server->id, 'name' => 'UpdatedServer', 'owner_id' => $owner->id]);
Bus::assertDispatched(RevokeSftpAccessJob::class);
});
test('update server details replaces every detail', function (): void {
Bus::fake();
$server = $this->createServerModel(['external_id' => 'ext-old', 'description' => 'Old description.']);
$other = $this->createServerModel(['external_id' => 'ext-taken']);
$this->putJson(route('api.admin.servers.details', ['server' => $server->id]), ['name' => 'Renamed', 'owner_id' => (string) $server->owner_id])
->assertOk()
->assertJsonPath('attributes.external_id', null);
$server->refresh();
expect($server->name)->toBe('Renamed')
->and($server->external_id)->toBeNull()
->and($server->description)->toBe('');
Bus::assertNotDispatched(RevokeSftpAccessJob::class);
$this->putJson(route('api.admin.servers.details', ['server' => $server->id]), ['name' => 'Renamed', 'owner_id' => $server->owner_id, 'external_id' => $other->external_id])
->assertUnprocessable()
->assertJsonCount(1, 'errors')
->assertJsonPath('errors.0.meta.source_field', 'external_id')
->assertJsonPath('errors.0.meta.rule', 'unique');
$this->putJson(route('api.admin.servers.details', ['server' => $server->id]), ['name' => '', 'owner_id' => 0])
->assertUnprocessable()
->assertJsonCount(2, 'errors')
->assertJsonPath('errors.0.meta.source_field', 'name')
->assertJsonPath('errors.1.meta.source_field', 'owner_id');
});
test('update server build', function (): void {
$server = $this->createServerModel();
new FakeDaemonServer;
@@ -104,6 +104,32 @@ test('server details can be updated', function (): void {
expect($server->owner_id)->toBe($owner->id);
$revocation->assertDeauthorized($previousOwner->uuid, [$server->uuid]);
});
test('server details update replaces every detail and keeps its own rules', function (): void {
$server = $this->createServerModel(['external_id' => 'ext-old', 'description' => 'Old description.']);
$other = $this->createServerModel(['external_id' => 'ext-taken']);
$this->patchJson("/api/application/servers/{$server->id}/details", ['name' => 'Renamed', 'user' => (string) $server->owner_id, 'external_id' => 'ext-old'])
->assertOk()
->assertJsonPath('attributes.external_id', 'ext-old')
->assertJsonPath('attributes.description', '');
$this->patchJson("/api/application/servers/{$server->id}/details", ['name' => 'Renamed', 'user' => $server->owner_id])
->assertOk()
->assertJsonPath('attributes.external_id', null);
$this->patchJson("/api/application/servers/{$server->id}/details", ['name' => 'Renamed', 'user' => $server->owner_id, 'external_id' => $other->external_id])
->assertUnprocessable()
->assertJsonCount(1, 'errors')
->assertJsonPath('errors.0.meta.source_field', 'external_id')
->assertJsonPath('errors.0.meta.rule', 'unique');
$this->patchJson("/api/application/servers/{$server->id}/details", ['name' => str_repeat('a', 192), 'user' => 0, 'description' => ['text']])
->assertUnprocessable()
->assertJsonCount(3, 'errors')
->assertJsonPath('errors.0.meta.source_field', 'name')
->assertJsonPath('errors.1.meta.source_field', 'user')
->assertJsonPath('errors.1.meta.rule', 'exists')
->assertJsonPath('errors.2.meta.source_field', 'description');
});
test('server build can be updated', function (): void {
mockDaemon();
$server = $this->createServerModel();
@@ -32,6 +32,29 @@ test('server name can be changed', function (array $permissions): void {
expect($server->name)->toBe('Test Server Name');
expect($server->description)->toBe('This is a test server.');
})->with('renamePermissionsDataProvider');
test('renaming a server keeps its owner, external id and a description it is not sent', function (): void {
[$user, $server] = $this->generateTestAccount();
$server->forceFill(['external_id' => 'ext-rename', 'description' => 'Kept description.'])->saveOrFail();
$owner = $server->owner_id;
$this->actingAs($user)->postJson("/api/client/servers/{$server->uuid}/settings/rename", ['name' => 'Renamed Only'])->assertNoContent();
$server->refresh();
expect($server->name)->toBe('Renamed Only')
->and($server->description)->toBe('Kept description.')
->and($server->external_id)->toBe('ext-rename')
->and($server->owner_id)->toBe($owner);
$this->actingAs($user)->postJson("/api/client/servers/{$server->uuid}/settings/rename", ['name' => 'Renamed Again', 'description' => null])->assertNoContent();
expect($server->refresh()->description)->toBe('')
->and($server->external_id)->toBe('ext-rename');
$this->actingAs($user)->postJson("/api/client/servers/{$server->uuid}/settings/rename", ['name' => 'Renamed Again', 'description' => ['text']])
->assertUnprocessable()
->assertJsonPath('errors.0.meta.source_field', 'description')
->assertJsonPath('errors.0.meta.rule', 'string');
});
test('subuser cannot change server name without permission', function (): void {
[$user, $server] = $this->generateTestAccount([Permissions::WebsocketConnect->value]);
$originalName = $server->name;