diff --git a/app/Actions/Eggs/CreateEgg.php b/app/Actions/Eggs/CreateEgg.php index 6935a66bd..305b76027 100644 --- a/app/Actions/Eggs/CreateEgg.php +++ b/app/Actions/Eggs/CreateEgg.php @@ -6,29 +6,125 @@ namespace Pterodactyl\Actions\Eggs; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; use Pterodactyl\Contracts\Eggs\CreatesEggs; use Pterodactyl\Models\Egg; +use Pterodactyl\Rules\DockerImageList; use Pterodactyl\Services\Extensions\ExtensionFields; use Pterodactyl\Services\Extensions\ValidatedExtensionValues; use Pterodactyl\Support\JsonValueGuard; final readonly class CreateEgg implements CreatesEggs { + /** + * Rules every Docker image an egg offers must pass, wherever it is set: an image, + * optionally prefixed with its display name, such as `Java 21|ghcr.io/...`. + * + * @var list + */ + public const array DOCKER_IMAGE = ['required', 'string', 'max:191', 'regex:/^[\w#\.\/\- ]*\|?~?[\w\.\/\-:@ ]*$/']; + public function __construct(private ExtensionFields $extensions) {} + /** + * An egg's fields, for creating one and for updating one. The Docker images are one per + * line, each held to DOCKER_IMAGE (see DockerImageList). An egg that copies its config from + * another needs none of its own; every config block given must be JSON, apart from the + * stop command. + * + * @return NormalizedValidationRules + */ + public static function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:191'], + 'description' => ['nullable', 'string'], + 'docker_images' => ['required', 'string', new DockerImageList], + 'force_outgoing_ip' => ['sometimes', 'boolean'], + 'file_denylist' => ['array'], + 'file_denylist.*' => ['string'], + 'features' => ['sometimes', 'array'], + 'features.*' => ['string'], + 'startup' => ['required', 'string'], + 'config_from' => ['sometimes', 'bail', 'nullable', 'integer', Rule::exists(Egg::class, 'id')], + 'config_stop' => ['required_without:config_from', 'nullable', 'string', 'max:191'], + 'config_startup' => ['required_without:config_from', 'nullable', 'json'], + 'config_logs' => ['required_without:config_from', 'nullable', 'json'], + 'config_files' => ['required_without:config_from', 'nullable', 'json'], + ]; + } + + /** + * Validates egg input and returns the model attributes it describes. The Docker images + * become a map of display name to image, a line without a name using the image as its + * name. A config_from of 0 is the legacy "no parent egg" sentinel, read as null. + * + * An egg given no description, outgoing IP flag or features gets none, so an update clears + * them. The file denylist, the parent egg and the config blocks are left out when they are + * not given, so a new egg takes the column defaults and an updated one keeps its stored + * values; a blank one is cleared. + * + * @param ActionInput $input + * @return array{name: string, description: string|null, docker_images: array, force_outgoing_ip: bool, features: list, startup: string, file_denylist?: list, config_from?: int|null, config_stop?: string|null, config_startup?: string|null, config_logs?: string|null, config_files?: string|null} + */ + public static function attributes(array $input): array + { + if (array_key_exists('config_from', $input) && filter_var($input['config_from'], FILTER_VALIDATE_INT) === 0) { + $input['config_from'] = null; + } + + $input = Validator::make($input, self::rules())->safe(); + + $attributes = [ + 'name' => $input->string('name')->toString(), + 'description' => $input->filled('description') ? $input->string('description')->toString() : null, + 'docker_images' => self::dockerImages($input->string('docker_images')->toString()), + 'force_outgoing_ip' => $input->boolean('force_outgoing_ip'), + 'features' => array_map(fn (int|string $key): string => $input->string('features.'.$key)->toString(), array_keys($input->array('features'))), + 'startup' => $input->string('startup')->toString(), + ]; + + if ($input->has('file_denylist')) { + $attributes['file_denylist'] = array_map(fn (int|string $key): string => $input->string('file_denylist.'.$key)->toString(), array_keys($input->array('file_denylist'))); + } + + if ($input->has('config_from')) { + $attributes['config_from'] = $input->filled('config_from') ? $input->integer('config_from') : null; + } + + if ($input->has('config_stop')) { + $attributes['config_stop'] = $input->filled('config_stop') ? $input->string('config_stop')->toString() : null; + } + + if ($input->has('config_startup')) { + $attributes['config_startup'] = $input->filled('config_startup') ? $input->string('config_startup')->toString() : null; + } + + if ($input->has('config_logs')) { + $attributes['config_logs'] = $input->filled('config_logs') ? $input->string('config_logs')->toString() : null; + } + + if ($input->has('config_files')) { + $attributes['config_files'] = $input->filled('config_files') ? $input->string('config_files')->toString() : null; + } + + return $attributes; + } + /** * Create an egg, stamping the configured service author. * - * @param EggCreationData $data + * @param ActionInput $input */ - public function create(array $data): Egg + public function create(array $input): Egg { - $extensions = ValidatedExtensionValues::of($data['extensions'] ?? null); - unset($data['extensions']); + $attributes = self::attributes($input); + $extensions = ValidatedExtensionValues::of($input['extensions'] ?? null); - return DB::transaction(function () use ($data, $extensions): Egg { + return DB::transaction(function () use ($attributes, $extensions): Egg { $egg = Egg::query()->forceCreate([ - ...$data, + ...$attributes, 'author' => JsonValueGuard::string(Config::get('pterodactyl.service.author')), ]); $this->extensions->save($egg, $extensions); @@ -36,4 +132,20 @@ final readonly class CreateEgg implements CreatesEggs return $egg->refresh(); }); } + + /** + * The images of a newline-separated list, keyed by display name. + * + * @return array + */ + private static function dockerImages(string $images): array + { + $normalized = []; + foreach (DockerImageList::lines($images) as $value) { + $parts = explode('|', $value, 2); + $normalized[$parts[0]] = empty($parts[1]) ? $parts[0] : $parts[1]; + } + + return $normalized; + } } diff --git a/app/Actions/Eggs/Scripts/UpdateInstallScript.php b/app/Actions/Eggs/Scripts/UpdateInstallScript.php index 7b348e50b..572d11dcd 100644 --- a/app/Actions/Eggs/Scripts/UpdateInstallScript.php +++ b/app/Actions/Eggs/Scripts/UpdateInstallScript.php @@ -4,35 +4,83 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Eggs\Scripts; -use Illuminate\Support\Arr; +use Illuminate\Support\Facades\Validator; use Pterodactyl\Contracts\Eggs\UpdatesEggInstallScripts; use Pterodactyl\Exceptions\Service\Egg\InvalidCopyFromException; use Pterodactyl\Models\Egg; -use Pterodactyl\Support\JsonValueGuard; final class UpdateInstallScript implements UpdatesEggInstallScripts { + /** + * An egg's install script fields, each of them optional: the script, whether it runs + * privileged, the container entrypoint and image it runs in, and the egg to copy the + * script from instead. + * + * @return NormalizedValidationRules + */ + public static function rules(): array + { + return [ + 'script_install' => ['sometimes', 'nullable', 'string'], + 'script_is_privileged' => ['sometimes', 'required', 'boolean'], + 'script_entry' => ['sometimes', 'required', 'string'], + 'script_container' => ['sometimes', 'required', 'string'], + 'copy_script_from' => ['sometimes', 'nullable', 'integer'], + ]; + } + + /** + * Validates install script input and returns the attributes it changes: only the fields + * given, so the rest keep their stored values. A blank script or copy source is cleared. + * + * @param ActionInput $input + * @return array{script_install?: string|null, script_is_privileged?: bool, script_entry?: string, script_container?: string, copy_script_from?: int|null} + */ + public static function attributes(array $input): array + { + $input = Validator::make($input, self::rules())->safe(); + + $attributes = []; + if ($input->has('script_install')) { + $attributes['script_install'] = $input->filled('script_install') ? $input->string('script_install')->toString() : null; + } + + if ($input->has('script_is_privileged')) { + $attributes['script_is_privileged'] = $input->boolean('script_is_privileged'); + } + + if ($input->has('script_entry')) { + $attributes['script_entry'] = $input->string('script_entry')->toString(); + } + + if ($input->has('script_container')) { + $attributes['script_container'] = $input->string('script_container')->toString(); + } + + if ($input->has('copy_script_from')) { + $attributes['copy_script_from'] = $input->filled('copy_script_from') ? $input->integer('copy_script_from') : null; + } + + return $attributes; + } + /** * Modify the install script for a given Egg. * - * @param ModelAttributes $data validated install script attributes + * @param ActionInput $input * * @throws InvalidCopyFromException */ - public function update(Egg $egg, array $data): Egg + public function update(Egg $egg, array $input): Egg { - $copyFrom = JsonValueGuard::nullableInteger(Arr::get($data, 'copy_script_from')); + $attributes = self::attributes($input); + + $copyFrom = $attributes['copy_script_from'] ?? null; if ($copyFrom !== null && ! Egg::query()->scriptSources()->whereKey($copyFrom)->exists()) { throw new InvalidCopyFromException(trans('exceptions.egg.invalid_copy_id')); } - $egg->update([ - 'script_install' => JsonValueGuard::nullableString(Arr::get($data, 'script_install')), - 'script_is_privileged' => JsonValueGuard::boolean(Arr::get($data, 'script_is_privileged', true)), - 'script_entry' => JsonValueGuard::string(Arr::get($data, 'script_entry')), - 'script_container' => JsonValueGuard::string(Arr::get($data, 'script_container')), - 'copy_script_from' => $copyFrom, - ]); + $egg->update($attributes); return $egg; } diff --git a/app/Actions/Eggs/UpdateEgg.php b/app/Actions/Eggs/UpdateEgg.php index b05d2e065..52c7daf94 100644 --- a/app/Actions/Eggs/UpdateEgg.php +++ b/app/Actions/Eggs/UpdateEgg.php @@ -15,21 +15,21 @@ final readonly class UpdateEgg implements UpdatesEggs public function __construct(private ExtensionFields $extensions) {} /** - * Update an egg from request-validated attributes. + * Update an egg with the fields it is created with. * - * @param EggCreationData $data + * @param ActionInput $input */ - public function update(Egg $egg, array $data): Egg + public function update(Egg $egg, array $input): Egg { - $extensions = ValidatedExtensionValues::of($data['extensions'] ?? null); - unset($data['extensions']); + $attributes = CreateEgg::attributes($input); + $extensions = ValidatedExtensionValues::of($input['extensions'] ?? null); // TODO(dane): Once the admin UI is done being reworked and this is exposed // in said UI, remove this so that you can actually update the denylist. - unset($data['file_denylist']); + unset($attributes['file_denylist']); - DB::transaction(function () use ($egg, $data, $extensions): void { - $egg->update($data); + DB::transaction(function () use ($egg, $attributes, $extensions): void { + $egg->update($attributes); $this->extensions->save($egg, $extensions); }); diff --git a/app/Actions/Eggs/Variables/CreateEggVariable.php b/app/Actions/Eggs/Variables/CreateEggVariable.php index 9ac496dda..6df53537f 100644 --- a/app/Actions/Eggs/Variables/CreateEggVariable.php +++ b/app/Actions/Eggs/Variables/CreateEggVariable.php @@ -4,20 +4,75 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Eggs\Variables; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; use Pterodactyl\Contracts\Eggs\CreatesEggVariables; use Pterodactyl\Models\Egg; use Pterodactyl\Models\EggVariable; +use Pterodactyl\Rules\UnreservedEnvironmentVariable; +use Pterodactyl\Rules\ValidRuleSet; final class CreateEggVariable implements CreatesEggVariables { /** - * Create a new variable for a given Egg from request-validated attributes. + * An egg variable's fields, whether it is written through the admin API or arrives in an + * imported egg, and the options that set whether users can see and edit it. Pass the egg + * to hold the environment variable name unique among its variables, and the variable + * being updated so its own name is not taken for a duplicate. * - * @param EggVariableData $data + * @return NormalizedValidationRules */ - public function create(Egg $egg, array $data): EggVariable + public static function rules(?Egg $egg = null, ?EggVariable $ignore = null): array { - $variable = $egg->variables()->create($data); + $environmentVariable = ['required', 'regex:/^[\w]{1,191}$/', new UnreservedEnvironmentVariable]; + if ($egg instanceof Egg) { + $environmentVariable[] = Rule::unique(EggVariable::class, 'env_variable')->where('egg_id', $egg->id)->ignore($ignore); + } + + return [ + 'name' => ['required', 'string', 'min:1', 'max:191'], + 'description' => ['sometimes', 'nullable', 'string'], + 'env_variable' => $environmentVariable, + 'rules' => ['bail', 'required', 'string', new ValidRuleSet], + 'default_value' => ['present', 'string'], + 'options' => ['sometimes', 'required', 'array', 'list'], + 'options.*' => ['string'], + ]; + } + + /** + * Validates variable input for the egg and returns the model attributes it describes. + * The options become the user_viewable and user_editable flags, each set only when it is + * listed; any other option is ignored. A variable given no description gets a blank one. + * + * @param ActionInput $input + * @return array{name: string, description: string, env_variable: string, default_value: string, user_viewable: bool, user_editable: bool, rules: string} + */ + public static function attributes(array $input, Egg $egg, ?EggVariable $ignore = null): array + { + $input = Validator::make($input, self::rules($egg, $ignore))->safe(); + + $options = array_map(fn (int|string $key): string => $input->string('options.'.$key)->toString(), array_keys($input->array('options'))); + + return [ + 'name' => $input->string('name')->toString(), + 'description' => $input->string('description')->toString(), + 'env_variable' => $input->string('env_variable')->toString(), + 'default_value' => $input->string('default_value')->toString(), + 'user_viewable' => in_array('user_viewable', $options, true), + 'user_editable' => in_array('user_editable', $options, true), + 'rules' => $input->string('rules')->toString(), + ]; + } + + /** + * Create a new variable for a given Egg. + * + * @param ActionInput $input + */ + public function create(Egg $egg, array $input): EggVariable + { + $variable = $egg->variables()->create(self::attributes($input, $egg)); return $variable->refresh(); } diff --git a/app/Actions/Eggs/Variables/ReorderEggVariables.php b/app/Actions/Eggs/Variables/ReorderEggVariables.php index cc8449f1c..d054f0c38 100644 --- a/app/Actions/Eggs/Variables/ReorderEggVariables.php +++ b/app/Actions/Eggs/Variables/ReorderEggVariables.php @@ -5,14 +5,45 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Eggs\Variables; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; use Pterodactyl\Contracts\Eggs\ReordersEggVariables; use Pterodactyl\Models\Egg; final readonly class ReorderEggVariables implements ReordersEggVariables { - /** @param list $order */ + /** + * The variable ids of an egg in their new order, each once. An id may be an integer or + * a numeric string. + * + * @return NormalizedValidationRules + */ + public static function rules(): array + { + return [ + 'order' => ['required', 'array', 'list'], + 'order.*' => ['required', Rule::anyOf([['integer:strict'], ['string']]), 'integer', 'distinct'], + ]; + } + + /** + * Validates variable ids under `order` and returns them as integers. + * + * @param list $order + * @return list + */ + public static function order(array $order): array + { + $input = Validator::make(['order' => $order], self::rules())->safe(); + + return array_map(fn (int|string $key): int => $input->integer('order.'.$key), array_keys($input->array('order'))); + } + + /** @param list $order */ public function reorder(Egg $egg, array $order): void { + $order = self::order($order); + DB::transaction(function () use ($egg, $order): void { $egg = Egg::query()->lockForUpdate()->findOrFail($egg->id); foreach ($order as $index => $variableId) { diff --git a/app/Actions/Eggs/Variables/UpdateEggVariable.php b/app/Actions/Eggs/Variables/UpdateEggVariable.php index 2ed97a93b..41dc77f9e 100644 --- a/app/Actions/Eggs/Variables/UpdateEggVariable.php +++ b/app/Actions/Eggs/Variables/UpdateEggVariable.php @@ -5,18 +5,21 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Eggs\Variables; use Pterodactyl\Contracts\Eggs\UpdatesEggVariables; +use Pterodactyl\Models\Egg; use Pterodactyl\Models\EggVariable; final class UpdateEggVariable implements UpdatesEggVariables { /** - * Update an egg variable from request-validated attributes. + * Update an egg variable with the fields it is created with. * - * @param EggVariableData $data + * @param ActionInput $input */ - public function update(EggVariable $variable, array $data): EggVariable + public function update(EggVariable $variable, array $input): EggVariable { - $variable->update($data); + $egg = Egg::query()->findOrFail($variable->egg_id); + + $variable->update(CreateEggVariable::attributes($input, $egg, $variable)); return $variable; } diff --git a/app/Contracts/Eggs/CreatesEggVariables.php b/app/Contracts/Eggs/CreatesEggVariables.php index 709f8e961..f5515d519 100644 --- a/app/Contracts/Eggs/CreatesEggVariables.php +++ b/app/Contracts/Eggs/CreatesEggVariables.php @@ -10,9 +10,12 @@ use Pterodactyl\Models\EggVariable; interface CreatesEggVariables { /** - * Create a new variable for a given Egg from request-validated attributes. + * Create a new variable for a given Egg. The input is validated here, so it can come + * straight from any caller: the environment variable name must be unique among the egg's + * variables and not one the panel reserves, and the rules must be a valid rule set. + * Listing user_viewable or user_editable in options lets users see or edit the variable. * - * @param EggVariableData $data + * @param ActionInput $input name, env_variable, rules and default_value, and optionally description and options */ - public function create(Egg $egg, array $data): EggVariable; + public function create(Egg $egg, array $input): EggVariable; } diff --git a/app/Contracts/Eggs/CreatesEggs.php b/app/Contracts/Eggs/CreatesEggs.php index 0c952c055..9ed93108d 100644 --- a/app/Contracts/Eggs/CreatesEggs.php +++ b/app/Contracts/Eggs/CreatesEggs.php @@ -9,9 +9,13 @@ use Pterodactyl\Models\Egg; interface CreatesEggs { /** - * Create an egg, stamping the configured service author. + * Create an egg, stamping the configured service author. The input is validated here, + * so it can come straight from any caller; extension field values go under `extensions` + * as ValidatedExtensionValues. The Docker images are a newline-separated string, each line + * an image optionally prefixed with its display name and a pipe. An egg given a + * config_from copies its config from that egg and needs no config blocks of its own. * - * @param EggCreationData $data + * @param ActionInput $input name, docker_images and startup, and optionally description, force_outgoing_ip, features, file_denylist, config_from, config_stop, config_startup, config_logs and config_files */ - public function create(array $data): Egg; + public function create(array $input): Egg; } diff --git a/app/Contracts/Eggs/ReordersEggVariables.php b/app/Contracts/Eggs/ReordersEggVariables.php index 387275241..dafb51841 100644 --- a/app/Contracts/Eggs/ReordersEggVariables.php +++ b/app/Contracts/Eggs/ReordersEggVariables.php @@ -8,6 +8,12 @@ use Pterodactyl\Models\Egg; interface ReordersEggVariables { - /** @param list $order */ + /** + * Give the egg's variables the sort order of their position in the list. The ids are + * validated here, so they can come straight from any caller: each is an integer or a + * numeric string, listed once. An id of a variable on another egg is skipped. + * + * @param list $order the variable ids in their new order + */ public function reorder(Egg $egg, array $order): void; } diff --git a/app/Contracts/Eggs/UpdatesEggInstallScripts.php b/app/Contracts/Eggs/UpdatesEggInstallScripts.php index 6b454f491..65c527c3c 100644 --- a/app/Contracts/Eggs/UpdatesEggInstallScripts.php +++ b/app/Contracts/Eggs/UpdatesEggInstallScripts.php @@ -10,11 +10,13 @@ use Pterodactyl\Models\Egg; interface UpdatesEggInstallScripts { /** - * Modify the install script for a given Egg. + * Modify the install script for a given Egg. The input is validated here, so it can come + * straight from any caller, and only the fields given are changed. An egg to copy the + * script from must have a script of its own. * - * @param ModelAttributes $data validated install script attributes + * @param ActionInput $input any of script_install, script_is_privileged, script_entry, script_container and copy_script_from * * @throws InvalidCopyFromException */ - public function update(Egg $egg, array $data): Egg; + public function update(Egg $egg, array $input): Egg; } diff --git a/app/Contracts/Eggs/UpdatesEggVariables.php b/app/Contracts/Eggs/UpdatesEggVariables.php index 1f400505f..66ac57ce2 100644 --- a/app/Contracts/Eggs/UpdatesEggVariables.php +++ b/app/Contracts/Eggs/UpdatesEggVariables.php @@ -9,9 +9,13 @@ use Pterodactyl\Models\EggVariable; interface UpdatesEggVariables { /** - * Update an egg variable from request-validated attributes. + * Update an egg variable. The input is validated here, so it can come straight from any + * caller. It takes the fields a variable is created with, required ones included; a + * description left out is blanked, and the variable can only be seen or edited by users + * when options lists user_viewable or user_editable. The variable keeps its own + * environment variable name without it counting as taken. * - * @param EggVariableData $data + * @param ActionInput $input the fields a variable is created with */ - public function update(EggVariable $variable, array $data): EggVariable; + public function update(EggVariable $variable, array $input): EggVariable; } diff --git a/app/Contracts/Eggs/UpdatesEggs.php b/app/Contracts/Eggs/UpdatesEggs.php index 3807b7790..095d5cc39 100644 --- a/app/Contracts/Eggs/UpdatesEggs.php +++ b/app/Contracts/Eggs/UpdatesEggs.php @@ -9,9 +9,13 @@ use Pterodactyl\Models\Egg; interface UpdatesEggs { /** - * Update an egg from request-validated attributes. + * Update an egg. The input is validated here, so it can come straight from any caller. + * It takes the fields an egg is created with, required ones included; a description, + * outgoing IP flag or features left out are cleared, while the parent egg and config + * blocks left out keep their stored values. The file denylist cannot be changed here. + * Extension field values go under `extensions` as ValidatedExtensionValues. * - * @param EggCreationData $data + * @param ActionInput $input the fields an egg is created with */ - public function update(Egg $egg, array $data): Egg; + public function update(Egg $egg, array $input): Egg; } diff --git a/app/Http/Controllers/Api/Admin/Eggs/EggController.php b/app/Http/Controllers/Api/Admin/Eggs/EggController.php index 8e95a6b72..4663e42a3 100644 --- a/app/Http/Controllers/Api/Admin/Eggs/EggController.php +++ b/app/Http/Controllers/Api/Admin/Eggs/EggController.php @@ -90,7 +90,7 @@ class EggController extends AdminApiController #[ExtensionFieldsParam] public function store(StoreEggRequest $request, CreatesEggs $eggs): JsonResponse { - $egg = $eggs->create($request->payload()); + $egg = $eggs->create($request->actionInput()); Activity::event('admin:egg.create') ->subject($egg) @@ -115,7 +115,7 @@ class EggController extends AdminApiController #[ExtensionFieldsParam] public function update(UpdateEggRequest $request, UpdatesEggs $eggs, Egg $egg): array { - $egg = $eggs->update($egg, $request->payload()); + $egg = $eggs->update($egg, $request->actionInput()); Activity::event('admin:egg.update') ->subject($egg) diff --git a/app/Http/Controllers/Api/Admin/Eggs/EggScriptController.php b/app/Http/Controllers/Api/Admin/Eggs/EggScriptController.php index 4b106b3fd..6eeea6df7 100644 --- a/app/Http/Controllers/Api/Admin/Eggs/EggScriptController.php +++ b/app/Http/Controllers/Api/Admin/Eggs/EggScriptController.php @@ -57,7 +57,7 @@ class EggScriptController extends AdminApiController #[ScribeResponse(self::INVALID_COPY_FROM_ERROR, status: 400, description: 'The selected copy source is invalid.')] public function update(UpdateEggScriptRequest $request, UpdatesEggInstallScripts $scripts, Egg $egg): array { - $egg = $scripts->update($egg, $request->payload()); + $egg = $scripts->update($egg, $request->actionInput()); Activity::event('admin:egg.scripts') ->subject($egg) diff --git a/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php b/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php index 2228af8e7..e2cb49955 100644 --- a/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php +++ b/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php @@ -55,7 +55,7 @@ class EggVariableController extends AdminApiController public function store(StoreVariableRequest $request, CreatesEggVariables $variables, Egg $egg): JsonResponse { - $variable = $variables->create($egg, $request->payload()); + $variable = $variables->create($egg, $request->actionInput()); Activity::event('admin:egg-variable.create') ->subject($egg, $variable) @@ -76,7 +76,7 @@ class EggVariableController extends AdminApiController #[ResponseFromTransformer(EggVariableTransformer::class, EggVariable::class, description: 'Egg variable updated.', resourceKey: 'egg_variable')] public function update(UpdateVariableRequest $request, UpdatesEggVariables $variables, Egg $egg, EggVariable $variable): array { - $variable = $variables->update($variable, $request->payload()); + $variable = $variables->update($variable, $request->actionInput()); Activity::event('admin:egg-variable.update') ->subject($egg, $variable) diff --git a/app/Http/Requests/Api/Admin/Eggs/StoreEggRequest.php b/app/Http/Requests/Api/Admin/Eggs/StoreEggRequest.php index 8cb7cc3f8..ce832d20a 100644 --- a/app/Http/Requests/Api/Admin/Eggs/StoreEggRequest.php +++ b/app/Http/Requests/Api/Admin/Eggs/StoreEggRequest.php @@ -5,12 +5,11 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Admin\Eggs; use Illuminate\Database\Eloquent\Model; -use Illuminate\Validation\Rule; +use Pterodactyl\Actions\Eggs\CreateEgg; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest; use Pterodactyl\Http\Requests\Concerns\ValidatesExtensionFields; use Pterodactyl\Models\Egg; -use Pterodactyl\Rules\DockerImageList; class StoreEggRequest extends AdminApiRequest { @@ -28,55 +27,7 @@ class StoreEggRequest extends AdminApiRequest */ public function rules(): array { - return [ - 'name' => ['required', 'string', 'max:191'], - 'description' => ['nullable', 'string'], - 'docker_images' => ['required', 'string', new DockerImageList], - 'force_outgoing_ip' => ['sometimes', 'boolean'], - 'file_denylist' => ['array'], - 'features' => ['sometimes', 'array'], - 'startup' => ['required', 'string'], - 'config_from' => ['sometimes', 'bail', 'nullable', 'integer', Rule::exists(Egg::class, 'id')], - 'config_stop' => ['required_without:config_from', 'nullable', 'string', 'max:191'], - 'config_startup' => ['required_without:config_from', 'nullable', 'json'], - 'config_logs' => ['required_without:config_from', 'nullable', 'json'], - 'config_files' => ['required_without:config_from', 'nullable', 'json'], - ]; - } - - /** - * Normalize docker_images and apply defaults before handing data to the service. - * - * @return EggCreationData - */ - public function payload(): array - { - $data = [ - 'name' => $this->string('name')->toString(), - 'description' => $this->filled('description') ? $this->string('description')->toString() : null, - 'docker_images' => $this->normalizeDockerImages($this->string('docker_images')->toString()), - 'force_outgoing_ip' => $this->boolean('force_outgoing_ip'), - 'features' => $this->stringList('features'), - 'startup' => $this->string('startup')->toString(), - ]; - - if ($this->has('file_denylist')) { - $data['file_denylist'] = $this->stringList('file_denylist'); - } - - if ($this->has('config_from')) { - $data['config_from'] = $this->filled('config_from') ? $this->integer('config_from') : null; - } - - foreach (['config_stop', 'config_startup', 'config_logs', 'config_files'] as $field) { - if ($this->has($field)) { - $data[$field] = $this->filled($field) ? $this->string($field)->toString() : null; - } - } - - $data['extensions'] = $this->extensionValues(); - - return $data; + return CreateEgg::rules(); } /** @@ -87,45 +38,22 @@ class StoreEggRequest extends AdminApiRequest return Egg::class; } - /** A zero config_from is the legacy "no parent egg" sentinel; treat it as null. */ + /** + * A zero config_from is the legacy "no parent egg" sentinel; treat it as null. The API + * drops any entry of features or file_denylist that is not a string, and reads a list + * sent as an object as empty, where the action would refuse them. + */ protected function prepareForValidation(): void { if ($this->has('config_from') && filter_var($this->input('config_from'), FILTER_VALIDATE_INT) === 0) { $this->merge(['config_from' => null]); } - } - /** - * Normalize a newline-delimited docker image string into a name => image array. - * - * @return array - */ - protected function normalizeDockerImages(?string $input = null): array - { - $images = []; - foreach (DockerImageList::lines($input ?? '') as $value) { - $parts = explode('|', $value, 2); - $images[$parts[0]] = empty($parts[1]) ? $parts[0] : $parts[1]; - } - - return $images; - } - - /** @return list */ - private function stringList(string $field): array - { - $values = $this->input($field, []); - if (! is_array($values) || ! array_is_list($values)) { - return []; - } - - $strings = []; - foreach ($values as $value) { - if (is_string($value)) { - $strings[] = $value; + foreach (['features', 'file_denylist'] as $field) { + $values = $this->input($field); + if (is_array($values)) { + $this->merge([$field => array_is_list($values) ? array_values(array_filter($values, is_string(...))) : []]); } } - - return $strings; } } diff --git a/app/Http/Requests/Api/Admin/Eggs/UpdateEggScriptRequest.php b/app/Http/Requests/Api/Admin/Eggs/UpdateEggScriptRequest.php index f3e6b3875..ad491b4b7 100644 --- a/app/Http/Requests/Api/Admin/Eggs/UpdateEggScriptRequest.php +++ b/app/Http/Requests/Api/Admin/Eggs/UpdateEggScriptRequest.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Admin\Eggs; +use Pterodactyl\Actions\Eggs\Scripts\UpdateInstallScript; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest; -use Pterodactyl\Support\JsonValueGuard; class UpdateEggScriptRequest extends AdminApiRequest { @@ -22,26 +22,6 @@ class UpdateEggScriptRequest extends AdminApiRequest */ public function rules(): array { - return [ - 'script_install' => ['sometimes', 'nullable', 'string'], - 'script_is_privileged' => ['sometimes', 'required', 'boolean'], - 'script_entry' => ['sometimes', 'required', 'string'], - 'script_container' => ['sometimes', 'required', 'string'], - 'copy_script_from' => ['sometimes', 'nullable', 'integer'], - ]; - } - - /** - * @return ModelAttributes - */ - public function payload(): array - { - $data = $this->validated(); - JsonValueGuard::assertPayload9($data); - if (array_key_exists('script_is_privileged', $data)) { - $data['script_is_privileged'] = $this->boolean('script_is_privileged'); - } - - return $data; + return UpdateInstallScript::rules(); } } diff --git a/app/Http/Requests/Api/Admin/Eggs/Variables/ReorderVariablesRequest.php b/app/Http/Requests/Api/Admin/Eggs/Variables/ReorderVariablesRequest.php index 46e353226..b0c214f3b 100644 --- a/app/Http/Requests/Api/Admin/Eggs/Variables/ReorderVariablesRequest.php +++ b/app/Http/Requests/Api/Admin/Eggs/Variables/ReorderVariablesRequest.php @@ -4,10 +4,9 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Admin\Eggs\Variables; -use Illuminate\Validation\Rule; +use Pterodactyl\Actions\Eggs\Variables\ReorderEggVariables; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest; -use Pterodactyl\Support\JsonValueGuard; class ReorderVariablesRequest extends AdminApiRequest { @@ -23,15 +22,18 @@ class ReorderVariablesRequest extends AdminApiRequest */ public function rules(): array { - return [ - 'order' => ['required', 'array', 'list'], - 'order.*' => ['required', Rule::anyOf([['integer:strict'], ['string']]), 'integer', 'distinct'], - ]; + return ReorderEggVariables::rules(); } - /** @return list */ + /** + * The validated variable ids, in their new order. + * + * @return list + */ public function order(): array { - return JsonValueGuard::normalizedIntegerList(JsonValueGuard::integerStringList($this->validated('order'))); + $validated = $this->safe(); + + return array_map(fn (int|string $key): int => $validated->integer('order.'.$key), array_keys($validated->array('order'))); } } diff --git a/app/Http/Requests/Api/Admin/Eggs/Variables/StoreVariableRequest.php b/app/Http/Requests/Api/Admin/Eggs/Variables/StoreVariableRequest.php index c9f33dfc5..a5c637a73 100644 --- a/app/Http/Requests/Api/Admin/Eggs/Variables/StoreVariableRequest.php +++ b/app/Http/Requests/Api/Admin/Eggs/Variables/StoreVariableRequest.php @@ -4,14 +4,10 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Admin\Eggs\Variables; -use Illuminate\Validation\Rule; -use Illuminate\Validation\Rules\Unique; +use Pterodactyl\Actions\Eggs\Variables\CreateEggVariable; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest; use Pterodactyl\Models\Egg; -use Pterodactyl\Models\EggVariable; -use Pterodactyl\Support\JsonValueGuard; -use Pterodactyl\Validation\EggVariableRules; class StoreVariableRequest extends AdminApiRequest { @@ -27,40 +23,6 @@ class StoreVariableRequest extends AdminApiRequest */ public function rules(): array { - $rules = EggVariableRules::rules(); - $rules['env_variable'][] = $this->uniqueEnvironmentVariable(); - - return array_merge($rules, [ - 'options' => ['sometimes', 'required', 'array', 'list'], - 'options.*' => ['string'], - ]); - } - - /** - * Model attributes for the variable; the options list becomes the two flags. - * - * @return EggVariableData - */ - public function payload(): array - { - $options = JsonValueGuard::stringList($this->input('options', [])); - - return [ - 'name' => $this->string('name')->toString(), - 'description' => JsonValueGuard::nullableString($this->input('description')) ?? '', - 'env_variable' => $this->string('env_variable')->toString(), - 'default_value' => JsonValueGuard::string($this->input('default_value')), - 'user_viewable' => in_array('user_viewable', $options, true), - 'user_editable' => in_array('user_editable', $options, true), - 'rules' => $this->string('rules')->toString(), - ]; - } - - /** - * The environment variable name must be unique among the egg's variables. - */ - protected function uniqueEnvironmentVariable(): Unique - { - return Rule::unique(EggVariable::class, 'env_variable')->where('egg_id', $this->parameter('egg', Egg::class)->id); + return CreateEggVariable::rules($this->parameter('egg', Egg::class)); } } diff --git a/app/Http/Requests/Api/Admin/Eggs/Variables/UpdateVariableRequest.php b/app/Http/Requests/Api/Admin/Eggs/Variables/UpdateVariableRequest.php index fbbe9dca0..f14828435 100644 --- a/app/Http/Requests/Api/Admin/Eggs/Variables/UpdateVariableRequest.php +++ b/app/Http/Requests/Api/Admin/Eggs/Variables/UpdateVariableRequest.php @@ -4,8 +4,9 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Admin\Eggs\Variables; -use Illuminate\Validation\Rules\Unique; +use Pterodactyl\Actions\Eggs\Variables\CreateEggVariable; use Pterodactyl\Enum\Permissions; +use Pterodactyl\Models\Egg; use Pterodactyl\Models\EggVariable; class UpdateVariableRequest extends StoreVariableRequest @@ -15,8 +16,14 @@ class UpdateVariableRequest extends StoreVariableRequest return [Permissions::AdminEggVariablesUpdate]; } - protected function uniqueEnvironmentVariable(): Unique + /** + * Validation rules for updating an egg variable, which keeps its own environment + * variable name without a uniqueness clash. + * + * @return ValidationRules + */ + public function rules(): array { - return parent::uniqueEnvironmentVariable()->ignore($this->parameter('variable', EggVariable::class)); + return CreateEggVariable::rules($this->parameter('egg', Egg::class), $this->parameter('variable', EggVariable::class)); } } diff --git a/app/Http/Requests/Api/Client/Servers/Settings/SetDockerImageRequest.php b/app/Http/Requests/Api/Client/Servers/Settings/SetDockerImageRequest.php index cd4bed6b3..dbe1e0f48 100644 --- a/app/Http/Requests/Api/Client/Servers/Settings/SetDockerImageRequest.php +++ b/app/Http/Requests/Api/Client/Servers/Settings/SetDockerImageRequest.php @@ -5,11 +5,11 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Client\Servers\Settings; use Illuminate\Validation\Rule; +use Pterodactyl\Actions\Eggs\CreateEgg; use Pterodactyl\Contracts\Http\ClientPermissionsRequest; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest; use Pterodactyl\Models\Server; -use Pterodactyl\Validation\EggRules; use UnexpectedValueException; class SetDockerImageRequest extends ClientApiRequest implements ClientPermissionsRequest @@ -25,13 +25,13 @@ class SetDockerImageRequest extends ClientApiRequest implements ClientPermission public function rules(): array { if (! $this->filled('docker_image')) { - return ['docker_image' => EggRules::DOCKER_IMAGE]; + return ['docker_image' => CreateEgg::DOCKER_IMAGE]; } $server = $this->parameter('server', Server::class); $egg = $server->egg ?? throw new UnexpectedValueException('The server does not have an egg relationship.'); // Only one of the images the server's egg offers can be chosen. - return ['docker_image' => [...EggRules::DOCKER_IMAGE, Rule::in(array_values($egg->docker_images))]]; + return ['docker_image' => [...CreateEgg::DOCKER_IMAGE, Rule::in(array_values($egg->docker_images))]]; } } diff --git a/app/Rules/DockerImageList.php b/app/Rules/DockerImageList.php index 4ee3619b0..967a0c9a0 100644 --- a/app/Rules/DockerImageList.php +++ b/app/Rules/DockerImageList.php @@ -8,7 +8,7 @@ use Closure; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; -use Pterodactyl\Validation\EggRules; +use Pterodactyl\Actions\Eggs\CreateEgg; /** * A newline-separated list of Docker images, as the admin egg form submits them. Each @@ -47,7 +47,7 @@ class DockerImageList implements ValidationRule } foreach ($images as $image) { - if (Validator::make(['image' => $image], ['image' => EggRules::DOCKER_IMAGE])->fails()) { + if (Validator::make(['image' => $image], ['image' => CreateEgg::DOCKER_IMAGE])->fails()) { $fail(sprintf('The :attribute entry "%s" is not a valid Docker image.', Str::limit($image, 64))); return; diff --git a/app/Services/Eggs/EggImportData.php b/app/Services/Eggs/EggImportData.php index d1a508418..b7545bfc5 100644 --- a/app/Services/Eggs/EggImportData.php +++ b/app/Services/Eggs/EggImportData.php @@ -5,10 +5,12 @@ declare(strict_types=1); namespace Pterodactyl\Services\Eggs; use Illuminate\Support\Facades\Validator; +use Pterodactyl\Actions\Eggs\CreateEgg; +use Pterodactyl\Actions\Eggs\Variables\CreateEggVariable; use Pterodactyl\Exceptions\Service\InvalidFileUploadException; use Pterodactyl\Models\Egg; use Pterodactyl\Support\JsonValueGuard; -use Pterodactyl\Validation\EggRules; +use Pterodactyl\Support\ValidationRuleSubset; final readonly class EggImportData { @@ -228,6 +230,41 @@ final readonly class EggImportData return new InvalidFileUploadException(sprintf('The egg field "%s" is missing or invalid.', $field)); } + /** + * The rules an egg read from an export file must pass, keyed like its model attributes. + * Exports carry their own config rather than inheriting one, so every config block is + * checked as JSON. Each image and each variable is held to the rules of one written + * through the admin API. An imported variable carries its user_viewable and user_editable + * flags rather than options, and its environment variable name must differ from the + * others'. + * + * @return NormalizedValidationRules + */ + private function rules(): array + { + $rules = [ + 'name' => ['required', 'string', 'max:191'], + 'author' => ['required', 'string', 'email'], + 'docker_images' => ['required', 'array', 'min:1'], + 'docker_images.*' => CreateEgg::DOCKER_IMAGE, + 'startup' => ['nullable', 'string'], + 'config_stop' => ['nullable', 'string', 'max:191'], + 'config_startup' => ['nullable', 'json'], + 'config_logs' => ['nullable', 'json'], + 'config_files' => ['nullable', 'json'], + 'variables' => ['array'], + ]; + + $variable = ValidationRuleSubset::select(CreateEggVariable::rules(), ['name', 'description', 'env_variable', 'rules', 'default_value']); + foreach ($variable as $field => $fieldRules) { + $rules["variables.*.{$field}"] = $fieldRules; + } + + $rules['variables.*.env_variable'][] = 'distinct'; + + return $rules; + } + /** * Holds an imported egg to the rules an egg written through the admin API meets, so a * file cannot store config that every node serving the egg would later fail to read. @@ -244,7 +281,7 @@ final readonly class EggImportData 'config_logs' => $this->configLogs, 'config_files' => $this->configFiles, 'variables' => array_map(fn (EggImportVariable $variable): array => $variable->attributes(), $this->variables), - ], EggRules::import()); + ], $this->rules()); if ($validator->fails()) { $errors = $validator->errors(); diff --git a/app/Validation/EggRules.php b/app/Validation/EggRules.php deleted file mode 100644 index 0546475b1..000000000 --- a/app/Validation/EggRules.php +++ /dev/null @@ -1,46 +0,0 @@ - - */ - public const array DOCKER_IMAGE = ['required', 'string', 'max:191', 'regex:/^[\w#\.\/\- ]*\|?~?[\w\.\/\-:@ ]*$/']; - - /** - * Validation rules for an egg read from an export file, keyed like its model attributes. - * Exports carry their own config rather than inheriting one, so every config block is - * checked as JSON. - * - * @return NormalizedValidationRules - */ - public static function import(): array - { - $rules = [ - 'name' => ['required', 'string', 'max:191'], - 'author' => ['required', 'string', 'email'], - 'docker_images' => ['required', 'array', 'min:1'], - 'docker_images.*' => self::DOCKER_IMAGE, - 'startup' => ['nullable', 'string'], - 'config_stop' => ['nullable', 'string', 'max:191'], - 'config_startup' => ['nullable', 'json'], - 'config_logs' => ['nullable', 'json'], - 'config_files' => ['nullable', 'json'], - 'variables' => ['array'], - ]; - - foreach (EggVariableRules::rules() as $field => $fieldRules) { - $rules["variables.*.{$field}"] = $fieldRules; - } - - $rules['variables.*.env_variable'][] = 'distinct'; - - return $rules; - } -} diff --git a/app/Validation/EggVariableRules.php b/app/Validation/EggVariableRules.php deleted file mode 100644 index 3fd892607..000000000 --- a/app/Validation/EggVariableRules.php +++ /dev/null @@ -1,28 +0,0 @@ - ['required', 'string', 'min:1', 'max:191'], - 'description' => ['sometimes', 'nullable', 'string'], - 'env_variable' => ['required', 'regex:/^[\w]{1,191}$/', new UnreservedEnvironmentVariable], - 'rules' => ['bail', 'required', 'string', new ValidRuleSet], - 'default_value' => ['present', 'string'], - ]; - } -} diff --git a/phpstan.neon b/phpstan.neon index 2c0535e65..02805908d 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -85,10 +85,8 @@ parameters: DatabaseCreationData: 'array{database: string, remote: string, database_host_id: int, max_connections?: int|null}' DatabaseDeploymentData: 'array{database: string, remote: string, database_host_id?: int|null, max_connections?: int|null}' DatabaseModelCreationData: 'array{database: string, remote: string, database_host_id: int, max_connections?: int|null, server_id: int, username: string, password: string}' - 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}' SftpAuthenticationData: 'array{type: string|null, username: string, password: string}' - EggCreationData: 'array{name: string, description: string|null, docker_images: array, force_outgoing_ip: bool, features: list, startup: string, file_denylist?: list, 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}' ServerTransferData: 'array{node_id: int, allocation_id: int, allocation_additional: list}' BackupCompletionData: 'array{successful: bool, checksum: string|null, checksum_type: string|null, size: int, parts: list|null}' BackupUploadParts: 'array{parts: list, part_size: int}' diff --git a/tests/Integration/Actions/Eggs/CreateEggTest.php b/tests/Integration/Actions/Eggs/CreateEggTest.php new file mode 100644 index 000000000..c067b0fa9 --- /dev/null +++ b/tests/Integration/Actions/Eggs/CreateEggTest.php @@ -0,0 +1,105 @@ + */ +function egg(array $overrides = []): array +{ + return [...[ + 'name' => 'Direct Egg', + 'docker_images' => "Java 21|ghcr.io/pterodactyl/yolks:java_21\nghcr.io/pterodactyl/yolks:java_17", + 'startup' => 'java -jar server.jar', + 'config_stop' => 'stop', + 'config_startup' => '{"done": ["Done"]}', + 'config_logs' => '{}', + 'config_files' => '{}', + ], ...$overrides]; +} + +test('eggs created without the http api meet the same rules', function (array $input, string $field): void { + $count = Egg::query()->count(); + + try { + $this->app->make(CreatesEggs::class)->create(egg($input)); + $this->fail('The egg was created.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect(Egg::query()->count())->toBe($count); +})->with([ + 'a missing name' => [['name' => null], 'name'], + 'a name that is too long' => [['name' => str_repeat('a', 192)], 'name'], + 'docker images given as a list' => [['docker_images' => ['ghcr.io/pterodactyl/yolks:java_21']], 'docker_images'], + 'a docker image line with shell characters' => [['docker_images' => "ghcr.io/pterodactyl/yolks:java_21\nghcr.io/x;rm -rf /"], 'docker_images'], + 'only blank docker image lines' => [['docker_images' => "\n \n"], 'docker_images'], + 'an outgoing ip flag that is not a boolean' => [['force_outgoing_ip' => 'yes'], 'force_outgoing_ip'], + 'features that are not a list' => [['features' => 'eula'], 'features'], + 'a feature that is not a string' => [['features' => ['eula', 5]], 'features.1'], + 'a denied file that is not a string' => [['file_denylist' => [['nested']]], 'file_denylist.0'], + 'a missing startup command' => [['startup' => ''], 'startup'], + 'a parent egg that does not exist' => [['config_from' => 999999], 'config_from'], + 'a missing stop command without a parent egg' => [['config_stop' => null], 'config_stop'], + 'a stop command that is too long' => [['config_stop' => str_repeat('a', 192)], 'config_stop'], + 'startup config that is not json' => [['config_startup' => '{done'], 'config_startup'], + 'files config that is not json' => [['config_files' => 'files'], 'config_files'], +]); + +test('an egg is created with its images keyed by name and the service author', function (): void { + config()->set('pterodactyl.service.author', 'eggs@example.com'); + + $egg = $this->app->make(CreatesEggs::class)->create(egg([ + 'description' => '', + 'features' => ['eula', 'fastdl'], + 'file_denylist' => ['secret.txt'], + ])); + + expect($egg->author)->toBe('eggs@example.com') + ->and($egg->docker_images)->toBe(['Java 21' => 'ghcr.io/pterodactyl/yolks:java_21', 'ghcr.io/pterodactyl/yolks:java_17' => 'ghcr.io/pterodactyl/yolks:java_17']) + ->and($egg->description)->toBeNull() + ->and($egg->features)->toBe(['eula', 'fastdl']) + ->and($egg->file_denylist)->toBe(['secret.txt']) + ->and($egg->force_outgoing_ip)->toBeFalse() + ->and($egg->config_from)->toBeNull() + ->and($egg->config_startup)->toBe('{"done": ["Done"]}'); +}); + +test('values are coerced the way laravel validates them', function (int|string $flag, bool $expected): void { + $parent = Egg::factory()->create(); + + $egg = $this->app->make(CreatesEggs::class)->create([ + 'name' => 'Child Egg', + 'docker_images' => 'ghcr.io/pterodactyl/yolks:java_21', + 'startup' => 'java -jar server.jar', + 'force_outgoing_ip' => $flag, + 'config_from' => (string) $parent->id, + ]); + + expect($egg->force_outgoing_ip)->toBe($expected) + ->and($egg->config_from)->toBe($parent->id) + ->and($egg->config_stop)->toBeNull() + ->and($egg->features)->toBe([]); +})->with([[1, true], ['1', true], [0, false], ['0', false]]); + +test('a parent egg of zero means none, so the egg needs its own config', function (int|string $none): void { + $eggs = $this->app->make(CreatesEggs::class); + + try { + $eggs->create(egg(['config_from' => $none, 'config_stop' => null])); + $this->fail('The egg was created.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe(['config_stop']); + } + + expect($eggs->create(egg(['config_from' => $none]))->config_from)->toBeNull(); +})->with([0, '0']); diff --git a/tests/Integration/Actions/Eggs/Scripts/UpdateInstallScriptTest.php b/tests/Integration/Actions/Eggs/Scripts/UpdateInstallScriptTest.php new file mode 100644 index 000000000..a436b4ae1 --- /dev/null +++ b/tests/Integration/Actions/Eggs/Scripts/UpdateInstallScriptTest.php @@ -0,0 +1,78 @@ +create(['script_install' => 'echo "original"', 'script_entry' => 'bash', 'script_container' => 'alpine:3.4'])->refresh(); + $before = $egg->getAttributes(); + + try { + $this->app->make(UpdatesEggInstallScripts::class)->update($egg, $input); + $this->fail('The script was updated.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect($egg->fresh()->getAttributes())->toBe($before); +})->with([ + 'a script that is not a string' => [['script_install' => ['echo']], 'script_install'], + 'a privileged flag that is not a boolean' => [['script_is_privileged' => 'yes'], 'script_is_privileged'], + 'a null privileged flag' => [['script_is_privileged' => null], 'script_is_privileged'], + 'a blank entrypoint' => [['script_entry' => ''], 'script_entry'], + 'a container that is not a string' => [['script_container' => 5], 'script_container'], + 'a copy source that is not a number' => [['copy_script_from' => 'not-a-number'], 'copy_script_from'], +]); + +test('an update changes only the fields it is given', function (): void { + $source = Egg::factory()->create(); + $egg = Egg::factory()->create(['script_install' => 'echo "original"', 'script_is_privileged' => true, 'script_entry' => 'bash', 'script_container' => 'alpine:3.4', 'copy_script_from' => $source->id]); + $scripts = $this->app->make(UpdatesEggInstallScripts::class); + + $scripts->update($egg, ['script_entry' => 'ash']); + $egg->refresh(); + expect($egg->script_entry)->toBe('ash') + ->and($egg->script_install)->toBe('echo "original"') + ->and($egg->script_is_privileged)->toBeTrue() + ->and($egg->script_container)->toBe('alpine:3.4') + ->and($egg->copy_script_from)->toBe($source->id); + + $scripts->update($egg, ['script_install' => '', 'copy_script_from' => null]); + $egg->refresh(); + expect($egg->script_install)->toBeNull() + ->and($egg->copy_script_from)->toBeNull() + ->and($egg->script_entry)->toBe('ash'); +}); + +test('values are coerced the way laravel validates them', function (int|string $flag, bool $expected): void { + $source = Egg::factory()->create(); + $egg = Egg::factory()->create(['script_is_privileged' => ! $expected]); + + $this->app->make(UpdatesEggInstallScripts::class)->update($egg, ['script_is_privileged' => $flag, 'copy_script_from' => (string) $source->id]); + + $egg->refresh(); + expect($egg->script_is_privileged)->toBe($expected) + ->and($egg->copy_script_from)->toBe($source->id); +})->with([[1, true], ['1', true], [0, false], ['0', false]]); + +test('a script can only be copied from an egg with a script of its own', function (): void { + $source = Egg::factory()->create(); + $copy = Egg::factory()->create(['copy_script_from' => $source->id]); + $egg = Egg::factory()->create(['script_entry' => 'bash']); + $scripts = $this->app->make(UpdatesEggInstallScripts::class); + + expect(fn () => $scripts->update($egg, ['script_entry' => 'ash', 'copy_script_from' => $copy->id]))->toThrow(InvalidCopyFromException::class) + ->and(fn () => $scripts->update($egg, ['copy_script_from' => 999999]))->toThrow(InvalidCopyFromException::class) + ->and($egg->refresh()->script_entry)->toBe('bash') + ->and($egg->copy_script_from)->toBeNull(); +}); diff --git a/tests/Integration/Actions/Eggs/UpdateEggTest.php b/tests/Integration/Actions/Eggs/UpdateEggTest.php new file mode 100644 index 000000000..86b944ec9 --- /dev/null +++ b/tests/Integration/Actions/Eggs/UpdateEggTest.php @@ -0,0 +1,93 @@ + */ +function egg(array $overrides = []): array +{ + return [...[ + 'name' => 'Updated Egg', + 'docker_images' => 'Java 21|ghcr.io/pterodactyl/yolks:java_21', + 'startup' => 'java -jar updated.jar', + 'config_stop' => '^C', + 'config_startup' => '{}', + 'config_logs' => '{}', + 'config_files' => '{}', + ], ...$overrides]; +} + +test('eggs updated without the http api meet the same rules', function (array $input, string $field): void { + $egg = Egg::factory()->create()->refresh(); + $before = $egg->getAttributes(); + + try { + $this->app->make(UpdatesEggs::class)->update($egg, egg($input)); + $this->fail('The egg was updated.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect($egg->fresh()->getAttributes())->toBe($before); +})->with([ + 'a missing name' => [['name' => ''], 'name'], + 'a missing docker image list' => [['docker_images' => null], 'docker_images'], + 'an invalid docker image' => [['docker_images' => 'ghcr.io/x;rm -rf /'], 'docker_images'], + 'a feature that is not a string' => [['features' => [['eula']]], 'features.0'], + 'an outgoing ip flag that is not a boolean' => [['force_outgoing_ip' => 'sometimes'], 'force_outgoing_ip'], + 'a parent egg that does not exist' => [['config_from' => 999999], 'config_from'], + 'logs config that is not json' => [['config_logs' => 'logs'], 'config_logs'], + 'no logs config and no parent egg' => [['config_logs' => null], 'config_logs'], +]); + +test('an update replaces the egg fields and keeps the config it is not given', function (): void { + $parent = Egg::factory()->create(); + $egg = Egg::factory()->create(['force_outgoing_ip' => true, 'features' => ['eula'], 'file_denylist' => ['secret.txt']])->refresh(); + $config = $egg->only(['config_startup', 'config_logs', 'config_files']); + + $this->app->make(UpdatesEggs::class)->update($egg, [ + 'name' => 'Updated Egg', + 'docker_images' => 'Java 21|ghcr.io/pterodactyl/yolks:java_21', + 'startup' => 'java -jar updated.jar', + 'config_from' => $parent->id, + 'config_stop' => '', + 'file_denylist' => ['other.txt'], + ]); + + $egg->refresh(); + expect($egg->name)->toBe('Updated Egg') + ->and($egg->docker_images)->toBe(['Java 21' => 'ghcr.io/pterodactyl/yolks:java_21']) + ->and($egg->startup)->toBe('java -jar updated.jar') + ->and($egg->config_from)->toBe($parent->id) + ->and($egg->config_stop)->toBeNull() + ->and($egg->only(['config_startup', 'config_logs', 'config_files']))->toBe($config) + // Left out, the description, outgoing IP flag and features are cleared. + ->and($egg->description)->toBeNull() + ->and($egg->force_outgoing_ip)->toBeFalse() + ->and($egg->features)->toBe([]) + // The denylist cannot be changed through an update yet. + ->and($egg->file_denylist)->toBe(['secret.txt']); +}); + +test('values are coerced the way laravel validates them', function (int|string $flag, bool $expected): void { + $parent = Egg::factory()->create(); + $egg = Egg::factory()->create(); + + $this->app->make(UpdatesEggs::class)->update($egg, egg(['force_outgoing_ip' => $flag, 'config_from' => (string) $parent->id])); + + $egg->refresh(); + expect($egg->force_outgoing_ip)->toBe($expected) + ->and($egg->config_from)->toBe($parent->id); + + $this->app->make(UpdatesEggs::class)->update($egg, egg(['config_from' => '0'])); + expect($egg->refresh()->config_from)->toBeNull(); +})->with([[1, true], ['1', true], [0, false], ['0', false]]); diff --git a/tests/Integration/Actions/Eggs/Variables/CreateEggVariableTest.php b/tests/Integration/Actions/Eggs/Variables/CreateEggVariableTest.php new file mode 100644 index 000000000..b9ff3c883 --- /dev/null +++ b/tests/Integration/Actions/Eggs/Variables/CreateEggVariableTest.php @@ -0,0 +1,71 @@ + */ +function variable(array $overrides = []): array +{ + return [...['name' => 'Server Jar', 'env_variable' => 'SERVER_JARFILE', 'rules' => 'required|string', 'default_value' => 'server.jar'], ...$overrides]; +} + +test('variables created without the http api meet the same rules', function (array $input, string $field): void { + $egg = Egg::factory()->create(); + EggVariable::factory()->for($egg)->create(['env_variable' => 'TAKEN']); + + try { + $this->app->make(CreatesEggVariables::class)->create($egg, variable($input)); + $this->fail('The variable was created.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect($egg->variables()->count())->toBe(1); +})->with([ + 'a missing name' => [['name' => null], 'name'], + 'a description that is not a string' => [['description' => ['text']], 'description'], + 'a missing environment variable' => [['env_variable' => ''], 'env_variable'], + 'an environment variable with a dash' => [['env_variable' => 'SERVER-JAR'], 'env_variable'], + 'a reserved environment variable' => [['env_variable' => 'server_port'], 'env_variable'], + 'an environment variable the egg already has' => [['env_variable' => 'TAKEN'], 'env_variable'], + 'a rule laravel does not know' => [['rules' => 'requird|string'], 'rules'], + 'no default value' => [['default_value' => null], 'default_value'], + 'options that are not a list' => [['options' => ['viewable' => 'user_viewable']], 'options'], + 'an option that is not a string' => [['options' => ['user_viewable', 42]], 'options.1'], + 'an empty list of options' => [['options' => []], 'options'], +]); + +test('the options set whether users can see and edit the variable', function (?array $options, bool $viewable, bool $editable): void { + $egg = Egg::factory()->create(); + + $variable = $this->app->make(CreatesEggVariables::class)->create($egg, variable($options === null ? [] : ['options' => $options])); + + expect($variable->egg_id)->toBe($egg->id) + ->and($variable->user_viewable)->toBe($viewable) + ->and($variable->user_editable)->toBe($editable) + ->and($variable->description)->toBe(''); +})->with([ + 'none given' => [null, false, false], + 'viewable' => [['user_viewable'], true, false], + 'both, with an option nothing reads' => [['user_editable', 'unknown', 'user_viewable'], true, true], +]); + +test('an environment variable another egg has is free to use', function (): void { + EggVariable::factory()->for(Egg::factory())->create(['env_variable' => 'SHARED']); + $egg = Egg::factory()->create(); + + $variable = $this->app->make(CreatesEggVariables::class)->create($egg, variable(['env_variable' => 'SHARED', 'description' => 'Shared.'])); + + expect($variable->env_variable)->toBe('SHARED') + ->and($variable->description)->toBe('Shared.'); +}); diff --git a/tests/Integration/Actions/Eggs/Variables/ReorderEggVariablesTest.php b/tests/Integration/Actions/Eggs/Variables/ReorderEggVariablesTest.php new file mode 100644 index 000000000..605e262a2 --- /dev/null +++ b/tests/Integration/Actions/Eggs/Variables/ReorderEggVariablesTest.php @@ -0,0 +1,51 @@ +create(); + $variable = EggVariable::factory()->for($egg)->create(['sort_order' => 5]); + + try { + // "id" stands in for the id of the egg's variable. + $this->app->make(ReordersEggVariables::class)->reorder($egg, array_map(fn (mixed $id): mixed => $id === 'id' ? $variable->id : $id, $order)); + $this->fail('The variables were reordered.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe($fields); + } + + expect($variable->refresh()->sort_order)->toBe(5); +})->with([ + 'no ids' => [[], ['order']], + 'ids keyed by name' => [['first' => 'id'], ['order']], + 'an id that is not a number' => [['id', 'abc'], ['order.1']], + 'a whole float' => [[1.0], ['order.0']], + 'a boolean' => [[true], ['order.0']], + 'a null id' => [[null], ['order.0']], + 'the same id twice' => [['id', 'id'], ['order.0', 'order.1']], +]); + +test('the variables take the sort order of their position, ids given as integers or numeric strings', function (): void { + $egg = Egg::factory()->create(); + [$first, $second, $third] = EggVariable::factory()->for($egg)->count(3)->create()->all(); + $other = EggVariable::factory()->for(Egg::factory())->create(['sort_order' => 7]); + + $this->app->make(ReordersEggVariables::class)->reorder($egg, [(string) $third->id, $first->id, $other->id, (string) $second->id]); + + expect($third->refresh()->sort_order)->toBe(0) + ->and($first->refresh()->sort_order)->toBe(1) + ->and($second->refresh()->sort_order)->toBe(3) + // A variable of another egg is skipped. + ->and($other->refresh()->sort_order)->toBe(7); +}); diff --git a/tests/Integration/Actions/Eggs/Variables/UpdateEggVariableTest.php b/tests/Integration/Actions/Eggs/Variables/UpdateEggVariableTest.php new file mode 100644 index 000000000..5678ae9fd --- /dev/null +++ b/tests/Integration/Actions/Eggs/Variables/UpdateEggVariableTest.php @@ -0,0 +1,67 @@ + */ +function variable(array $overrides = []): array +{ + return [...['name' => 'Renamed', 'env_variable' => 'KEEP_ME', 'rules' => 'required|string', 'default_value' => 'kept'], ...$overrides]; +} + +test('variables updated without the http api meet the same rules', function (array $input, string $field): void { + $egg = Egg::factory()->create(); + EggVariable::factory()->for($egg)->create(['env_variable' => 'TAKEN']); + $variable = EggVariable::factory()->for($egg)->create(['env_variable' => 'KEEP_ME'])->refresh(); + $before = $variable->getAttributes(); + + try { + $this->app->make(UpdatesEggVariables::class)->update($variable, variable($input)); + $this->fail('The variable was updated.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect($variable->fresh()->getAttributes())->toBe($before); +})->with([ + 'a missing name' => [['name' => ''], 'name'], + 'an environment variable another variable of the egg has' => [['env_variable' => 'TAKEN'], 'env_variable'], + 'a reserved environment variable' => [['env_variable' => 'STARTUP'], 'env_variable'], + 'a default value that is not a string' => [['default_value' => ['nested']], 'default_value'], + 'a rule laravel does not know' => [['rules' => 'string|requird'], 'rules'], +]); + +test('a variable keeps its own environment variable and takes the fields it is given', function (): void { + $egg = Egg::factory()->create(); + $variable = EggVariable::factory()->for($egg)->viewable()->editable()->create(['env_variable' => 'KEEP_ME', 'description' => 'Old.']); + + $this->app->make(UpdatesEggVariables::class)->update($variable, variable(['options' => ['user_editable']])); + + $variable->refresh(); + expect($variable->name)->toBe('Renamed') + ->and($variable->env_variable)->toBe('KEEP_ME') + ->and($variable->default_value)->toBe('kept') + // Left out, the description is blanked; an option left out is unset. + ->and($variable->description)->toBe('') + ->and($variable->user_viewable)->toBeFalse() + ->and($variable->user_editable)->toBeTrue(); +}); + +test('a variable can take an environment variable another egg has', function (): void { + EggVariable::factory()->for(Egg::factory())->create(['env_variable' => 'SHARED']); + $variable = EggVariable::factory()->for(Egg::factory())->create(); + + $this->app->make(UpdatesEggVariables::class)->update($variable, variable(['env_variable' => 'SHARED'])); + + expect($variable->refresh()->env_variable)->toBe('SHARED'); +}); diff --git a/tests/Integration/Api/Admin/Eggs/EggCrudControllerTest.php b/tests/Integration/Api/Admin/Eggs/EggCrudControllerTest.php index 5942b48a2..2fccaab05 100644 --- a/tests/Integration/Api/Admin/Eggs/EggCrudControllerTest.php +++ b/tests/Integration/Api/Admin/Eggs/EggCrudControllerTest.php @@ -73,6 +73,19 @@ test('blank lines between docker images are ignored', function (): void { expect(Egg::query()->where('name', 'Test Egg')->firstOrFail()->docker_images)->toBe(['Java 17' => 'ghcr.io/pterodactyl/yolks:java_17', 'Java 11' => 'ghcr.io/pterodactyl/yolks:java_11']); }); +test('features and denied files that are not strings are dropped', function (): void { + $this->postJson(route('api.admin.eggs.store'), array_merge(validCreatePayload(), ['features' => ['eula', 5, ['fastdl']], 'file_denylist' => ['secret.txt', true]])) + ->assertCreated(); + + $egg = Egg::query()->where('name', 'Test Egg')->firstOrFail(); + expect($egg->features)->toBe(['eula']) + ->and($egg->file_denylist)->toBe(['secret.txt']); + + $this->putJson(route('api.admin.eggs.update', ['egg' => $egg->id]), array_merge(validCreatePayload(), ['features' => ['name' => 'eula']])) + ->assertOk(); + + expect($egg->refresh()->features)->toBe([]); +}); test('update egg', function (): void { $egg = Egg::factory()->create(); $response = $this->putJson(route('api.admin.eggs.update', ['egg' => $egg->id]), array_merge(validCreatePayload(), ['name' => 'Updated Egg', 'startup' => 'java -jar updated.jar'])); diff --git a/tests/Integration/Api/Admin/Eggs/EggScriptControllerTest.php b/tests/Integration/Api/Admin/Eggs/EggScriptControllerTest.php index be4c84136..c6c9d9139 100644 --- a/tests/Integration/Api/Admin/Eggs/EggScriptControllerTest.php +++ b/tests/Integration/Api/Admin/Eggs/EggScriptControllerTest.php @@ -55,6 +55,21 @@ test('update script accepts string flags and ids', function () { $egg->refresh(); expect($egg->script_is_privileged)->toBeFalse()->and($egg->copy_script_from)->toBe($source->id); }); +test('update script changes only the fields it is given', function () { + $source = Egg::factory()->create(); + $egg = Egg::factory()->create(['script_install' => 'echo "original"', 'script_is_privileged' => false, 'script_entry' => 'bash', 'script_container' => 'alpine:3.4', 'copy_script_from' => $source->id]); + + $this->putJson(route('api.admin.eggs.script.update', ['egg' => $egg->id]), ['script_container' => 'alpine:3.20']) + ->assertOk() + ->assertJsonPath('attributes.script.container', 'alpine:3.20'); + + $egg->refresh(); + expect($egg->script_container)->toBe('alpine:3.20') + ->and($egg->script_install)->toBe('echo "original"') + ->and($egg->script_is_privileged)->toBeFalse() + ->and($egg->script_entry)->toBe('bash') + ->and($egg->copy_script_from)->toBe($source->id); +}); test('update script copy from must be an integer', function () { $egg = Egg::factory()->create(); $response = $this->putJson(route('api.admin.eggs.script.update', ['egg' => $egg->id]), ['copy_script_from' => 'not-a-number']);