mirror of
https://github.com/pterodactyl/panel.git
synced 2026-12-04 21:35:47 -05:00
subuser actions
This commit is contained in:
@@ -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<string>|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<string> $grantable
|
||||
* @return array{email: string, permissions: list<string>}
|
||||
*/
|
||||
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<string> $permissions
|
||||
* @param list<string> $grantable
|
||||
* @return list<string>
|
||||
*/
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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]);
|
||||
|
||||
|
||||
@@ -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<string> $permissions The permission keys to grant, deduplicated
|
||||
* before they are stored.
|
||||
*
|
||||
|
||||
@@ -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<string> $permissions
|
||||
*
|
||||
* @throws Throwable
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<string>
|
||||
*/
|
||||
|
||||
@@ -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.*']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Tests\Pest\Integration\Actions\Subusers\CreateSubuserTest;
|
||||
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Pterodactyl\Contracts\Subusers\CreatesSubusers;
|
||||
use Pterodactyl\Exceptions\Service\Subuser\ServerSubuserExistsException;
|
||||
use Pterodactyl\Exceptions\Service\Subuser\UserIsServerOwnerException;
|
||||
use Pterodactyl\Models\Subuser;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Services\Extensions\ExtensionPermissionRegistry;
|
||||
use Pterodactyl\Tests\Integration\IntegrationTestCase;
|
||||
|
||||
uses(IntegrationTestCase::class, DatabaseTransactions::class);
|
||||
|
||||
beforeEach(function (): void {
|
||||
Notification::fake();
|
||||
$this->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']);
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Tests\Pest\Integration\Actions\Subusers\UpdateSubuserTest;
|
||||
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Pterodactyl\Contracts\Subusers\UpdatesSubusers;
|
||||
use Pterodactyl\Jobs\RevokeSftpAccessJob;
|
||||
use Pterodactyl\Models\Subuser;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Services\Extensions\ExtensionPermissionRegistry;
|
||||
use Pterodactyl\Tests\Integration\IntegrationTestCase;
|
||||
|
||||
uses(IntegrationTestCase::class, DatabaseTransactions::class);
|
||||
|
||||
beforeEach(function (): void {
|
||||
Bus::fake([RevokeSftpAccessJob::class]);
|
||||
$this->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']);
|
||||
});
|
||||
@@ -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]);
|
||||
|
||||
Reference in New Issue
Block a user