tag actions

This commit is contained in:
robert dennis
2026-10-12 05:18:56 -04:00
parent 01ff4a3d1e
commit d006674f6d
16 changed files with 354 additions and 102 deletions
+52 -4
View File
@@ -4,18 +4,66 @@ declare(strict_types=1);
namespace Pterodactyl\Actions\Tags;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Pterodactyl\Contracts\Tags\CreatesTags;
use Pterodactyl\Models\Tag;
use Pterodactyl\Rules\TagSlug;
final readonly class CreateTag implements CreatesTags
{
/**
* Create a new tag from validated attributes.
* A tag's fields. Pass the tag being edited so its own slug does not collide with the
* uniqueness check. A slug may not be purely numeric, so a leftover legacy nest id can be
* told apart from a real tag and a slug can never shadow a tag id (see TagSlug).
*
* @param TagData $data
* @return NormalizedValidationRules
*/
public function create(array $data): Tag
public static function rules(?Tag $tag = null): array
{
return Tag::query()->create($data);
return [
'name' => ['required', 'string', 'between:1,191'],
'slug' => ['required', 'string', 'between:1,191', Rule::unique('tags', 'slug')->ignore($tag), new TagSlug],
// Custom tags store an optional chip colour; built-in tags ignore it - their
// colour is owned by EggSpecificTags. Null clears it.
'color' => ['nullable', 'string', 'hex_color'],
'legacy_nest_id' => ['sometimes', 'nullable', 'integer'],
];
}
/**
* Validates tag input and returns the model attributes it describes. The colour and legacy
* nest id are left out when they are not given, so an edited tag keeps its stored values;
* a blank colour is cleared.
*
* @param ActionInput $input
* @return array{name: string, slug: string, color?: string|null, legacy_nest_id?: int|null}
*/
public static function attributes(array $input, ?Tag $tag = null): array
{
$input = Validator::make($input, self::rules($tag))->safe();
$attributes = [
'name' => $input->string('name')->toString(),
'slug' => $input->string('slug')->toString(),
];
if ($input->has('color')) {
$attributes['color'] = $input->filled('color') ? $input->string('color')->toString() : null;
}
if ($input->has('legacy_nest_id')) {
$attributes['legacy_nest_id'] = $input->filled('legacy_nest_id') ? $input->integer('legacy_nest_id') : null;
}
return $attributes;
}
/**
* @param ActionInput $input
*/
public function create(array $input): Tag
{
return Tag::query()->create(self::attributes($input));
}
}
+47 -6
View File
@@ -6,6 +6,8 @@ namespace Pterodactyl\Actions\Tags;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Tags\SyncsTags;
use Pterodactyl\Models\Egg;
@@ -15,24 +17,63 @@ use Pterodactyl\Services\Tags\TagResolutionService;
final readonly class SyncTags implements SyncsTags
{
/**
* Rules for a tag value given as text: an existing tag's id as a numeric string, or the
* name of a tag to find or create.
*
* @var list<string>
*/
public const array TEXT = ['string', 'max:191'];
public function __construct(private TagResolutionService $resolver) {}
/** @param list<string> $values */
/**
* The tags to sync, each an existing tag's id or a new tag's name. An id may also be an
* integer.
*
* @return NormalizedValidationRules
*/
public static function rules(): array
{
return [
'tags' => ['present', 'array'],
// A numeric value is read as an existing tag id rather than a new name.
// \Pterodactyl\Rules\TagSlug is what keeps those two spaces from
// overlapping, so no rule is needed here beyond the length bound.
'tags.*' => [Rule::anyOf([['integer:strict'], self::TEXT])],
];
}
/**
* Validates tag values under `tags` and returns them as strings for the resolver, an
* integer id becoming the numeric string the panel sends.
*
* @param list<ApiValue9> $values
* @return list<string>
*/
public static function values(array $values): array
{
$input = Validator::make(['tags' => $values], self::rules())->safe();
return array_map(fn (int|string $key): string => $input->string('tags.'.$key)->toString(), array_keys($input->array('tags')));
}
/** @param list<ApiValue9> $values */
public function syncEgg(Egg $egg, array $values): void
{
$this->sync($egg, $egg->tags(), $values);
$this->sync($egg, $egg->tags(), self::values($values));
}
/** @param list<string> $values */
/** @param list<ApiValue9> $values */
public function syncNodeGames(Node $node, array $values): void
{
$this->sync($node, $node->eggTags(), $values, $node->deploymentTags());
$this->sync($node, $node->eggTags(), self::values($values), $node->deploymentTags());
}
/** @param list<string> $values */
/** @param list<ApiValue9> $values */
public function syncNodeDeployments(Node $node, array $values): void
{
$this->sync($node, $node->deploymentTags(), $values, $node->eggTags());
$this->sync($node, $node->deploymentTags(), self::values($values), $node->eggTags());
}
/**
+6 -6
View File
@@ -12,19 +12,19 @@ use Pterodactyl\Models\Tag;
final readonly class UpdateTag implements UpdatesTags
{
/**
* Update an existing tag from validated attributes. A built-in game tag's slug is
* the key feature gating matches on and its presentation comes from the
* EggSpecificTags enum, so it must never be renamed or relabelled.
* Update an existing tag. A built-in game tag's slug is the key feature gating matches on
* and its presentation comes from the EggSpecificTags enum, so it must never be renamed or
* relabelled.
*
* @param TagData $data
* @param ActionInput $input
*
* @throws DisplayException
*/
public function update(Tag $tag, array $data): Tag
public function update(Tag $tag, array $input): Tag
{
throw_if(EggSpecificTags::isSpecial($tag->slug), DisplayException::class, 'Built-in game tags cannot be edited.');
$tag->update($data);
$tag->update(CreateTag::attributes($input, $tag));
return $tag;
}
+3 -3
View File
@@ -9,9 +9,9 @@ use Pterodactyl\Models\Tag;
interface CreatesTags
{
/**
* Create a new tag from validated attributes.
* Create a new tag. The input is validated here, so it can come straight from any caller.
*
* @param TagData $data
* @param ActionInput $input name and slug, and optionally color and legacy_nest_id
*/
public function create(array $data): Tag;
public function create(array $input): Tag;
}
+17 -3
View File
@@ -7,14 +7,28 @@ namespace Pterodactyl\Contracts\Tags;
use Pterodactyl\Models\Egg;
use Pterodactyl\Models\Node;
/**
* Replaces the full set of tags of one kind on an egg or a node. Each value is an existing
* tag's id, as an integer or a numeric string, or the name of a tag to find or create. The
* values are validated here, so they can come straight from any caller; errors are reported
* under `tags` and `tags.N`.
*/
interface SyncsTags
{
/** @param list<string> $values */
/** @param list<ApiValue9> $values */
public function syncEgg(Egg $egg, array $values): void;
/** @param list<string> $values */
/**
* Replace the games a node accepts. A tag the node holds as a reservation is refused.
*
* @param list<ApiValue9> $values
*/
public function syncNodeGames(Node $node, array $values): void;
/** @param list<string> $values */
/**
* Replace the reservations on a node. A tag the node accepts as a game is refused.
*
* @param list<ApiValue9> $values
*/
public function syncNodeDeployments(Node $node, array $values): void;
}
+6 -3
View File
@@ -10,11 +10,14 @@ use Pterodactyl\Models\Tag;
interface UpdatesTags
{
/**
* Update an existing tag from validated attributes. Built-in game tags cannot be edited.
* Update an existing tag. Built-in game tags cannot be edited. The input is validated here,
* so it can come straight from any caller. It takes the fields a tag is created with,
* required ones included; the colour and legacy nest id keep their stored values when they
* are left out.
*
* @param TagData $data
* @param ActionInput $input the fields a tag is created with
*
* @throws DisplayException
*/
public function update(Tag $tag, array $data): Tag;
public function update(Tag $tag, array $input): Tag;
}
@@ -97,7 +97,7 @@ class TagController extends AdminApiController
#[ResponseFromTransformer(TagTransformer::class, Tag::class, status: 201, description: 'Tag created.', resourceKey: 'tag', meta: ['resource' => 'https://panel.example.com/api/admin/tags/1'])]
public function store(StoreTagRequest $request, CreatesTags $tags): JsonResponse
{
$tag = $tags->create($request->payload());
$tag = $tags->create($request->actionInput());
Activity::event('admin:tag.create')
->subject($tag)
@@ -127,7 +127,7 @@ class TagController extends AdminApiController
#[ScribeResponse(self::BUILT_IN_ERROR, status: 400, description: 'The tag is a built-in game tag.')]
public function update(UpdateTagRequest $request, UpdatesTags $tags, Tag $tag): array
{
$tag = $tags->update($tag, $request->payload());
$tag = $tags->update($tag, $request->actionInput());
Activity::event('admin:tag.update')
->subject($tag)
@@ -4,12 +4,10 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Admin\Tags;
use Pterodactyl\Actions\Tags\CreateTag;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest;
use Pterodactyl\Rules\TagSlug;
use Pterodactyl\Support\JsonValueGuard;
use Pterodactyl\Support\ValidationRuleSubset;
use Pterodactyl\Validation\TagRules;
class StoreTagRequest extends AdminApiRequest
{
@@ -23,42 +21,17 @@ class StoreTagRequest extends AdminApiRequest
*/
public function rules(): array
{
return $this->withSlugRule(TagRules::rules());
return $this->writable(CreateTag::rules());
}
/**
* Model attributes for the tag. The color stays absent when the request
* omits it so an update leaves the stored value alone.
*
* @return TagData
*/
public function payload(): array
{
$payload = [
'name' => $this->string('name')->toString(),
'slug' => $this->string('slug')->toString(),
];
if ($this->exists('color')) {
$payload['color'] = JsonValueGuard::nullableString($this->input('color'));
}
return $payload;
}
/**
* Narrow the model rules to the writable fields and forbid numeric slugs, so a
* leftover legacy nest id can be told apart from a real tag and a slug can never
* shadow a tag id (see TagSlug).
* Narrow a tag's rules to the fields the API writes; it never sets the legacy nest id.
*
* @param NormalizedValidationRules $rules
* @return NormalizedValidationRules
*/
protected function withSlugRule(array $rules): array
protected function writable(array $rules): array
{
$rules = ValidationRuleSubset::select($rules, ['name', 'slug', 'color']);
$rules['slug'] = array_merge($rules['slug'], [new TagSlug]);
return $rules;
return ValidationRuleSubset::select($rules, ['name', 'slug', 'color']);
}
}
@@ -4,10 +4,10 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Admin\Tags;
use Pterodactyl\Actions\Tags\SyncTags;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest;
use Pterodactyl\Services\Tags\TagResolutionService;
use Pterodactyl\Support\JsonValueGuard;
/**
* Replace the full set of tags on an egg or a node.
@@ -24,16 +24,16 @@ class SyncTagsRequest extends AdminApiRequest
}
/**
* The action's rules, with every value held to its text rules: integer ids are numeric
* strings by now (see prepareForValidation()).
*
* @return ValidationRules
*/
public function rules(): array
{
return [
'tags' => ['present', 'array'],
// A numeric value is read as an existing tag id rather than a new name.
// \Pterodactyl\Rules\TagSlug is what keeps those two spaces from
// overlapping, so no rule is needed here beyond the length bound.
'tags.*' => ['string', 'max:191'],
'tags' => SyncTags::rules()['tags'],
'tags.*' => SyncTags::TEXT,
];
}
@@ -44,7 +44,9 @@ class SyncTagsRequest extends AdminApiRequest
*/
public function tagValues(): array
{
return JsonValueGuard::stringList(array_values(JsonValueGuard::jsonArray($this->validated('tags', []))));
$validated = $this->safe();
return array_map(fn (int|string $key): string => $validated->string('tags.'.$key)->toString(), array_keys($validated->array('tags')));
}
/** Tag ids sent as JSON integers are read the same as the numeric strings the panel sends. */
@@ -4,9 +4,9 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Admin\Tags;
use Pterodactyl\Actions\Tags\CreateTag;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Models\Tag;
use Pterodactyl\Validation\TagRules;
class UpdateTagRequest extends StoreTagRequest
{
@@ -20,6 +20,6 @@ class UpdateTagRequest extends StoreTagRequest
*/
public function rules(): array
{
return $this->withSlugRule(TagRules::rules($this->parameter('tag', Tag::class)));
return $this->writable(CreateTag::rules($this->parameter('tag', Tag::class)));
}
}
+3 -4
View File
@@ -15,10 +15,9 @@ class TagResolutionService
* any tag that does not exist yet. This is what lets the node and egg tag
* pickers create a tag inline by typing a new name.
*
* Callers validate the submitted values first (SyncTagsRequest bounds each entry
* to a string of at most 191 characters); combined with the numeric guard below
* that satisfies every rule in TagRules::rules(), so tags created here need no
* separate check.
* SyncTags validates the values first (it bounds each name to at most 191
* characters); combined with the numeric guard below that satisfies every rule
* in CreateTag::rules(), so tags created here need no separate check.
*
* @param string[] $values
* @return int[]
-29
View File
@@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Validation;
use Illuminate\Validation\Rule;
use Pterodactyl\Models\Tag;
final class TagRules
{
/**
* Canonical validation rules for client-submitted tag fields. Pass the tag being
* edited so its own slug does not collide with the uniqueness check.
*
* @return NormalizedValidationRules
*/
public static function rules(?Tag $ignore = null): array
{
return [
'name' => ['required', 'string', 'between:1,191'],
'slug' => ['required', 'string', 'between:1,191', Rule::unique('tags', 'slug')->ignore($ignore)],
// Custom tags store an optional chip colour; built-in tags ignore it - their
// colour is owned by EggSpecificTags. Null clears it.
'color' => ['nullable', 'string', 'hex_color'],
'legacy_nest_id' => ['sometimes', 'nullable', 'integer'],
];
}
}
-1
View File
@@ -89,7 +89,6 @@ parameters:
DatabaseHostUpdateData: 'array{name: string, host: string, port: int, username: string, password?: string|null, node_id: int|null, extensions?: \Pterodactyl\Services\Extensions\ValidatedExtensionValues}'
EggVariableData: 'array{name: string, description: string, env_variable: string, default_value: string, user_viewable: bool, user_editable: bool, rules: string}'
MultipartUploadPart: 'array{etag: string, part_number: int}'
TagData: 'array{name: string, slug: string, color?: string|null}'
ApiKeyUpdateData: 'array{memo: string|null}'
SftpAuthenticationData: 'array{type: string|null, username: string, password: string}'
EggCreationData: 'array{name: string, description: string|null, docker_images: array<string, string>, force_outgoing_ip: bool, features: list<string>, startup: string, file_denylist?: list<string>, config_from?: int|null, config_stop?: string|null, config_startup?: string|null, config_logs?: string|null, config_files?: string|null, extensions?: \Pterodactyl\Services\Extensions\ValidatedExtensionValues}'
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Integration\Actions\Tags\CreateTagTest;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Tags\CreatesTags;
use Pterodactyl\Models\Tag;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
uses(IntegrationTestCase::class, DatabaseTransactions::class);
/** @return array<string, int|string|null> */
function tag(array $overrides = []): array
{
return [...['name' => 'Direct', 'slug' => 'direct-tag'], ...$overrides];
}
test('tags created without the http api meet the same rules', function (array $input, string $field): void {
Tag::factory()->create(['slug' => 'taken']);
$count = Tag::query()->count();
try {
$this->app->make(CreatesTags::class)->create(tag($input));
$this->fail('The tag was created.');
} catch (ValidationException $validationException) {
expect(array_keys($validationException->errors()))->toBe([$field]);
}
expect(Tag::query()->count())->toBe($count);
})->with([
'a missing name' => [['name' => null], 'name'],
'a name that is too long' => [['name' => str_repeat('a', 192)], 'name'],
'a missing slug' => [['slug' => null], 'slug'],
'a taken slug' => [['slug' => 'taken'], 'slug'],
'a purely numeric slug' => [['slug' => '42'], 'slug'],
'a colour that is not hex' => [['color' => 'red'], 'color'],
'a legacy nest id that is not a number' => [['legacy_nest_id' => 'one'], 'legacy_nest_id'],
]);
test('values are coerced the way laravel validates them', function (int|string $legacyNestId): void {
$tag = $this->app->make(CreatesTags::class)->create(tag(['color' => '#a1b2c3', 'legacy_nest_id' => $legacyNestId]));
$tag->refresh();
expect($tag->name)->toBe('Direct')
->and($tag->slug)->toBe('direct-tag')
->and($tag->color)->toBe('#a1b2c3')
->and($tag->legacy_nest_id)->toBe(7);
})->with([[7], ['7']]);
test('a tag given no colour or a blank one has none', function (?string $color): void {
$tag = $this->app->make(CreatesTags::class)->create(tag($color === null ? [] : ['color' => $color]));
expect($tag->refresh()->color)->toBeNull()
->and($tag->legacy_nest_id)->toBeNull();
})->with([[null], ['']]);
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Integration\Actions\Tags\SyncTagsTest;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Tags\SyncsTags;
use Pterodactyl\Models\Egg;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Tag;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
uses(IntegrationTestCase::class, DatabaseTransactions::class);
test('tag values synced without the http api meet the same rules', function (array $values, string $field): void {
$egg = Egg::factory()->create();
$count = Tag::query()->count();
try {
$this->app->make(SyncsTags::class)->syncEgg($egg, $values);
$this->fail('The tags were synced.');
} catch (ValidationException $validationException) {
expect(array_keys($validationException->errors()))->toBe([$field]);
}
expect($egg->tags()->exists())->toBeFalse()
->and(Tag::query()->count())->toBe($count);
})->with([
'a name that is too long' => [[str_repeat('a', 192)], 'tags.0'],
'a boolean' => [['fresh-name', true], 'tags.1'],
'null' => [[null], 'tags.0'],
'a float' => [[1.5], 'tags.0'],
'a list' => [[['nested']], 'tags.0'],
]);
test('integer ids, numeric strings and names all resolve to tags', function (): void {
$first = Tag::factory()->create();
$second = Tag::factory()->create();
$egg = Egg::factory()->create();
// A numeric value that names no tag is a stale legacy nest id, and is dropped.
$this->app->make(SyncsTags::class)->syncEgg($egg, [$first->id, (string) $second->id, ' Brand New ', '999999']);
$created = Tag::query()->where('slug', 'Brand New')->sole();
expect($egg->tags()->pluck('tags.id')->sort()->values()->all())->toBe([$first->id, $second->id, $created->id])
->and(Tag::query()->where('slug', '999999')->exists())->toBeFalse();
});
test('an empty list clears the tags', function (): void {
$egg = Egg::factory()->create();
$egg->tags()->attach(Tag::factory()->create());
$this->app->make(SyncsTags::class)->syncEgg($egg, []);
expect($egg->tags()->exists())->toBeFalse();
});
test('a node synced directly still cannot hold a tag as both kinds', function (): void {
$tag = Tag::factory()->create(['name' => 'Both Kinds']);
$node = Node::factory()->withLocation()->create();
$sync = $this->app->make(SyncsTags::class);
$sync->syncNodeGames($node, [$tag->id]);
try {
$sync->syncNodeDeployments($node, [$tag->id]);
$this->fail('The tag was synced as both kinds.');
} catch (ValidationException $validationException) {
expect($validationException->errors())->toBe(['tags' => ['These tags are already on the node as the other kind: Both Kinds.']]);
}
expect($node->eggTags()->pluck('tags.id')->all())->toBe([$tag->id])
->and($node->deploymentTags()->exists())->toBeFalse();
});
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Integration\Actions\Tags\UpdateTagTest;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Tags\UpdatesTags;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Models\Tag;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
uses(IntegrationTestCase::class, DatabaseTransactions::class);
test('an update keeps the colour and legacy nest id it is not given', function (): void {
$tag = Tag::factory()->create(['color' => '#123456', 'legacy_nest_id' => 3]);
$this->app->make(UpdatesTags::class)->update($tag, ['name' => 'Renamed', 'slug' => 'renamed']);
$tag->refresh();
expect($tag->name)->toBe('Renamed')
->and($tag->slug)->toBe('renamed')
->and($tag->color)->toBe('#123456')
->and($tag->legacy_nest_id)->toBe(3);
});
test('a tag keeps its own slug, and a null colour clears it', function (): void {
$tag = Tag::factory()->create(['slug' => 'mine', 'color' => '#123456']);
$this->app->make(UpdatesTags::class)->update($tag, ['name' => 'Mine', 'slug' => 'mine', 'color' => null, 'legacy_nest_id' => '12']);
$tag->refresh();
expect($tag->slug)->toBe('mine')
->and($tag->color)->toBeNull()
->and($tag->legacy_nest_id)->toBe(12);
});
test('tags updated without the http api meet the same rules', function (array $input, string $field): void {
Tag::factory()->create(['slug' => 'taken']);
$tag = Tag::factory()->create()->refresh();
$before = $tag->getAttributes();
try {
$this->app->make(UpdatesTags::class)->update($tag, [...['name' => $tag->name, 'slug' => $tag->slug], ...$input]);
$this->fail('The tag was updated.');
} catch (ValidationException $validationException) {
expect(array_keys($validationException->errors()))->toBe([$field]);
}
expect($tag->fresh()->getAttributes())->toBe($before);
})->with([
'a blank name' => [['name' => ''], 'name'],
'a taken slug' => [['slug' => 'taken'], 'slug'],
'a purely numeric slug' => [['slug' => '7'], 'slug'],
'a colour that is not hex' => [['color' => '#12345g'], 'color'],
]);
test('built-in game tags cannot be edited, whatever the input', function (array $input): void {
$tag = Tag::factory()->predefined()->create();
expect(fn () => $this->app->make(UpdatesTags::class)->update($tag, $input))
->toThrow(DisplayException::class, 'Built-in game tags cannot be edited.');
expect($tag->fresh()->slug)->toBe('minecraft');
})->with([
'valid input' => [['name' => 'Changed', 'slug' => 'changed']],
'invalid input' => [[]],
]);