From c15f0fed14f23a80379af727df548508bfb4dbb0 Mon Sep 17 00:00:00 2001 From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com> Date: Sun, 11 Oct 2026 08:00:46 -0400 Subject: [PATCH] subuser actions --- app/Actions/Subusers/CreateSubuser.php | 66 ++++++++++++++- app/Actions/Subusers/UpdateSubuser.php | 7 ++ app/Contracts/Subusers/CreatesSubusers.php | 4 + app/Contracts/Subusers/UpdatesSubusers.php | 4 + .../Servers/Subusers/StoreSubuserRequest.php | 8 +- .../Servers/Subusers/SubuserRequest.php | 3 +- .../Servers/Subusers/UpdateSubuserRequest.php | 7 +- .../Actions/Subusers/CreateSubuserTest.php | 80 +++++++++++++++++++ .../Actions/Subusers/UpdateSubuserTest.php | 64 +++++++++++++++ .../Server/Subuser/UpdateSubuserTest.php | 18 +++++ 10 files changed, 246 insertions(+), 15 deletions(-) create mode 100644 tests/Integration/Actions/Subusers/CreateSubuserTest.php create mode 100644 tests/Integration/Actions/Subusers/UpdateSubuserTest.php diff --git a/app/Actions/Subusers/CreateSubuser.php b/app/Actions/Subusers/CreateSubuser.php index e2724da19..5e9a78a70 100644 --- a/app/Actions/Subusers/CreateSubuser.php +++ b/app/Actions/Subusers/CreateSubuser.php @@ -5,7 +5,9 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Subusers; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; +use Illuminate\Validation\Rule; use Pterodactyl\Contracts\Subusers\CreatesSubusers; use Pterodactyl\Contracts\Users\CreatesUsers; use Pterodactyl\Exceptions\Service\Subuser\ServerSubuserExistsException; @@ -13,11 +15,65 @@ use Pterodactyl\Exceptions\Service\Subuser\UserIsServerOwnerException; use Pterodactyl\Models\Server; use Pterodactyl\Models\Subuser; use Pterodactyl\Models\User; +use Pterodactyl\Rules\UserEmail; +use Pterodactyl\Services\Servers\SubuserPermissionCatalog; +use Pterodactyl\Support\ValidationRuleSubset; use Throwable; final readonly class CreateSubuser implements CreatesSubusers { - public function __construct(private CreatesUsers $users) {} + public function __construct(private CreatesUsers $users, private SubuserPermissionCatalog $catalog) {} + + /** + * A subuser's fields: the email address of the user to give access, who is invited when + * no account has it, and the permission keys to grant. Pass the keys that can be granted + * to hold each permission to them. + * + * @param list|null $grantable + * @return NormalizedValidationRules + */ + public static function rules(?array $grantable = null): array + { + return [ + 'email' => ['required', 'email:strict', 'between:1,191', new UserEmail], + 'permissions' => ['required', 'array'], + 'permissions.*' => $grantable === null ? ['string'] : ['string', Rule::in($grantable)], + ]; + } + + /** + * Validates subuser input and returns the email address and the permissions it + * describes, each permission one of the grantable keys. + * + * @param ActionInput $input + * @param list $grantable + * @return array{email: string, permissions: list} + */ + public static function attributes(array $input, array $grantable): array + { + $input = Validator::make($input, self::rules($grantable))->safe(); + + return [ + 'email' => $input->string('email')->toString(), + 'permissions' => array_map(fn (int|string $key): string => $input->string('permissions.'.$key)->toString(), array_keys($input->array('permissions'))), + ]; + } + + /** + * Validates permission keys under `permissions` and returns them, each one of the + * grantable keys. + * + * @param list $permissions + * @param list $grantable + * @return list + */ + public static function permissions(array $permissions, array $grantable): array + { + $rules = ValidationRuleSubset::select(self::rules($grantable), ['permissions', 'permissions.*']); + $input = Validator::make(['permissions' => $permissions], $rules)->safe(); + + return array_map(fn (int|string $key): string => $input->string('permissions.'.$key)->toString(), array_keys($input->array('permissions'))); + } /** * Creates a new user on the system and assigns them access to the provided server. @@ -33,9 +89,11 @@ final readonly class CreateSubuser implements CreatesSubusers */ public function create(Server $server, string $email, array $permissions): Subuser { - return DB::transaction(function () use ($server, $email, $permissions): Subuser { + $attributes = self::attributes(['email' => $email, 'permissions' => $permissions], $this->catalog->keys()); + + return DB::transaction(function () use ($server, $attributes): Subuser { $server = $server->newQuery()->whereKey($server->getKey())->lockForUpdate()->firstOrFail(); - $user = User::query()->where('email', $email)->first() ?? $this->createUser($email); + $user = User::query()->where('email', $attributes['email'])->first() ?? $this->createUser($attributes['email']); throw_if($server->owner_id === $user->id, UserIsServerOwnerException::class, trans('exceptions.subusers.user_is_owner')); throw_if($server->subusers()->where('user_id', $user->id)->exists(), ServerSubuserExistsException::class, trans('exceptions.subusers.subuser_exists')); @@ -43,7 +101,7 @@ final readonly class CreateSubuser implements CreatesSubusers return Subuser::query()->create([ 'user_id' => $user->id, 'server_id' => $server->id, - 'permissions' => array_values(array_unique($permissions)), + 'permissions' => array_values(array_unique($attributes['permissions'])), ])->setRelation('user', $user); }); } diff --git a/app/Actions/Subusers/UpdateSubuser.php b/app/Actions/Subusers/UpdateSubuser.php index 04e537601..672eb9995 100644 --- a/app/Actions/Subusers/UpdateSubuser.php +++ b/app/Actions/Subusers/UpdateSubuser.php @@ -10,10 +10,13 @@ use Pterodactyl\Contracts\Subusers\UpdatesSubusers; use Pterodactyl\Jobs\RevokeSftpAccessJob; use Pterodactyl\Models\Server; use Pterodactyl\Models\Subuser; +use Pterodactyl\Services\Servers\SubuserPermissionCatalog; use Throwable; final readonly class UpdateSubuser implements UpdatesSubusers { + public function __construct(private SubuserPermissionCatalog $catalog) {} + /** * Replaces the subuser's permissions and revokes their outstanding SFTP sessions on Wings. * @@ -23,6 +26,10 @@ final readonly class UpdateSubuser implements UpdatesSubusers */ public function update(Server $server, Subuser $subuser, array $permissions): Subuser { + // A permission the subuser already holds stays grantable even once nothing defines + // it, such as one of a disabled extension, so a caller can hand it back unchanged. + $permissions = CreateSubuser::permissions($permissions, [...$this->catalog->keys(), ...$subuser->permissions]); + return DB::transaction(function () use ($server, $subuser, $permissions): Subuser { $subuser->update(['permissions' => $permissions]); diff --git a/app/Contracts/Subusers/CreatesSubusers.php b/app/Contracts/Subusers/CreatesSubusers.php index f901e4a03..13d73ce1a 100644 --- a/app/Contracts/Subusers/CreatesSubusers.php +++ b/app/Contracts/Subusers/CreatesSubusers.php @@ -17,6 +17,10 @@ interface CreatesSubusers * If the email address already belongs to a user on the system a new user will not * be created. * + * The email address and the permissions are validated here, so they can come straight + * from any caller: each permission must be one the panel or an enabled extension + * defines. Whether the caller may grant them is left to the caller. + * * @param list $permissions The permission keys to grant, deduplicated * before they are stored. * diff --git a/app/Contracts/Subusers/UpdatesSubusers.php b/app/Contracts/Subusers/UpdatesSubusers.php index 2eda32c12..1594b74fe 100644 --- a/app/Contracts/Subusers/UpdatesSubusers.php +++ b/app/Contracts/Subusers/UpdatesSubusers.php @@ -13,6 +13,10 @@ interface UpdatesSubusers /** * Replaces the subuser's permissions and revokes their outstanding SFTP sessions on Wings. * + * The permissions are validated here, so they can come straight from any caller: each + * must be one the panel or an enabled extension defines, or one the subuser already + * holds. Whether the caller may grant them is left to the caller. + * * @param list $permissions * * @throws Throwable diff --git a/app/Http/Requests/Api/Client/Servers/Subusers/StoreSubuserRequest.php b/app/Http/Requests/Api/Client/Servers/Subusers/StoreSubuserRequest.php index 96da97c44..0137eaf9a 100644 --- a/app/Http/Requests/Api/Client/Servers/Subusers/StoreSubuserRequest.php +++ b/app/Http/Requests/Api/Client/Servers/Subusers/StoreSubuserRequest.php @@ -4,8 +4,8 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Client\Servers\Subusers; +use Pterodactyl\Actions\Subusers\CreateSubuser; use Pterodactyl\Enum\Permissions; -use Pterodactyl\Rules\UserEmail; class StoreSubuserRequest extends SubuserRequest { @@ -19,10 +19,6 @@ class StoreSubuserRequest extends SubuserRequest */ public function rules(): array { - return [ - 'email' => ['required', 'email:strict', 'between:1,191', new UserEmail], - 'permissions' => ['required', 'array'], - 'permissions.*' => ['string'], - ]; + return CreateSubuser::rules(); } } diff --git a/app/Http/Requests/Api/Client/Servers/Subusers/SubuserRequest.php b/app/Http/Requests/Api/Client/Servers/Subusers/SubuserRequest.php index c42d1a8e0..3611aa5cb 100644 --- a/app/Http/Requests/Api/Client/Servers/Subusers/SubuserRequest.php +++ b/app/Http/Requests/Api/Client/Servers/Subusers/SubuserRequest.php @@ -62,7 +62,8 @@ abstract class SubuserRequest extends ClientApiRequest implements ClientPermissi /** * The permissions to store for the subuser: the submitted keys the panel or an enabled - * extension knows about, always including websocket access. + * extension knows about, always including websocket access. The API drops any other key + * it is sent, where the action would refuse it. * * @return list */ diff --git a/app/Http/Requests/Api/Client/Servers/Subusers/UpdateSubuserRequest.php b/app/Http/Requests/Api/Client/Servers/Subusers/UpdateSubuserRequest.php index 153539de3..0a833bab9 100644 --- a/app/Http/Requests/Api/Client/Servers/Subusers/UpdateSubuserRequest.php +++ b/app/Http/Requests/Api/Client/Servers/Subusers/UpdateSubuserRequest.php @@ -5,7 +5,9 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Client\Servers\Subusers; use Illuminate\Contracts\Container\BindingResolutionException; +use Pterodactyl\Actions\Subusers\CreateSubuser; use Pterodactyl\Enum\Permissions; +use Pterodactyl\Support\ValidationRuleSubset; class UpdateSubuserRequest extends SubuserRequest { @@ -19,10 +21,7 @@ class UpdateSubuserRequest extends SubuserRequest */ public function rules(): array { - return [ - 'permissions' => ['required', 'array'], - 'permissions.*' => ['string'], - ]; + return ValidationRuleSubset::select(CreateSubuser::rules(), ['permissions', 'permissions.*']); } /** diff --git a/tests/Integration/Actions/Subusers/CreateSubuserTest.php b/tests/Integration/Actions/Subusers/CreateSubuserTest.php new file mode 100644 index 000000000..3470e2ec3 --- /dev/null +++ b/tests/Integration/Actions/Subusers/CreateSubuserTest.php @@ -0,0 +1,80 @@ +app->make(ExtensionPermissionRegistry::class)->register('issue-probe', 'Control the probe.', ['view' => 'View the probe.']); +}); + +test('subusers created without the http api meet the same rules', function (string $email, array $permissions, string $field): void { + $server = $this->createServerModel(); + $users = User::query()->count(); + + try { + $this->app->make(CreatesSubusers::class)->create($server, $email, $permissions); + $this->fail('The subuser was created.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect($server->subusers()->exists())->toBeFalse() + ->and(User::query()->count())->toBe($users); +})->with([ + 'a blank email' => ['', ['control.start'], 'email'], + 'a malformed email' => ['not-an-email', ['control.start'], 'email'], + 'an email starting with a dash' => ['-direct@example.com', ['control.start'], 'email'], + 'an email that is too long' => [str_repeat('a', 64).'@'.str_repeat('b', 63).'.'.str_repeat('c', 63).'.com', ['control.start'], 'email'], + 'no permissions' => ['direct@example.com', [], 'permissions'], + 'a permission that is not a string' => ['direct@example.com', [5], 'permissions.0'], + 'a permission nothing defines' => ['direct@example.com', ['control.start', 'power.fake'], 'permissions.1'], + 'a permission of an extension that is not registered' => ['direct@example.com', ['ext.unregistered.view'], 'permissions.0'], +]); + +test('a subuser gets the permissions it is given once, extension permissions included', function (): void { + $server = $this->createServerModel(); + + $subuser = $this->app->make(CreatesSubusers::class)->create($server, 'probe@example.com', ['control.start', 'ext.issue-probe.view', 'control.start']); + + expect($subuser->user->wasRecentlyCreated)->toBeTrue() + ->and($subuser->user->email)->toBe('probe@example.com') + ->and($subuser->refresh()->permissions)->toBe(['control.start', 'ext.issue-probe.view']); +}); + +test('an existing user is given access rather than invited', function (): void { + $server = $this->createServerModel(); + $existing = User::factory()->create(); + $users = User::query()->count(); + + $subuser = $this->app->make(CreatesSubusers::class)->create($server, $existing->email, ['control.console']); + + expect($subuser->user->is($existing))->toBeTrue() + ->and($subuser->user->wasRecentlyCreated)->toBeFalse() + ->and(User::query()->count())->toBe($users); +}); + +test('the owner and an existing subuser cannot be added again', function (): void { + $server = $this->createServerModel(); + $subusers = $this->app->make(CreatesSubusers::class); + $subuser = $subusers->create($server, 'twice@example.com', ['control.start']); + + expect(fn () => $subusers->create($server, 'twice@example.com', ['control.stop']))->toThrow(ServerSubuserExistsException::class) + ->and(fn () => $subusers->create($server, $server->user->email, ['control.start']))->toThrow(UserIsServerOwnerException::class) + ->and(Subuser::query()->where('server_id', $server->id)->count())->toBe(1) + ->and($subuser->refresh()->permissions)->toBe(['control.start']); +}); diff --git a/tests/Integration/Actions/Subusers/UpdateSubuserTest.php b/tests/Integration/Actions/Subusers/UpdateSubuserTest.php new file mode 100644 index 000000000..41819b2dc --- /dev/null +++ b/tests/Integration/Actions/Subusers/UpdateSubuserTest.php @@ -0,0 +1,64 @@ +app->make(ExtensionPermissionRegistry::class)->register('issue-probe', 'Control the probe.', ['view' => 'View the probe.']); +}); + +test('permissions updated without the http api meet the same rules', function (array $permissions, string $field): void { + $server = $this->createServerModel(); + $subuser = Subuser::factory()->for($server)->for(User::factory()->create())->create(['permissions' => ['control.start']]); + + try { + $this->app->make(UpdatesSubusers::class)->update($server, $subuser, $permissions); + $this->fail('The subuser was updated.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect($subuser->refresh()->permissions)->toBe(['control.start']); + Bus::assertNotDispatched(RevokeSftpAccessJob::class); +})->with([ + 'no permissions' => [[], 'permissions'], + 'a permission that is not a string' => [['control.start', ['control.stop']], 'permissions.1'], + 'a permission nothing defines' => [['power.fake'], 'permissions.0'], + 'a permission of an extension that is not registered' => [['control.start', 'ext.unregistered.view'], 'permissions.1'], +]); + +test('the permissions are replaced and the subuser loses its sftp sessions', function (): void { + $server = $this->createServerModel(); + $subuser = Subuser::factory()->for($server)->for(User::factory()->create())->create(['permissions' => ['control.start']]); + + $this->app->make(UpdatesSubusers::class)->update($server, $subuser, ['control.stop', 'ext.issue-probe.view']); + + expect($subuser->refresh()->permissions)->toBe(['control.stop', 'ext.issue-probe.view']); + Bus::assertDispatched(RevokeSftpAccessJob::class, fn (RevokeSftpAccessJob $job): bool => $job->user === $subuser->user->uuid && $job->target->is($server)); +}); + +test('a permission the subuser already holds can be kept once nothing defines it', function (): void { + $server = $this->createServerModel(); + $subuser = Subuser::factory()->for($server)->for(User::factory()->create())->create(['permissions' => ['control.start', 'ext.disabled.view']]); + $subusers = $this->app->make(UpdatesSubusers::class); + + $subusers->update($server, $subuser, ['control.stop', 'ext.disabled.view']); + expect($subuser->refresh()->permissions)->toBe(['control.stop', 'ext.disabled.view']); + + expect(fn () => $subusers->update($server, $subuser, ['control.stop', 'ext.disabled.view', 'ext.other.view']))->toThrow(ValidationException::class); + expect($subuser->refresh()->permissions)->toBe(['control.stop', 'ext.disabled.view']); +}); diff --git a/tests/Integration/Api/Client/Server/Subuser/UpdateSubuserTest.php b/tests/Integration/Api/Client/Server/Subuser/UpdateSubuserTest.php index 12bad5ce3..c76af389e 100644 --- a/tests/Integration/Api/Client/Server/Subuser/UpdateSubuserTest.php +++ b/tests/Integration/Api/Client/Server/Subuser/UpdateSubuserTest.php @@ -74,6 +74,24 @@ test('subuser cannot strip permissions from a subuser that they do not hold them Permissions::WebsocketConnect->value, ]); }); +test('a permission nothing defines any more is kept when the editor does not hold it', function () { + Bus::fake([RevokeSftpAccessJob::class]); + [$user, $server] = $this->generateTestAccount([Permissions::UserUpdate->value, Permissions::ControlStart->value]); + /** @var Subuser $subuser */ + $subuser = Subuser::factory()->for(User::factory()->create())->for($server)->create(['permissions' => [ + Permissions::ControlStart->value, + 'ext.disabled.view', + ]]); + + $this->actingAs($user)->postJson("/api/client/servers/{$server->uuid}/users/{$subuser->user->uuid}", ['permissions' => ['power.fake']])->assertForbidden(); + $this->actingAs($user)->postJson("/api/client/servers/{$server->uuid}/users/{$subuser->user->uuid}", ['permissions' => []])->assertUnprocessable(); + $this->actingAs($user)->postJson("/api/client/servers/{$server->uuid}/users/{$subuser->user->uuid}", ['permissions' => ['ext.disabled.view']])->assertOk(); + + expect($subuser->refresh()->permissions)->toEqualCanonicalizing([ + 'ext.disabled.view', + Permissions::WebsocketConnect->value, + ]); +}); test('subuser can change the permissions they hold while preserving the ones they do not', function () { Bus::fake([RevokeSftpAccessJob::class]); [$user, $server] = $this->generateTestAccount([Permissions::UserUpdate->value, Permissions::ControlStart->value, Permissions::ControlStop->value]);