diff --git a/app/Actions/Allocations/AssignAllocation.php b/app/Actions/Allocations/AssignAllocation.php index 45b6bc330..1add5295a 100644 --- a/app/Actions/Allocations/AssignAllocation.php +++ b/app/Actions/Allocations/AssignAllocation.php @@ -25,7 +25,7 @@ final readonly class AssignAllocation implements AssignsAllocations return DB::transaction(function () use ($server): Allocation { throw_if($server->allocations()->lockForUpdate()->count() >= $server->allocation_limit, DisplayException::class, 'Cannot assign additional allocations to this server: limit has been reached.'); - return $this->assignable->assignAvailable($server)->refresh(); + return $this->assignable->assignAvailable($server); }); } } diff --git a/app/Actions/Allocations/AssignAvailableAllocation.php b/app/Actions/Allocations/AssignAvailableAllocation.php index 649ef797b..5f03dceb9 100644 --- a/app/Actions/Allocations/AssignAvailableAllocation.php +++ b/app/Actions/Allocations/AssignAvailableAllocation.php @@ -44,6 +44,6 @@ final readonly class AssignAvailableAllocation implements AssignsAvailableAlloca $allocation->update(['server_id' => $server->id]); - return $allocation->refresh(); + return $allocation; } } diff --git a/app/Actions/Allocations/SetPrimaryAllocation.php b/app/Actions/Allocations/SetPrimaryAllocation.php index 7846b5c49..7e817ff4a 100644 --- a/app/Actions/Allocations/SetPrimaryAllocation.php +++ b/app/Actions/Allocations/SetPrimaryAllocation.php @@ -14,6 +14,7 @@ final class SetPrimaryAllocation implements SetsPrimaryAllocations { $server->update(['allocation_id' => $allocation->id]); - return $allocation->refresh(); + // The allocation row is unchanged, but a loaded server relation still holds the old primary. + return $allocation->unsetRelation('server'); } } diff --git a/app/Actions/Allocations/UpdateAllocation.php b/app/Actions/Allocations/UpdateAllocation.php index e04b0537f..4724b3a44 100644 --- a/app/Actions/Allocations/UpdateAllocation.php +++ b/app/Actions/Allocations/UpdateAllocation.php @@ -15,6 +15,6 @@ final class UpdateAllocation implements UpdatesAllocations 'ip_alias' => empty($alias) ? null : $alias, ])->saveOrFail(); - return $allocation->refresh(); + return $allocation; } } diff --git a/app/Actions/Allocations/UpdateAllocationNotes.php b/app/Actions/Allocations/UpdateAllocationNotes.php index 756d3cace..6cd630af6 100644 --- a/app/Actions/Allocations/UpdateAllocationNotes.php +++ b/app/Actions/Allocations/UpdateAllocationNotes.php @@ -13,6 +13,6 @@ final class UpdateAllocationNotes implements UpdatesAllocationNotes { $allocation->forceFill(['notes' => $notes])->save(); - return $allocation->refresh(); + return $allocation; } } diff --git a/app/Actions/Api/DeleteApiKey.php b/app/Actions/Api/DeleteApiKey.php new file mode 100644 index 000000000..45a65b31f --- /dev/null +++ b/app/Actions/Api/DeleteApiKey.php @@ -0,0 +1,16 @@ +delete(); + } +} diff --git a/app/Actions/Api/UpdateApiKey.php b/app/Actions/Api/UpdateApiKey.php new file mode 100644 index 000000000..62b1f5a69 --- /dev/null +++ b/app/Actions/Api/UpdateApiKey.php @@ -0,0 +1,28 @@ + $permissions The r_* ACL columns, only applied to application keys. + */ + public function update(ApiKey $key, array $data, array $permissions = []): ApiKey + { + if ($key->key_type === ApiKey::TYPE_APPLICATION) { + $data = array_merge($data, $permissions); + } + + $key->forceFill($data)->saveOrFail(); + + return $key; + } +} diff --git a/app/Actions/Backups/InitiateBackup.php b/app/Actions/Backups/InitiateBackup.php index b402d16ef..82e922867 100644 --- a/app/Actions/Backups/InitiateBackup.php +++ b/app/Actions/Backups/InitiateBackup.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Backups; use Carbon\CarbonImmutable; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\DB; use Pterodactyl\Contracts\Backups\DeletesBackups; use Pterodactyl\Contracts\Backups\InitiatesBackups; @@ -60,13 +61,18 @@ final class InitiateBackup implements InitiatesBackups /** * Initiates the backup process for a server on Wings. * + * The rows are written in a transaction, but Wings is only asked to start the backup + * once that transaction commits, and backups rotated out to make room are deleted only + * after Wings accepted the new one. A rejected backup is marked failed and nothing is + * rotated out, so the oldest backup survives a failed attempt. + * * @throws Throwable * @throws TooManyBackupsException * @throws TooManyRequestsHttpException */ public function initiate(Server $server, ?string $name = null, bool $override = false): Backup { - return DB::transaction(function () use ($server, $name, $override): Backup { + [$backup, $rotated] = DB::transaction(/** @return array{Backup, Collection} */ function () use ($server, $name, $override): array { $limit = JsonValueGuard::integer(config('backups.throttles.limit')); $period = JsonValueGuard::integer(config('backups.throttles.period')); if ($period > 0) { @@ -90,22 +96,28 @@ final class InitiateBackup implements InitiatesBackups } } - $successful = $server->backups()->nonFailed(); - if (! $server->backup_limit || $successful->lockForUpdate()->count() >= $server->backup_limit) { + $rotated = new Collection; + $count = $server->backups()->nonFailed()->lockForUpdate()->count(); + if (! $server->backup_limit || $count >= $server->backup_limit) { // Do not allow the user to continue if this server is already at its limit and can't override. if (! $override || $server->backup_limit <= 0) { throw new TooManyBackupsException($server->backup_limit); } - // Get the oldest backup the server has that is not "locked" (indicating a backup that should - // never be automatically purged). If we find a backup we will delete it and then continue with - // this process. If no backup is found that can be used an exception is thrown. - $oldest = $successful->where('is_locked', false)->orderBy('created_at')->first(); - if (! $oldest) { + // Pick the oldest backups that are not "locked" (indicating a backup that should never + // be automatically purged) to make room for this one. A backup rotated out by another + // request that has not finished deleting it still counts here, so take enough to bring + // the server back to its limit. They are deleted once Wings accepts the new backup. + $needed = $count - $server->backup_limit + 1; + $rotated = $server->backups() + ->nonFailed() + ->where('is_locked', false) + ->orderBy('created_at') + ->limit($needed) + ->get(); + if ($rotated->count() < $needed) { throw new TooManyBackupsException($server->backup_limit); } - - $this->deleteBackup->delete($oldest); } $backup = $server->backups()->create([ @@ -116,9 +128,38 @@ final class InitiateBackup implements InitiatesBackups 'is_locked' => $this->isLocked, ]); - Daemon::server($server)->backups()->create($backup); - - return $backup->refresh(); + return [$backup, $rotated]; }); + + try { + Daemon::server($server)->backups()->create($backup); + } catch (Throwable $throwable) { + // Record the attempt as failed, the same state Wings reports for a failed backup. + $backup->forceFill([ + 'is_successful' => false, + 'is_locked' => false, + 'completed_at' => CarbonImmutable::now(), + ])->save(); + + throw $throwable; + } + + foreach ($rotated as $old) { + // Re-read the row: it may have been deleted or locked since it was picked. + $current = Backup::query()->whereKey($old->getKey())->first(); + if ($current === null) { + continue; + } + + try { + $this->deleteBackup->delete($current); + } catch (Throwable $throwable) { + // The new backup is already running, so leave the server one over its limit + // rather than failing a request Wings accepted. + report($throwable); + } + } + + return $backup->refresh(); } } diff --git a/app/Actions/Backups/RestoreBackupStatus.php b/app/Actions/Backups/RestoreBackupStatus.php index 290e4469e..1f8ec3bea 100644 --- a/app/Actions/Backups/RestoreBackupStatus.php +++ b/app/Actions/Backups/RestoreBackupStatus.php @@ -19,6 +19,6 @@ final class RestoreBackupStatus implements RestoresBackupStatuses $model->server->update(['status' => null]); - return $model->refresh(); + return $model; } } diff --git a/app/Actions/Backups/ToggleBackupLock.php b/app/Actions/Backups/ToggleBackupLock.php index 663632d5b..0bba518c7 100644 --- a/app/Actions/Backups/ToggleBackupLock.php +++ b/app/Actions/Backups/ToggleBackupLock.php @@ -13,6 +13,6 @@ final class ToggleBackupLock implements TogglesBackupLocks { $backup->update(['is_locked' => ! $backup->is_locked]); - return $backup->refresh(); + return $backup; } } diff --git a/app/Actions/Databases/CreateDatabaseHost.php b/app/Actions/Databases/CreateDatabaseHost.php index b07e823f5..2e8471614 100644 --- a/app/Actions/Databases/CreateDatabaseHost.php +++ b/app/Actions/Databases/CreateDatabaseHost.php @@ -42,6 +42,6 @@ final readonly class CreateDatabaseHost implements CreatesDatabaseHosts $host->save(); - return $host->refresh(); + return $host; } } diff --git a/app/Actions/Eggs/Variables/DeleteEggVariable.php b/app/Actions/Eggs/Variables/DeleteEggVariable.php new file mode 100644 index 000000000..4299b3783 --- /dev/null +++ b/app/Actions/Eggs/Variables/DeleteEggVariable.php @@ -0,0 +1,19 @@ +delete(); + } +} diff --git a/app/Actions/Mounts/AttachEggsToMount.php b/app/Actions/Mounts/AttachEggsToMount.php new file mode 100644 index 000000000..ec80f26c8 --- /dev/null +++ b/app/Actions/Mounts/AttachEggsToMount.php @@ -0,0 +1,21 @@ + $eggIds + */ + public function attach(Mount $mount, array $eggIds): void + { + $mount->eggs()->syncWithoutDetaching($eggIds); + } +} diff --git a/app/Actions/Mounts/AttachNodesToMount.php b/app/Actions/Mounts/AttachNodesToMount.php new file mode 100644 index 000000000..80d775f24 --- /dev/null +++ b/app/Actions/Mounts/AttachNodesToMount.php @@ -0,0 +1,21 @@ + $nodeIds + */ + public function attach(Mount $mount, array $nodeIds): void + { + $mount->nodes()->syncWithoutDetaching($nodeIds); + } +} diff --git a/app/Actions/Mounts/CreateMount.php b/app/Actions/Mounts/CreateMount.php new file mode 100644 index 000000000..9fdb02a9a --- /dev/null +++ b/app/Actions/Mounts/CreateMount.php @@ -0,0 +1,26 @@ +fill($data); + $mount->forceFill(['uuid' => Uuid::uuid4()->toString()]); + $mount->saveOrFail(); + + return $mount; + } +} diff --git a/app/Actions/Mounts/DeleteMount.php b/app/Actions/Mounts/DeleteMount.php new file mode 100644 index 000000000..7685b9e65 --- /dev/null +++ b/app/Actions/Mounts/DeleteMount.php @@ -0,0 +1,19 @@ +delete(); + } +} diff --git a/app/Actions/Mounts/DetachEggFromMount.php b/app/Actions/Mounts/DetachEggFromMount.php new file mode 100644 index 000000000..d4239bafb --- /dev/null +++ b/app/Actions/Mounts/DetachEggFromMount.php @@ -0,0 +1,20 @@ +eggs()->detach($egg->id); + } +} diff --git a/app/Actions/Mounts/DetachNodeFromMount.php b/app/Actions/Mounts/DetachNodeFromMount.php new file mode 100644 index 000000000..0d8a161d1 --- /dev/null +++ b/app/Actions/Mounts/DetachNodeFromMount.php @@ -0,0 +1,20 @@ +nodes()->detach($node->id); + } +} diff --git a/app/Actions/Mounts/UpdateMount.php b/app/Actions/Mounts/UpdateMount.php new file mode 100644 index 000000000..59e15a2e0 --- /dev/null +++ b/app/Actions/Mounts/UpdateMount.php @@ -0,0 +1,23 @@ +forceFill($data)->save(); + + return $mount; + } +} diff --git a/app/Actions/Nodes/UpdateNode.php b/app/Actions/Nodes/UpdateNode.php index d5b2327bf..49414034e 100644 --- a/app/Actions/Nodes/UpdateNode.php +++ b/app/Actions/Nodes/UpdateNode.php @@ -41,12 +41,13 @@ final readonly class UpdateNode implements UpdatesNodes $daemon = clone $node; $node->forceFill($data)->save(); - $updated = $node->refresh(); + // A location loaded before the save may no longer match location_id. + $node->unsetRelation('location'); try { - $daemon->fqdn = $updated->fqdn; + $daemon->fqdn = $node->fqdn; - Daemon::node($daemon)->update($updated); + Daemon::node($daemon)->update($node); } catch (DaemonConnectionException $daemonConnectionException) { Log::warning($daemonConnectionException->getMessage(), ['exception' => $daemonConnectionException, 'node_id' => $node->id]); @@ -58,10 +59,10 @@ final readonly class UpdateNode implements UpdatesNodes // inject their own response pages, causing this logic to get fucked up. // // @see https://github.com/pterodactyl/panel/issues/2712 - return [$updated, true]; + return [$node, true]; } - return [$updated, false]; + return [$node, false]; }); if ($exception) { diff --git a/app/Actions/Schedules/CreateScheduleTask.php b/app/Actions/Schedules/CreateScheduleTask.php index db368ab62..6ff21bd1f 100644 --- a/app/Actions/Schedules/CreateScheduleTask.php +++ b/app/Actions/Schedules/CreateScheduleTask.php @@ -47,7 +47,7 @@ final readonly class CreateScheduleTask implements CreatesScheduleTasks 'payload' => $data['payload'], 'time_offset' => $data['time_offset'], 'continue_on_failure' => $data['continue_on_failure'], - ])->refresh(); + ]); }); } } diff --git a/app/Actions/Schedules/UpdateSchedule.php b/app/Actions/Schedules/UpdateSchedule.php index a6c101b68..4ba79c3df 100644 --- a/app/Actions/Schedules/UpdateSchedule.php +++ b/app/Actions/Schedules/UpdateSchedule.php @@ -53,6 +53,6 @@ final class UpdateSchedule implements UpdatesSchedules $schedule->update($attributes); - return $schedule->refresh(); + return $schedule; } } diff --git a/app/Actions/Schedules/UpdateScheduleTask.php b/app/Actions/Schedules/UpdateScheduleTask.php index 575019517..fc50f81f9 100644 --- a/app/Actions/Schedules/UpdateScheduleTask.php +++ b/app/Actions/Schedules/UpdateScheduleTask.php @@ -48,7 +48,7 @@ final readonly class UpdateScheduleTask implements UpdatesScheduleTasks 'continue_on_failure' => $data['continue_on_failure'], ]); - return $task->refresh(); + return $task; }); } } diff --git a/app/Actions/Servers/AttachMountToServer.php b/app/Actions/Servers/AttachMountToServer.php index 6fd3a36f8..a75afa003 100644 --- a/app/Actions/Servers/AttachMountToServer.php +++ b/app/Actions/Servers/AttachMountToServer.php @@ -21,6 +21,6 @@ final class AttachMountToServer implements AttachesMountsToServers (new MountServer)->forceFill(['mount_id' => $mount->id, 'server_id' => $server->id])->saveOrFail(); - return $mount->refresh(); + return $mount; } } diff --git a/app/Actions/Servers/DeleteServer.php b/app/Actions/Servers/DeleteServer.php index 91b08a06b..c852c7257 100644 --- a/app/Actions/Servers/DeleteServer.php +++ b/app/Actions/Servers/DeleteServer.php @@ -4,7 +4,7 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Servers; -use Exception; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Http\Response; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; @@ -43,29 +43,36 @@ final class DeleteServer implements DeletesServers Daemon::server($server)->delete(); } catch (DaemonConnectionException $daemonConnectionException) { // A missing Wings record is safe to treat as already deleted. Force mode also - // tolerates other Wings and database-host cleanup failures. + // tolerates other Wings failures. throw_if(! $this->force && $daemonConnectionException->getStatusCode() !== Response::HTTP_NOT_FOUND, $daemonConnectionException); Log::warning($daemonConnectionException->getMessage(), ['exception' => $daemonConnectionException]); } - DB::transaction(function () use ($server): void { - foreach ($server->loadMissing('databases.host')->databases as $database) { - try { - $this->deleteDatabase->delete($database); - } catch (Exception $exception) { - throw_unless($this->force, $exception); - // The host entry could not be removed, so remove the Panel record and - // report the orphan for later cleanup rather than blocking server deletion. - $database->delete(); - Log::warning($exception->getMessage(), ['exception' => $exception]); - } + // The remote databases are dropped only after the Panel records are gone. Dropping + // them inside the transaction could not be undone if the deletion later rolled back. + $databases = DB::transaction(function () use ($server): Collection { + $databases = $server->loadMissing('databases.host')->databases; + foreach ($databases as $database) { + $database->delete(); } // Clear notes before releasing the allocations back to the unassigned pool. $server->allocations()->update(['notes' => null]); $server->delete(); + + return $databases; }); + foreach ($databases as $database) { + try { + $this->deleteDatabase->delete($database); + } catch (Throwable $throwable) { + // The server is already deleted, so report the orphaned database for manual + // cleanup and keep dropping the rest. + report($throwable); + } + } + // The row is gone, so only the uuid travels. Dispatched after any outer transaction commits. Event::dispatch(new OperationCompleted($server->uuid, 'delete', true, $server->uuid)); } diff --git a/app/Actions/Servers/RecordServerInstallResult.php b/app/Actions/Servers/RecordServerInstallResult.php index ddc9f4ef4..0abfb2e28 100644 --- a/app/Actions/Servers/RecordServerInstallResult.php +++ b/app/Actions/Servers/RecordServerInstallResult.php @@ -39,6 +39,6 @@ final readonly class RecordServerInstallResult implements RecordsServerInstallRe Event::dispatch(new OperationCompleted($server->uuid, $reinstall ? 'reinstall' : 'install', $successful, $server->uuid)); - return $server->refresh(); + return $server; } } diff --git a/app/Actions/Servers/ReinstallServer.php b/app/Actions/Servers/ReinstallServer.php index a69bb1601..81250f817 100644 --- a/app/Actions/Servers/ReinstallServer.php +++ b/app/Actions/Servers/ReinstallServer.php @@ -25,7 +25,7 @@ final readonly class ReinstallServer implements ReinstallsServers $server->fill(['status' => Server::STATUS_INSTALLING])->save(); Daemon::server($server)->reinstall(); - return $server->refresh(); + return $server; }); } } diff --git a/app/Actions/Servers/ToggleServerInstallStatus.php b/app/Actions/Servers/ToggleServerInstallStatus.php new file mode 100644 index 000000000..4af52f941 --- /dev/null +++ b/app/Actions/Servers/ToggleServerInstallStatus.php @@ -0,0 +1,29 @@ +status === Server::STATUS_INSTALL_FAILED) { + throw new DisplayException(trans('admin/server.exceptions.marked_as_failed')); + } + + $server->forceFill([ + 'status' => $server->isInstalled() ? Server::STATUS_INSTALLING : null, + ])->saveOrFail(); + } +} diff --git a/app/Actions/Subusers/CreateSubuser.php b/app/Actions/Subusers/CreateSubuser.php index 474b6efd2..ae2ce072d 100644 --- a/app/Actions/Subusers/CreateSubuser.php +++ b/app/Actions/Subusers/CreateSubuser.php @@ -44,7 +44,7 @@ final readonly class CreateSubuser implements CreatesSubusers 'user_id' => $user->id, 'server_id' => $server->id, 'permissions' => array_values(array_unique($permissions)), - ])->refresh()->setRelation('user', $user); + ])->setRelation('user', $user); }); } diff --git a/app/Actions/Subusers/UpdateSubuser.php b/app/Actions/Subusers/UpdateSubuser.php index 4a8f1c530..04e537601 100644 --- a/app/Actions/Subusers/UpdateSubuser.php +++ b/app/Actions/Subusers/UpdateSubuser.php @@ -29,7 +29,7 @@ final readonly class UpdateSubuser implements UpdatesSubusers $job = new RevokeSftpAccessJob($subuser->user->uuid, $server); DB::afterCommit(fn (): PendingDispatch => dispatch($job)); - return $subuser->refresh(); + return $subuser; }); } } diff --git a/app/Actions/Tags/CreateTag.php b/app/Actions/Tags/CreateTag.php new file mode 100644 index 000000000..6dd8febb7 --- /dev/null +++ b/app/Actions/Tags/CreateTag.php @@ -0,0 +1,21 @@ +create($data); + } +} diff --git a/app/Actions/Tags/DeleteTag.php b/app/Actions/Tags/DeleteTag.php new file mode 100644 index 000000000..488f0a683 --- /dev/null +++ b/app/Actions/Tags/DeleteTag.php @@ -0,0 +1,27 @@ +slug), DisplayException::class, 'Built-in game tags cannot be edited.'); + + $tag->delete(); + } +} diff --git a/app/Actions/Tags/UpdateTag.php b/app/Actions/Tags/UpdateTag.php new file mode 100644 index 000000000..e538b4bb2 --- /dev/null +++ b/app/Actions/Tags/UpdateTag.php @@ -0,0 +1,31 @@ +slug), DisplayException::class, 'Built-in game tags cannot be edited.'); + + $tag->update($data); + + return $tag; + } +} diff --git a/app/Actions/Transfers/InitiateTransfer.php b/app/Actions/Transfers/InitiateTransfer.php index ad75e1764..aab86bf46 100644 --- a/app/Actions/Transfers/InitiateTransfer.php +++ b/app/Actions/Transfers/InitiateTransfer.php @@ -6,6 +6,7 @@ namespace Pterodactyl\Actions\Transfers; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\DB; +use Pterodactyl\Contracts\Transfers\FailsTransfers; use Pterodactyl\Contracts\Transfers\InitiatesTransfers; use Pterodactyl\Enum\JwtScope; use Pterodactyl\Exceptions\DisplayException; @@ -21,11 +22,13 @@ final readonly class InitiateTransfer implements InitiatesTransfers { public function __construct( private NodeJWTService $nodeJWTService, + private FailsTransfers $failTransfer, ) {} /** * Records the transfer, reserves the target allocations, and tells the destination - * node to begin pulling the server. + * node to begin pulling the server. Wings is called after the records commit; if it + * rejects the transfer, it is marked failed and its allocations are released. * * @param list $additionalAllocations * @@ -34,7 +37,7 @@ final readonly class InitiateTransfer implements InitiatesTransfers */ public function initiate(Server $server, Node $node, int $allocationId, array $additionalAllocations): ServerTransfer { - return DB::transaction(function () use ($server, $node, $allocationId, $additionalAllocations): ServerTransfer { + $transfer = DB::transaction(function () use ($server, $node, $allocationId, $additionalAllocations): ServerTransfer { $server = $server->newQuery()->whereKey($server->getKey())->lockForUpdate()->firstOrFail(); throw_unless($node->isViable($server->memory, $server->disk), DisplayException::class, trans('admin/server.alerts.transfer_not_viable')); $server->validateTransferState(); @@ -67,6 +70,10 @@ final readonly class InitiateTransfer implements InitiatesTransfers // Assign now so another server can't claim these allocations mid-transfer. Allocation::query()->whereKey($allocationIds)->update(['server_id' => $server->id]); + return $transfer; + }); + + try { $token = $this->nodeJWTService ->setExpiresAt(CarbonImmutable::now()->addMinutes(15)) ->setSubject($server->uuid) @@ -74,8 +81,12 @@ final readonly class InitiateTransfer implements InitiatesTransfers ->handle($node, $server->uuid); Daemon::server($server)->transfer($node, $token); + } catch (Throwable $throwable) { + $this->failTransfer->fail($transfer); - return $transfer->refresh(); - }); + throw $throwable; + } + + return $transfer->refresh(); } } diff --git a/app/Actions/Users/DisableTwoFactor.php b/app/Actions/Users/DisableTwoFactor.php index cb6bd6a7c..00a7b2e46 100644 --- a/app/Actions/Users/DisableTwoFactor.php +++ b/app/Actions/Users/DisableTwoFactor.php @@ -11,9 +11,10 @@ final class DisableTwoFactor implements DisablesTwoFactor { public function disable(User $user): void { - $user->update([ - 'totp_authenticated_at' => now(), + $user->forceFill([ 'use_totp' => false, - ]); + 'totp_secret' => null, + 'totp_authenticated_at' => null, + ])->saveOrFail(); } } diff --git a/app/Actions/Users/UpdateUser.php b/app/Actions/Users/UpdateUser.php index af8a30066..e24bda29a 100644 --- a/app/Actions/Users/UpdateUser.php +++ b/app/Actions/Users/UpdateUser.php @@ -32,6 +32,6 @@ final class UpdateUser implements UpdatesUsers event(new PasswordChanged($user)); } - return $user->refresh(); + return $user; } } diff --git a/app/Contracts/Api/DeletesApiKeys.php b/app/Contracts/Api/DeletesApiKeys.php new file mode 100644 index 000000000..12686ab19 --- /dev/null +++ b/app/Contracts/Api/DeletesApiKeys.php @@ -0,0 +1,12 @@ + $permissions The r_* ACL columns, only applied to application keys. + */ + public function update(ApiKey $key, array $data, array $permissions = []): ApiKey; +} diff --git a/app/Contracts/Eggs/DeletesEggVariables.php b/app/Contracts/Eggs/DeletesEggVariables.php new file mode 100644 index 000000000..f0dacdf46 --- /dev/null +++ b/app/Contracts/Eggs/DeletesEggVariables.php @@ -0,0 +1,15 @@ + $eggIds + */ + public function attach(Mount $mount, array $eggIds): void; +} diff --git a/app/Contracts/Mounts/AttachesNodesToMounts.php b/app/Contracts/Mounts/AttachesNodesToMounts.php new file mode 100644 index 000000000..8b33628ba --- /dev/null +++ b/app/Contracts/Mounts/AttachesNodesToMounts.php @@ -0,0 +1,17 @@ + $nodeIds + */ + public function attach(Mount $mount, array $nodeIds): void; +} diff --git a/app/Contracts/Mounts/CreatesMounts.php b/app/Contracts/Mounts/CreatesMounts.php new file mode 100644 index 000000000..869cb1721 --- /dev/null +++ b/app/Contracts/Mounts/CreatesMounts.php @@ -0,0 +1,17 @@ +where('key_type', ApiKey::TYPE_APPLICATION) ->where('identifier', $identifier) ->firstOrFail(); - $key->forceFill(array_merge( - ['memo' => $request->validated('memo')], - $request->getKeyPermissions() - ))->saveOrFail(); + $key = $keyUpdater->update($key, ['memo' => JsonValueGuard::nullableString($request->validated('memo'))], $request->getKeyPermissions()); $key->load('user'); Activity::event('admin:api-key.update') @@ -136,7 +135,7 @@ class ApiKeyController extends AdminApiController */ #[Endpoint('Delete API key', 'Deletes an application API key by identifier.')] #[ScribeResponse(status: 204, description: 'API key deleted.')] - public function destroy(DeleteApiKeyRequest $request, string $identifier): Response + public function destroy(DeleteApiKeyRequest $request, DeletesApiKeys $keyDeleter, string $identifier): Response { $key = ApiKey::query() ->where('key_type', ApiKey::TYPE_APPLICATION) @@ -148,7 +147,7 @@ class ApiKeyController extends AdminApiController ->property('identifier', $key->identifier) ->log(); - $key->delete(); + $keyDeleter->delete($key); return $this->returnNoContent(); } diff --git a/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php b/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php index dd9a8c061..75b4d6174 100644 --- a/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php +++ b/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php @@ -13,6 +13,7 @@ use Knuckles\Scribe\Attributes\QueryParam; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; use Pterodactyl\Contracts\Eggs\CreatesEggVariables; +use Pterodactyl\Contracts\Eggs\DeletesEggVariables; use Pterodactyl\Contracts\Eggs\UpdatesEggVariables; use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer; use Pterodactyl\Facades\Activity; @@ -94,9 +95,9 @@ class EggVariableController extends AdminApiController */ #[Endpoint('Delete egg variable', 'Deletes a startup variable from an egg.')] #[ScribeResponse(status: 204, description: 'Egg variable deleted.')] - public function destroy(DeleteVariableRequest $request, Egg $egg, EggVariable $variable): Response + public function destroy(DeleteVariableRequest $request, DeletesEggVariables $variables, Egg $egg, EggVariable $variable): Response { - $variable->delete(); + $variables->delete($variable); Activity::event('admin:egg-variable.delete') ->subject($egg, $variable) diff --git a/app/Http/Controllers/Api/Admin/Mounts/AttachEggsController.php b/app/Http/Controllers/Api/Admin/Mounts/AttachEggsController.php index ba416d6e6..67d0512b6 100644 --- a/app/Http/Controllers/Api/Admin/Mounts/AttachEggsController.php +++ b/app/Http/Controllers/Api/Admin/Mounts/AttachEggsController.php @@ -8,6 +8,7 @@ use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\QueryParam; use Knuckles\Scribe\Attributes\Subgroup; +use Pterodactyl\Contracts\Mounts\AttachesEggsToMounts; use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer; use Pterodactyl\Facades\Activity; use Pterodactyl\Facades\Fractal; @@ -28,11 +29,11 @@ class AttachEggsController extends AdminApiController #[Endpoint('Attach eggs to mount', 'Attaches one or more eggs to a mount definition without removing existing egg attachments.')] #[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "eggs", "nodes", and "servers".', required: false, example: 'eggs,nodes', enum: ['eggs', 'nodes', 'servers', 'eggs,nodes', 'eggs,nodes,servers'])] #[ResponseFromTransformer(MountTransformer::class, Mount::class, description: 'Mount updated.', resourceKey: 'mount')] - public function __invoke(AttachEggsRequest $request, Mount $mount): array + public function __invoke(AttachEggsRequest $request, AttachesEggsToMounts $attacher, Mount $mount): array { $eggs = $request->eggs(); - $mount->eggs()->syncWithoutDetaching($eggs); + $attacher->attach($mount, $eggs); Activity::event('admin:mount.attach-egg') ->subject($mount) diff --git a/app/Http/Controllers/Api/Admin/Mounts/AttachNodesController.php b/app/Http/Controllers/Api/Admin/Mounts/AttachNodesController.php index 53410be51..48524a1cc 100644 --- a/app/Http/Controllers/Api/Admin/Mounts/AttachNodesController.php +++ b/app/Http/Controllers/Api/Admin/Mounts/AttachNodesController.php @@ -8,6 +8,7 @@ use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\QueryParam; use Knuckles\Scribe\Attributes\Subgroup; +use Pterodactyl\Contracts\Mounts\AttachesNodesToMounts; use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer; use Pterodactyl\Facades\Activity; use Pterodactyl\Facades\Fractal; @@ -28,11 +29,11 @@ class AttachNodesController extends AdminApiController #[Endpoint('Attach nodes to mount', 'Attaches one or more nodes to a mount definition without removing existing node attachments.')] #[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "eggs", "nodes", and "servers".', required: false, example: 'eggs,nodes', enum: ['eggs', 'nodes', 'servers', 'eggs,nodes', 'eggs,nodes,servers'])] #[ResponseFromTransformer(MountTransformer::class, Mount::class, description: 'Mount updated.', resourceKey: 'mount')] - public function __invoke(AttachNodesRequest $request, Mount $mount): array + public function __invoke(AttachNodesRequest $request, AttachesNodesToMounts $attacher, Mount $mount): array { $nodes = $request->nodes(); - $mount->nodes()->syncWithoutDetaching($nodes); + $attacher->attach($mount, $nodes); Activity::event('admin:mount.attach-node') ->subject($mount) diff --git a/app/Http/Controllers/Api/Admin/Mounts/DetachEggController.php b/app/Http/Controllers/Api/Admin/Mounts/DetachEggController.php index a7689ee1b..28f5501d7 100644 --- a/app/Http/Controllers/Api/Admin/Mounts/DetachEggController.php +++ b/app/Http/Controllers/Api/Admin/Mounts/DetachEggController.php @@ -9,6 +9,7 @@ use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; +use Pterodactyl\Contracts\Mounts\DetachesEggsFromMounts; use Pterodactyl\Facades\Activity; use Pterodactyl\Http\Controllers\Api\Admin\AdminApiController; use Pterodactyl\Http\Requests\Api\Admin\Mounts\DetachEggRequest; @@ -24,9 +25,9 @@ class DetachEggController extends AdminApiController */ #[Endpoint('Detach egg from mount', 'Removes a single egg attachment from a mount definition.')] #[ScribeResponse(status: 204, description: 'Egg detached from mount.')] - public function __invoke(DetachEggRequest $request, Mount $mount, Egg $egg): Response + public function __invoke(DetachEggRequest $request, DetachesEggsFromMounts $detacher, Mount $mount, Egg $egg): Response { - $mount->eggs()->detach($egg->id); + $detacher->detach($mount, $egg); Activity::event('admin:mount.detach-egg') ->subject($mount) diff --git a/app/Http/Controllers/Api/Admin/Mounts/DetachNodeController.php b/app/Http/Controllers/Api/Admin/Mounts/DetachNodeController.php index 06f544d01..5ddc9d081 100644 --- a/app/Http/Controllers/Api/Admin/Mounts/DetachNodeController.php +++ b/app/Http/Controllers/Api/Admin/Mounts/DetachNodeController.php @@ -9,6 +9,7 @@ use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; +use Pterodactyl\Contracts\Mounts\DetachesNodesFromMounts; use Pterodactyl\Facades\Activity; use Pterodactyl\Http\Controllers\Api\Admin\AdminApiController; use Pterodactyl\Http\Requests\Api\Admin\Mounts\DetachNodeRequest; @@ -24,9 +25,9 @@ class DetachNodeController extends AdminApiController */ #[Endpoint('Detach node from mount', 'Removes a single node attachment from a mount definition.')] #[ScribeResponse(status: 204, description: 'Node detached from mount.')] - public function __invoke(DetachNodeRequest $request, Mount $mount, Node $node): Response + public function __invoke(DetachNodeRequest $request, DetachesNodesFromMounts $detacher, Mount $mount, Node $node): Response { - $mount->nodes()->detach($node->id); + $detacher->detach($mount, $node); Activity::event('admin:mount.detach-node') ->subject($mount) diff --git a/app/Http/Controllers/Api/Admin/Mounts/MountController.php b/app/Http/Controllers/Api/Admin/Mounts/MountController.php index 36112811f..af689b688 100644 --- a/app/Http/Controllers/Api/Admin/Mounts/MountController.php +++ b/app/Http/Controllers/Api/Admin/Mounts/MountController.php @@ -12,6 +12,9 @@ use Knuckles\Scribe\Attributes\QueryParam; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; use League\Fractal\Pagination\IlluminatePaginatorAdapter; +use Pterodactyl\Contracts\Mounts\CreatesMounts; +use Pterodactyl\Contracts\Mounts\DeletesMounts; +use Pterodactyl\Contracts\Mounts\UpdatesMounts; use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer; use Pterodactyl\Facades\Activity; use Pterodactyl\Facades\Fractal; @@ -23,7 +26,6 @@ use Pterodactyl\Http\Requests\Api\Admin\Mounts\StoreMountRequest; use Pterodactyl\Http\Requests\Api\Admin\Mounts\UpdateMountRequest; use Pterodactyl\Models\Mount; use Pterodactyl\Transformers\Api\Admin\MountTransformer; -use Ramsey\Uuid\Uuid; use Spatie\QueryBuilder\QueryBuilder; #[Group('Admin API', 'Root administrator endpoints for managing panel configuration and resources.')] @@ -93,11 +95,9 @@ class MountController extends AdminApiController */ #[Endpoint('Create mount', 'Creates a mount definition and generates its UUID.')] #[ResponseFromTransformer(MountTransformer::class, Mount::class, status: 201, description: 'Mount created.', resourceKey: 'mount', meta: ['resource' => 'https://panel.example.com/api/admin/mounts/1'])] - public function store(StoreMountRequest $request): JsonResponse + public function store(StoreMountRequest $request, CreatesMounts $mounts): JsonResponse { - $mount = (new Mount)->fill($request->validated()); - $mount->forceFill(['uuid' => Uuid::uuid4()->toString()]); - $mount->saveOrFail(); + $mount = $mounts->create($request->payload()); Activity::event('admin:mount.create') ->subject($mount) @@ -121,9 +121,9 @@ class MountController extends AdminApiController */ #[Endpoint('Update mount', 'Updates an existing mount definition.')] #[ResponseFromTransformer(MountTransformer::class, Mount::class, description: 'Mount updated.', resourceKey: 'mount')] - public function update(UpdateMountRequest $request, Mount $mount): array + public function update(UpdateMountRequest $request, UpdatesMounts $mounts, Mount $mount): array { - $mount->forceFill($request->validated())->save(); + $mount = $mounts->update($mount, $request->payload()); Activity::event('admin:mount.update') ->subject($mount) @@ -140,11 +140,11 @@ class MountController extends AdminApiController */ #[Endpoint('Delete mount', 'Deletes a mount definition.')] #[ScribeResponse(status: 204, description: 'Mount deleted.')] - public function destroy(DeleteMountRequest $request, Mount $mount): Response + public function destroy(DeleteMountRequest $request, DeletesMounts $mounts, Mount $mount): Response { $name = $mount->name; - $mount->delete(); + $mounts->delete($mount); Activity::event('admin:mount.delete') ->subject($mount) diff --git a/app/Http/Controllers/Api/Admin/Nodes/DeleteAllocationBlockController.php b/app/Http/Controllers/Api/Admin/Nodes/DeleteAllocationBlockController.php index 8b6866de6..220e69c2b 100644 --- a/app/Http/Controllers/Api/Admin/Nodes/DeleteAllocationBlockController.php +++ b/app/Http/Controllers/Api/Admin/Nodes/DeleteAllocationBlockController.php @@ -5,15 +5,19 @@ declare(strict_types=1); namespace Pterodactyl\Http\Controllers\Api\Admin\Nodes; use Illuminate\Http\Response; +use Illuminate\Support\Facades\DB; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; +use Pterodactyl\Contracts\Allocations\DeletesAllocations; use Pterodactyl\Facades\Activity; use Pterodactyl\Http\Controllers\Api\Admin\AdminApiController; use Pterodactyl\Http\Requests\Api\Admin\Nodes\Allocations\BlockDeleteAllocationRequest; +use Pterodactyl\Models\Allocation; use Pterodactyl\Models\Node; use Pterodactyl\Support\JsonValueGuard; +use Throwable; #[Group('Admin API', 'Root administrator endpoints for managing panel configuration and resources.')] #[Subgroup('Node Allocations', 'Create, update, retrieve, and delete node allocations.')] @@ -21,13 +25,21 @@ class DeleteAllocationBlockController extends AdminApiController { /** * Delete unassigned allocations for IP block. + * + * @throws Throwable */ #[Endpoint('Delete node allocation IP block', 'Deletes every unassigned allocation for an IP address on a node.')] #[ScribeResponse(status: 204, description: 'Unassigned allocations for the IP were deleted.')] - public function __invoke(BlockDeleteAllocationRequest $request, Node $node): Response + public function __invoke(BlockDeleteAllocationRequest $request, DeletesAllocations $deleter, Node $node): Response { $ip = JsonValueGuard::string($request->validated('ip')); - $node->allocations()->unassigned()->where('ip', $ip)->delete(); + + // Delete through the action so extension wrappers see each allocation, while + // the transaction keeps the block delete all-or-nothing like the bulk query was. + DB::transaction(function () use ($deleter, $node, $ip): void { + $node->allocations()->unassigned()->where('ip', $ip)->lockForUpdate()->get() + ->each(fn (Allocation $allocation) => $deleter->delete($allocation)); + }); Activity::event('admin:node-allocation.delete-block') ->subject($node) diff --git a/app/Http/Controllers/Api/Admin/Servers/RotateDatabasePasswordController.php b/app/Http/Controllers/Api/Admin/Servers/RotateDatabasePasswordController.php index 3a35add0a..c0bb06303 100644 --- a/app/Http/Controllers/Api/Admin/Servers/RotateDatabasePasswordController.php +++ b/app/Http/Controllers/Api/Admin/Servers/RotateDatabasePasswordController.php @@ -35,10 +35,14 @@ class RotateDatabasePasswordController extends AdminApiController throw (new ModelNotFoundException)->setModel(Database::class); } + // The action commits its own transaction around the remote user change, so the + // activity is logged afterwards instead of wrapping a change it cannot undo. + $passwordService->rotate($database); + Activity::event('admin:server-database.rotate-password') ->subject($database) ->property('name', $database->database) - ->transaction(fn (): string => $passwordService->rotate($database)); + ->log(); return Fractal::item($database->refresh()) ->parseIncludes(['password']) diff --git a/app/Http/Controllers/Api/Admin/Servers/ToggleBackupController.php b/app/Http/Controllers/Api/Admin/Servers/ToggleBackupController.php index 0a703c425..6891f8bb9 100644 --- a/app/Http/Controllers/Api/Admin/Servers/ToggleBackupController.php +++ b/app/Http/Controllers/Api/Admin/Servers/ToggleBackupController.php @@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\ModelNotFoundException; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Subgroup; +use Pterodactyl\Contracts\Backups\TogglesBackupLocks; use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer; use Pterodactyl\Facades\Activity; use Pterodactyl\Facades\Fractal; @@ -28,13 +29,13 @@ class ToggleBackupController extends AdminApiController */ #[Endpoint('Toggle server backup lock', 'Toggles whether a server backup is locked against deletion.')] #[ResponseFromTransformer(BackupTransformer::class, Backup::class, description: 'Server backup lock state toggled.', resourceKey: 'backup')] - public function __invoke(ToggleBackupRequest $request, Server $server, Backup $backup): array + public function __invoke(ToggleBackupRequest $request, TogglesBackupLocks $toggle, Server $server, Backup $backup): array { if ($backup->server_id !== $server->id) { throw (new ModelNotFoundException)->setModel(Backup::class); } - $backup->update(['is_locked' => ! $backup->is_locked]); + $backup = $toggle->toggle($backup); Activity::event('admin:server-backup.toggle-lock') ->subject($backup) diff --git a/app/Http/Controllers/Api/Admin/Servers/ToggleInstallController.php b/app/Http/Controllers/Api/Admin/Servers/ToggleInstallController.php index 905b3cfac..c5f666f3d 100644 --- a/app/Http/Controllers/Api/Admin/Servers/ToggleInstallController.php +++ b/app/Http/Controllers/Api/Admin/Servers/ToggleInstallController.php @@ -9,6 +9,7 @@ use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; +use Pterodactyl\Contracts\Servers\TogglesServerInstallStatus; use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Facades\Activity; use Pterodactyl\Http\Controllers\Api\Admin\AdminApiController; @@ -31,19 +32,15 @@ class ToggleInstallController extends AdminApiController /** * Toggle server install state. + * + * @throws DisplayException */ #[Endpoint('Toggle server install state', 'Toggles a server between installed and installing states unless it is marked as failed.')] #[ScribeResponse(status: 204, description: 'Server install state toggled.')] #[ScribeResponse(self::INSTALL_FAILED_ERROR, status: 400, description: 'The server is marked as failed.')] - public function __invoke(ToggleInstallRequest $request, Server $server): Response + public function __invoke(ToggleInstallRequest $request, TogglesServerInstallStatus $toggler, Server $server): Response { - if ($server->status === Server::STATUS_INSTALL_FAILED) { - throw new DisplayException(trans('admin/server.exceptions.marked_as_failed')); - } - - $server->forceFill([ - 'status' => $server->isInstalled() ? Server::STATUS_INSTALLING : null, - ])->saveOrFail(); + $toggler->toggle($server); Activity::event('admin:server.toggle-install') ->subject($server) diff --git a/app/Http/Controllers/Api/Admin/Tags/TagController.php b/app/Http/Controllers/Api/Admin/Tags/TagController.php index bb4f723fd..2e87d8fd6 100644 --- a/app/Http/Controllers/Api/Admin/Tags/TagController.php +++ b/app/Http/Controllers/Api/Admin/Tags/TagController.php @@ -12,8 +12,10 @@ use Knuckles\Scribe\Attributes\QueryParam; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; use League\Fractal\Pagination\IlluminatePaginatorAdapter; +use Pterodactyl\Contracts\Tags\CreatesTags; +use Pterodactyl\Contracts\Tags\DeletesTags; use Pterodactyl\Contracts\Tags\SyncsTags; -use Pterodactyl\Enum\EggSpecificTags; +use Pterodactyl\Contracts\Tags\UpdatesTags; use Pterodactyl\Exceptions\DisplayException; use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer; use Pterodactyl\Facades\Activity; @@ -93,9 +95,9 @@ class TagController extends AdminApiController */ #[Endpoint('Create tag', 'Creates a tag.')] #[ResponseFromTransformer(TagTransformer::class, Tag::class, status: 201, description: 'Tag created.', resourceKey: 'tag', meta: ['resource' => 'https://panel.example.com/api/admin/tags/1'])] - public function store(StoreTagRequest $request): JsonResponse + public function store(StoreTagRequest $request, CreatesTags $tags): JsonResponse { - $tag = Tag::query()->create($request->validated()); + $tag = $tags->create($request->payload()); Activity::event('admin:tag.create') ->subject($tag) @@ -123,11 +125,9 @@ class TagController extends AdminApiController #[Endpoint('Update tag', 'Updates an existing tag. Built-in game tags cannot be edited.')] #[ResponseFromTransformer(TagTransformer::class, Tag::class, description: 'Tag updated.', resourceKey: 'tag')] #[ScribeResponse(self::BUILT_IN_ERROR, status: 400, description: 'The tag is a built-in game tag.')] - public function update(UpdateTagRequest $request, Tag $tag): array + public function update(UpdateTagRequest $request, UpdatesTags $tags, Tag $tag): array { - $this->guardBuiltIn($tag); - - $tag->update($request->validated()); + $tag = $tags->update($tag, $request->payload()); Activity::event('admin:tag.update') ->subject($tag) @@ -151,11 +151,9 @@ class TagController extends AdminApiController #[Endpoint('Delete tag', 'Deletes a tag and detaches it from every egg and node.')] #[ScribeResponse(status: 204, description: 'Tag deleted.')] #[ScribeResponse(self::BUILT_IN_ERROR, status: 400, description: 'The tag is a built-in game tag.')] - public function destroy(DeleteTagRequest $request, Tag $tag): Response + public function destroy(DeleteTagRequest $request, DeletesTags $tags, Tag $tag): Response { - $this->guardBuiltIn($tag); - - $tag->delete(); + $tags->delete($tag); Activity::event('admin:tag.delete') ->subject($tag) @@ -230,16 +228,4 @@ class TagController extends AdminApiController ->transformWith($this->getTransformer(TagTransformer::class)) ->toResponseArray(); } - - /** - * Reject edits to a built-in game tag. Its slug is the key that feature gating - * matches on, and its presentation comes from the EggSpecificTags enum, so it - * must never be renamed or relabelled. - * - * @throws DisplayException - */ - private function guardBuiltIn(Tag $tag): void - { - throw_if(EggSpecificTags::isSpecial($tag->slug), DisplayException::class, 'Built-in game tags cannot be edited.'); - } } diff --git a/app/Http/Controllers/Api/Admin/Users/DisableTwoFactorController.php b/app/Http/Controllers/Api/Admin/Users/DisableTwoFactorController.php index a4cd96ab8..432406b15 100644 --- a/app/Http/Controllers/Api/Admin/Users/DisableTwoFactorController.php +++ b/app/Http/Controllers/Api/Admin/Users/DisableTwoFactorController.php @@ -9,6 +9,7 @@ use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; +use Pterodactyl\Contracts\Users\DisablesTwoFactor; use Pterodactyl\Facades\Activity; use Pterodactyl\Http\Controllers\Api\Admin\AdminApiController; use Pterodactyl\Http\Requests\Api\Admin\Users\DisableTwoFactorRequest; @@ -23,13 +24,9 @@ class DisableTwoFactorController extends AdminApiController */ #[Endpoint('Disable user two-factor authentication', 'Clears the configured TOTP secret and disables two-factor authentication for a user.')] #[ScribeResponse(status: 204, description: 'Two-factor authentication disabled.')] - public function __invoke(DisableTwoFactorRequest $request, User $user): Response + public function __invoke(DisableTwoFactorRequest $request, DisablesTwoFactor $twoFactor, User $user): Response { - $user->forceFill([ - 'use_totp' => false, - 'totp_secret' => null, - 'totp_authenticated_at' => null, - ])->saveOrFail(); + $twoFactor->disable($user); Activity::event('admin:user.disable-2fa') ->subject($user) diff --git a/app/Http/Controllers/Api/Client/Servers/DatabaseController.php b/app/Http/Controllers/Api/Client/Servers/DatabaseController.php index 92a66ea68..b96739205 100644 --- a/app/Http/Controllers/Api/Client/Servers/DatabaseController.php +++ b/app/Http/Controllers/Api/Client/Servers/DatabaseController.php @@ -97,10 +97,14 @@ class DatabaseController extends ClientApiController #[ResponseFromTransformer(DatabaseTransformer::class, Database::class, description: 'Database password rotated.', resourceKey: 'server_database', include: ['password'])] public function rotatePassword(RotatePasswordRequest $request, RotatesDatabasePasswords $passwordService, Server $server, Database $database): array { + // The action commits its own transaction around the remote user change, so the + // activity is logged afterwards instead of wrapping a change it cannot undo. + $passwordService->rotate($database); + Activity::event('server:database.rotate-password') ->subject($database) ->property('name', $database->database) - ->transaction(fn (): string => $passwordService->rotate($database)); + ->log(); return Fractal::item($database->refresh()) ->parseIncludes(['password']) diff --git a/app/Http/Controllers/Api/Client/Servers/SettingsController.php b/app/Http/Controllers/Api/Client/Servers/SettingsController.php index 74e5f3e79..5c438bdaa 100644 --- a/app/Http/Controllers/Api/Client/Servers/SettingsController.php +++ b/app/Http/Controllers/Api/Client/Servers/SettingsController.php @@ -12,6 +12,7 @@ use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response as ScribeResponse; use Knuckles\Scribe\Attributes\Subgroup; use Pterodactyl\Contracts\Servers\ReinstallsServers; +use Pterodactyl\Contracts\Servers\UpdatesServerDetails; use Pterodactyl\Facades\Activity; use Pterodactyl\Http\Controllers\Api\Client\ClientApiController; use Pterodactyl\Http\Requests\Api\Client\Servers\Settings\ReinstallServerRequest; @@ -39,26 +40,32 @@ class SettingsController extends ClientApiController /** * Renames a server. + * + * @throws Throwable */ #[Endpoint('Rename server', 'Updates the server name and optionally its description.')] #[ScribeResponse(status: 204, description: 'Server renamed.')] - public function rename(RenameServerRequest $request, Server $server): JsonResponse + public function rename(RenameServerRequest $request, UpdatesServerDetails $details, Server $server): JsonResponse { $previousName = $server->name; $previousDescription = $server->description; - $server->update([ + // The action writes owner and external ID too, so pass the current values + // through unchanged; only the name and description come from the request. + $server = $details->update($server, [ + 'external_id' => $server->external_id, + 'owner_id' => $server->owner_id, 'name' => $request->string('name')->toString(), 'description' => $request->has('description') ? $request->description() : $server->description, ]); - if ($server->wasChanged('name')) { + if ($previousName !== $server->name) { Activity::event('server:settings.rename') ->property(['old' => $previousName, 'new' => $server->name]) ->log(); } - if ($server->wasChanged('description')) { + if ($previousDescription !== $server->description) { Activity::event('server:settings.description') ->property(['old' => $previousDescription, 'new' => $server->description]) ->log(); diff --git a/app/Http/Requests/Api/Admin/Mounts/StoreMountRequest.php b/app/Http/Requests/Api/Admin/Mounts/StoreMountRequest.php index 04b838b69..e6e1a9d64 100644 --- a/app/Http/Requests/Api/Admin/Mounts/StoreMountRequest.php +++ b/app/Http/Requests/Api/Admin/Mounts/StoreMountRequest.php @@ -6,6 +6,7 @@ namespace Pterodactyl\Http\Requests\Api\Admin\Mounts; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest; +use Pterodactyl\Support\JsonValueGuard; use Pterodactyl\Validation\MountRules; class StoreMountRequest extends AdminApiRequest @@ -24,4 +25,33 @@ class StoreMountRequest extends AdminApiRequest { return MountRules::rules(); } + + /** + * Model attributes for the mount. Optional fields stay absent when the + * request omits them so an update leaves the stored value alone. + * + * @return MountData + */ + public function payload(): array + { + $payload = [ + 'name' => $this->string('name')->toString(), + 'source' => $this->string('source')->toString(), + 'target' => $this->string('target')->toString(), + ]; + + if ($this->exists('description')) { + $payload['description'] = JsonValueGuard::nullableString($this->input('description')); + } + + if ($this->exists('read_only')) { + $payload['read_only'] = $this->boolean('read_only'); + } + + if ($this->exists('user_mountable')) { + $payload['user_mountable'] = $this->boolean('user_mountable'); + } + + return $payload; + } } diff --git a/app/Http/Requests/Api/Admin/Tags/StoreTagRequest.php b/app/Http/Requests/Api/Admin/Tags/StoreTagRequest.php index 80a6027d9..b1c625003 100644 --- a/app/Http/Requests/Api/Admin/Tags/StoreTagRequest.php +++ b/app/Http/Requests/Api/Admin/Tags/StoreTagRequest.php @@ -7,6 +7,7 @@ namespace Pterodactyl\Http\Requests\Api\Admin\Tags; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest; use Pterodactyl\Rules\TagSlug; +use Pterodactyl\Support\JsonValueGuard; use Pterodactyl\Support\ValidationRuleSubset; use Pterodactyl\Validation\TagRules; @@ -25,6 +26,26 @@ class StoreTagRequest extends AdminApiRequest return $this->withSlugRule(TagRules::rules()); } + /** + * Model attributes for the tag. The color stays absent when the request + * omits it so an update leaves the stored value alone. + * + * @return TagData + */ + public function payload(): array + { + $payload = [ + 'name' => $this->string('name')->toString(), + 'slug' => $this->string('slug')->toString(), + ]; + + if ($this->exists('color')) { + $payload['color'] = JsonValueGuard::nullableString($this->input('color')); + } + + return $payload; + } + /** * Narrow the model rules to the writable fields and forbid numeric slugs, so a * leftover legacy nest id can be told apart from a real tag and a slug can never diff --git a/app/Providers/ActionServiceProvider.php b/app/Providers/ActionServiceProvider.php index 8e7a5be7b..49de83f77 100644 --- a/app/Providers/ActionServiceProvider.php +++ b/app/Providers/ActionServiceProvider.php @@ -16,6 +16,8 @@ use Pterodactyl\Actions\Allocations\UpdateAllocation; use Pterodactyl\Actions\Allocations\UpdateAllocationNotes; use Pterodactyl\Actions\Api\CreateAccountApiKey; use Pterodactyl\Actions\Api\CreateApiKey; +use Pterodactyl\Actions\Api\DeleteApiKey; +use Pterodactyl\Actions\Api\UpdateApiKey; use Pterodactyl\Actions\Backups\CompleteBackup; use Pterodactyl\Actions\Backups\DeleteBackup; use Pterodactyl\Actions\Backups\GenerateBackupDownloadLink; @@ -40,6 +42,7 @@ use Pterodactyl\Actions\Eggs\Sharing\ImportEgg; use Pterodactyl\Actions\Eggs\Sharing\UpdateEggFromImport; use Pterodactyl\Actions\Eggs\UpdateEgg; use Pterodactyl\Actions\Eggs\Variables\CreateEggVariable; +use Pterodactyl\Actions\Eggs\Variables\DeleteEggVariable; use Pterodactyl\Actions\Eggs\Variables\ReorderEggVariables; use Pterodactyl\Actions\Eggs\Variables\UpdateEggVariable; use Pterodactyl\Actions\Extensions\InstallExtension; @@ -61,6 +64,13 @@ use Pterodactyl\Actions\Files\WriteFileContents; use Pterodactyl\Actions\Locations\CreateLocation; use Pterodactyl\Actions\Locations\DeleteLocation; use Pterodactyl\Actions\Locations\UpdateLocation; +use Pterodactyl\Actions\Mounts\AttachEggsToMount; +use Pterodactyl\Actions\Mounts\AttachNodesToMount; +use Pterodactyl\Actions\Mounts\CreateMount; +use Pterodactyl\Actions\Mounts\DeleteMount; +use Pterodactyl\Actions\Mounts\DetachEggFromMount; +use Pterodactyl\Actions\Mounts\DetachNodeFromMount; +use Pterodactyl\Actions\Mounts\UpdateMount; use Pterodactyl\Actions\Nodes\CreateNode; use Pterodactyl\Actions\Nodes\DeleteNode; use Pterodactyl\Actions\Nodes\ResetServerStates; @@ -84,6 +94,7 @@ use Pterodactyl\Actions\Servers\RecordServerInstallResult; use Pterodactyl\Actions\Servers\ReinstallServer; use Pterodactyl\Actions\Servers\SendServerCommand; use Pterodactyl\Actions\Servers\SendServerPower; +use Pterodactyl\Actions\Servers\ToggleServerInstallStatus; use Pterodactyl\Actions\Servers\ToggleServerSuspension; use Pterodactyl\Actions\Servers\UpdateServerBuild; use Pterodactyl\Actions\Servers\UpdateServerDetails; @@ -91,7 +102,10 @@ use Pterodactyl\Actions\Servers\UpdateServerStartup; use Pterodactyl\Actions\Subusers\CreateSubuser; use Pterodactyl\Actions\Subusers\DeleteSubuser; use Pterodactyl\Actions\Subusers\UpdateSubuser; +use Pterodactyl\Actions\Tags\CreateTag; +use Pterodactyl\Actions\Tags\DeleteTag; use Pterodactyl\Actions\Tags\SyncTags; +use Pterodactyl\Actions\Tags\UpdateTag; use Pterodactyl\Actions\Telemetry\SendTelemetry; use Pterodactyl\Actions\Themes\ApplyTheme; use Pterodactyl\Actions\Themes\ResetTheme; @@ -118,6 +132,8 @@ use Pterodactyl\Contracts\Allocations\UpdatesAllocationNotes; use Pterodactyl\Contracts\Allocations\UpdatesAllocations; use Pterodactyl\Contracts\Api\CreatesAccountApiKeys; use Pterodactyl\Contracts\Api\CreatesApiKeys; +use Pterodactyl\Contracts\Api\DeletesApiKeys; +use Pterodactyl\Contracts\Api\UpdatesApiKeys; use Pterodactyl\Contracts\Backups\CompletesBackups; use Pterodactyl\Contracts\Backups\DeletesBackups; use Pterodactyl\Contracts\Backups\GeneratesBackupDownloadLinks; @@ -136,6 +152,7 @@ use Pterodactyl\Contracts\Databases\UpdatesDatabaseHosts; use Pterodactyl\Contracts\Eggs\CreatesEggs; use Pterodactyl\Contracts\Eggs\CreatesEggVariables; use Pterodactyl\Contracts\Eggs\DeletesEggs; +use Pterodactyl\Contracts\Eggs\DeletesEggVariables; use Pterodactyl\Contracts\Eggs\ExportsEggs; use Pterodactyl\Contracts\Eggs\ImportsCatalogEggs; use Pterodactyl\Contracts\Eggs\ImportsEggs; @@ -163,6 +180,13 @@ use Pterodactyl\Contracts\Files\WritesFileContents; use Pterodactyl\Contracts\Locations\CreatesLocations; use Pterodactyl\Contracts\Locations\DeletesLocations; use Pterodactyl\Contracts\Locations\UpdatesLocations; +use Pterodactyl\Contracts\Mounts\AttachesEggsToMounts; +use Pterodactyl\Contracts\Mounts\AttachesNodesToMounts; +use Pterodactyl\Contracts\Mounts\CreatesMounts; +use Pterodactyl\Contracts\Mounts\DeletesMounts; +use Pterodactyl\Contracts\Mounts\DetachesEggsFromMounts; +use Pterodactyl\Contracts\Mounts\DetachesNodesFromMounts; +use Pterodactyl\Contracts\Mounts\UpdatesMounts; use Pterodactyl\Contracts\Nodes\CreatesNodes; use Pterodactyl\Contracts\Nodes\DeletesNodes; use Pterodactyl\Contracts\Nodes\ResetsServerStates; @@ -186,6 +210,7 @@ use Pterodactyl\Contracts\Servers\RecordsServerInstallResults; use Pterodactyl\Contracts\Servers\ReinstallsServers; use Pterodactyl\Contracts\Servers\SendsServerCommands; use Pterodactyl\Contracts\Servers\SendsServerPower; +use Pterodactyl\Contracts\Servers\TogglesServerInstallStatus; use Pterodactyl\Contracts\Servers\TogglesServerSuspension; use Pterodactyl\Contracts\Servers\UpdatesServerBuild; use Pterodactyl\Contracts\Servers\UpdatesServerDetails; @@ -193,7 +218,10 @@ use Pterodactyl\Contracts\Servers\UpdatesServerStartup; use Pterodactyl\Contracts\Subusers\CreatesSubusers; use Pterodactyl\Contracts\Subusers\DeletesSubusers; use Pterodactyl\Contracts\Subusers\UpdatesSubusers; +use Pterodactyl\Contracts\Tags\CreatesTags; +use Pterodactyl\Contracts\Tags\DeletesTags; use Pterodactyl\Contracts\Tags\SyncsTags; +use Pterodactyl\Contracts\Tags\UpdatesTags; use Pterodactyl\Contracts\Telemetry\SendsTelemetry; use Pterodactyl\Contracts\Themes\AppliesThemes; use Pterodactyl\Contracts\Themes\ResetsThemes; @@ -321,5 +349,19 @@ class ActionServiceProvider extends ServiceProvider $this->app->bind(ReadsServerState::class, ReadServerState::class); $this->app->bind(ChangesServerEgg::class, ChangeServerEgg::class); $this->app->bind(CompletesLogins::class, CompleteLogin::class); + $this->app->bind(UpdatesApiKeys::class, UpdateApiKey::class); + $this->app->bind(DeletesApiKeys::class, DeleteApiKey::class); + $this->app->bind(DeletesEggVariables::class, DeleteEggVariable::class); + $this->app->bind(CreatesMounts::class, CreateMount::class); + $this->app->bind(UpdatesMounts::class, UpdateMount::class); + $this->app->bind(DeletesMounts::class, DeleteMount::class); + $this->app->bind(AttachesEggsToMounts::class, AttachEggsToMount::class); + $this->app->bind(AttachesNodesToMounts::class, AttachNodesToMount::class); + $this->app->bind(DetachesEggsFromMounts::class, DetachEggFromMount::class); + $this->app->bind(DetachesNodesFromMounts::class, DetachNodeFromMount::class); + $this->app->bind(TogglesServerInstallStatus::class, ToggleServerInstallStatus::class); + $this->app->bind(CreatesTags::class, CreateTag::class); + $this->app->bind(UpdatesTags::class, UpdateTag::class); + $this->app->bind(DeletesTags::class, DeleteTag::class); } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 87794c90b..2c47f9880 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -41,6 +41,7 @@ use Pterodactyl\Models\Task; use Pterodactyl\Models\User; use Pterodactyl\Models\UserSSHKey; use Pterodactyl\Services\Daemon\DaemonManager; +use Pterodactyl\Services\Servers\EnvironmentService; use Pterodactyl\Support\JsonValueGuard; class AppServiceProvider extends ServiceProvider @@ -110,6 +111,10 @@ class AppServiceProvider extends ServiceProvider { $this->app->singleton(DaemonManager::class); + // Keys registered through setEnvironmentKey() must survive to every consumer, + // so the service is shared rather than rebuilt on each resolve. + $this->app->singleton(EnvironmentService::class); + $this->app->extend('auth.password', fn (): PasswordBrokerManager => new PasswordBrokerManager($this->app)); $this->app->bind(function (): Fractal { diff --git a/packages/sdk/README.md b/packages/sdk/README.md index 3afe68cab..a4cfeb6d0 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -403,6 +403,15 @@ final class PurgeDnsRecords implements DeletesServers } ``` +A few core actions call out only after their own transaction commits, so wrappers of the +nested contracts run outside it. When creating a backup rotates out an old one, +`DeletesBackups` runs after the new backup is recorded and Wings has accepted it. During +server deletion, `DeletesDatabases` runs after the server and its database rows are +deleted, so the `Database` it receives no longer exists in the panel, and a failure is +reported instead of failing the deletion. The Wings call that starts a transfer also runs +after the transfer is recorded; if Wings rejects it, the transfer is marked failed through +`FailsTransfers`. + The wrapper owns the call: it decides whether and when to invoke the inner action and must forward fluent options such as `withForce()` itself, returning itself. Whatever it throws reaches the caller unchanged, and exceptions of the inner action pass through diff --git a/packages/sdk/types/api/generated/types.gen.d.ts b/packages/sdk/types/api/generated/types.gen.d.ts index d7eac352e..502839426 100644 --- a/packages/sdk/types/api/generated/types.gen.d.ts +++ b/packages/sdk/types/api/generated/types.gen.d.ts @@ -10,7 +10,7 @@ export type AdminActivityLogAttributes = { ip: string | null; description: string | null; properties: { - [key: string]: string | number | number | boolean | Array | { + [key: string]: string | number | boolean | Array | { [key: string]: string; }; }; @@ -983,7 +983,7 @@ export type ClientActivityLogAttributes = { ip: string | null; description: string | null; properties: { - [key: string]: string | number | number | boolean | Array | { + [key: string]: string | number | boolean | Array | { [key: string]: string; }; }; @@ -1912,11 +1912,11 @@ export type AdminCreateMountRequest = { */ description?: string | null; /** - * The source path. Must not be one of /etc/pterodactyl, /var/lib/pterodactyl/volumes, or /srv/daemon-data. + * The source path. Must start with one of /. */ source: string; /** - * The target path. Must not be one of /home/container. + * The target path. Must start with one of /. */ target: string; /** @@ -1938,11 +1938,11 @@ export type AdminUpdateMountRequest = { */ description?: string | null; /** - * The source path. Must not be one of /etc/pterodactyl, /var/lib/pterodactyl/volumes, or /srv/daemon-data. + * The source path. Must start with one of /. */ source: string; /** - * The target path. Must not be one of /home/container. + * The target path. Must start with one of /. */ target: string; /** @@ -3034,17 +3034,23 @@ export type ClientCreateServerDatabaseRequest = { }; export type ClientRenameFilesRequest = { /** - * The root. + * The root. Must not be greater than 2048 characters. */ - root: string; + root?: string | null; files?: Array<{ + /** + * Must not be greater than 2048 characters. + */ to: string; + /** + * Must not be greater than 2048 characters. + */ from: string; }>; }; export type ClientCopyFileRequest = { /** - * The location. + * The location. Must not be greater than 2048 characters. */ location: string; }; @@ -3054,62 +3060,74 @@ export type ClientCopyFileRequest = { export type ClientWriteFileContentsRequest = string; export type ClientCompressFilesRequest = { /** - * The root. + * The root. Must not be greater than 2048 characters. */ root?: string | null; + /** + * Must not be greater than 2048 characters. + */ files?: Array; }; export type ClientDecompressFileRequest = { /** - * The root. + * The root. Must not be greater than 2048 characters. */ root?: string | null; /** - * The file path. + * The file path. Must not be greater than 2048 characters. */ file: string; }; export type ClientDeleteFilesRequest = { /** - * The root. + * The root. Must not be greater than 2048 characters. + */ + root?: string | null; + /** + * Must not be greater than 2048 characters. */ - root: string; files?: Array; }; export type ClientCreateFolderRequest = { /** - * The root. + * The root. Must not be greater than 2048 characters. */ root?: string | null; /** - * The display name. + * The display name. Must not be greater than 255 characters. */ name: string; }; export type ClientChangeFilePermissionsRequest = { /** - * The root. + * The root. Must not be greater than 2048 characters. */ - root: string; + root?: string | null; /** * File paths affected by the operation. */ files: Array<{ + /** + * Must not be greater than 2048 characters. + */ file: string; - mode: number; + /** + * Must match the regex /^[0-7]{3,4}$/. + */ + mode: string; }>; }; export type ClientPullRemoteFileRequest = { /** - * The URL. Must be a valid URL. + * The URL. Must be a valid URL. Must not be greater than 2048 characters. */ url: string; /** - * The directory path. + * The directory path. Must not be greater than 2048 characters. */ directory?: string | null; /** - * The file name. + * The file name. Must not be greater than 255 characters. */ filename?: string | null; /** @@ -11874,7 +11892,7 @@ export type ClientGetFileDownloadUrlResponses = { }; export type ClientGetFileDownloadUrlResponse = ClientGetFileDownloadUrlResponses[keyof ClientGetFileDownloadUrlResponses]; export type ClientRenameFilesData = { - body: ClientRenameFilesRequest; + body?: ClientRenameFilesRequest; path: { /** * The server UUID. @@ -12084,7 +12102,7 @@ export type ClientDecompressFileResponses = { }; export type ClientDecompressFileResponse = ClientDecompressFileResponses[keyof ClientDecompressFileResponses]; export type ClientDeleteFilesData = { - body: ClientDeleteFilesRequest; + body?: ClientDeleteFilesRequest; path: { /** * The server UUID. diff --git a/packages/sdk/types/components/elements/Can.d.ts b/packages/sdk/types/components/elements/Can.d.ts index 6a767a885..3ed1dd6b2 100644 --- a/packages/sdk/types/components/elements/Can.d.ts +++ b/packages/sdk/types/components/elements/Can.d.ts @@ -6,5 +6,5 @@ interface Props { renderOnError?: React.ReactNode | null; children: React.ReactNode; } -export default function Can({ action, matchAny, renderOnError, children }: Props): React.JSX.Element; +export default function Can({ action, matchAny, renderOnError, children }: Props): React.ReactNode; export {}; diff --git a/phpstan.neon b/phpstan.neon index 1932718c0..d4c9e5597 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -89,6 +89,9 @@ parameters: MultipartUploadPart: 'array{etag: string, part_number: int}' LocationCreationData: 'array{short: string, long?: string|null}' LocationUpdateData: 'array{short?: string, long?: string|null}' + MountData: 'array{name: string, description?: string|null, source: string, target: string, read_only?: bool, user_mountable?: bool}' + TagData: 'array{name: string, slug: string, color?: string|null}' + ApiKeyUpdateData: 'array{memo: string|null}' NodeUpdateData: 'NodeCreationData&array{daemon_token?: string, daemon_token_id?: string}' NodeCreationData: 'array{name: string, location_id: int, fqdn: string, scheme: string, memory: int, memory_overallocate: int, disk: int, disk_overallocate: int, daemonListen: int, daemonSFTP: int, daemonBase: string, description?: string|null, public?: bool, behind_proxy?: bool, maintenance_mode?: bool, upload_size?: int}' UserCreationData: 'array{email: string, username: string, name_first: string, name_last: string, external_id?: string|null, password?: string|null, root_admin?: bool, language?: string}' diff --git a/resources/scripts/components/server/console/AreaChart.tsx b/resources/scripts/components/server/console/AreaChart.tsx index 83a09c3c5..e59dd8a8b 100644 --- a/resources/scripts/components/server/console/AreaChart.tsx +++ b/resources/scripts/components/server/console/AreaChart.tsx @@ -1,14 +1,20 @@ -import { lazy, Suspense, useId, useMemo, useRef } from 'react'; -import { type ChartPoint, useAnimationClock, useElementVisible } from '@/components/server/console/chart'; +import { lazy, Suspense, useId, useLayoutEffect, useMemo, useRef } from 'react'; +import { type ChartPoint, useElementWidth } from '@/components/server/console/chart'; import type { ChartSeries } from '@/components/server/console/types'; const GRID_COLOR = 'var(--border)'; const TICK_COLOR = 'var(--muted-foreground)'; const SANS_FONT = 'var(--font-sans)'; +const Y_AXIS_WIDTH = 64; +const MARGIN = { top: 8, right: 8, bottom: 0, left: 0 }; + // How far the visible right edge trails real time; just over the ~1s stats cadence. const RIGHT_LAG_MS = 1100; +// Time drawn past the visible right edge, so the plot can keep sliding while the next sample is late. +const SLIDE_MS = 4000; + interface Props { data: ChartPoint[]; series: ChartSeries[]; @@ -20,100 +26,160 @@ interface Props { height?: number; } -type YDomain = [number, (dataMax: number) => number] | [number, string]; +type YDomain = [number, number | 'auto']; interface RechartsAreaChartContentProps { data: ChartPoint[]; series: ChartSeries[]; + live: boolean; uid: string; + width: number; height: number; - xDomain: [number, number]; + windowMs: number; yDomain: YDomain; tickFormatter?: (value: number) => string; } +/* + * The chart is drawn in two layers. The grid and Y axis stay put; the series are drawn once per + * sample, a little wider than the plot, and slid left by a transform animation until the next + * sample replaces them. Moving the plot never re-renders or repaints the SVG, so its cost does not + * depend on the frame rate or on how expensive the active theme makes painting. + */ const LazyRechartsAreaChart = lazy(async () => { - const { - Area, - AreaChart: RechartsAreaChart, - CartesianGrid, - ResponsiveContainer, - XAxis, - YAxis, - } = await import('recharts'); + const { Area, AreaChart: RechartsAreaChart, CartesianGrid, XAxis, YAxis } = await import('recharts'); return { default: function RechartsAreaChartContent({ data, series, + live, uid, + width, height, - xDomain, + windowMs, yDomain, tickFormatter, }: RechartsAreaChartContentProps) { + const slider = useRef(null); + const plotWidth = Math.max(0, width - Y_AXIS_WIDTH - MARGIN.right); + const slideDistance = (plotWidth * SLIDE_MS) / windowMs; + + // The newest sample's arrival time is the moment the visible window ends at `anchor - RIGHT_LAG_MS`. + const anchor = data.at(-1)?.t; + const right = (anchor ?? 0) - RIGHT_LAG_MS; + + useLayoutEffect(() => { + if (!slider.current || anchor === undefined) { + return; + } + + const animation = slider.current.animate( + [{ transform: 'translateX(0)' }, { transform: `translateX(${-slideDistance}px)` }], + { duration: SLIDE_MS, easing: 'linear', fill: 'forwards' } + ); + + animation.currentTime = Math.min(SLIDE_MS, Math.max(0, performance.now() - anchor)); + + if (!live) { + animation.pause(); + } + + return () => animation.cancel(); + }, [anchor, live, slideDistance]); + return ( - - - - {series.map(({ dataKey, color }) => ( - - - - - ))} - {series.map(({ dataKey, color }) => ( - - - - ))} - - - - - {series.map(({ dataKey, color }) => ( - +
+ + + - ))} - - + +
+
+
+ + + {series.map(({ dataKey, color }) => ( + + + + + ))} + {series.map(({ dataKey, color }) => ( + + + + ))} + + + + {series.map(({ dataKey, color }) => ( + + ))} + +
+
+ ); }, }; @@ -122,29 +188,38 @@ const LazyRechartsAreaChart = lazy(async () => { export default function AreaChart({ data, series, live, windowMs, suggestedMax, tickFormatter, height = 180 }: Props) { const uid = useId().replaceAll(':', ''); const container = useRef(null); - const visible = useElementVisible(container); - const now = useAnimationClock(live && visible); + const width = useElementWidth(container); - const right = now - RIGHT_LAG_MS; - const xDomain = useMemo<[number, number]>(() => [right - windowMs, right], [right, windowMs]); - const yDomain = useMemo( - () => (suggestedMax === undefined ? [0, 'auto'] : [0, (dataMax: number) => Math.max(suggestedMax, dataMax)]), - [suggestedMax] - ); + // Both layers share one domain so the static axis lines up with the sliding series. + const yDomain = useMemo(() => { + let max = suggestedMax ?? 0; + + for (const point of data) { + for (const { dataKey } of series) { + max = Math.max(max, point[dataKey] ?? 0); + } + } + + return [0, max > 0 ? max : 'auto']; + }, [data, series, suggestedMax]); return ( -
- }> - - +
+ {width > 0 && ( + + + + )}
); } diff --git a/resources/scripts/components/server/console/chart.spec.tsx b/resources/scripts/components/server/console/chart.spec.tsx index 4dbf09175..46a9a8729 100644 --- a/resources/scripts/components/server/console/chart.spec.tsx +++ b/resources/scripts/components/server/console/chart.spec.tsx @@ -1,106 +1,126 @@ /** @vitest-environment jsdom */ -import { useRef } from 'react'; -import { act, cleanup, render } from '@testing-library/react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { useAnimationClock, useElementVisible } from './chart'; +import { act, cleanup, render, waitFor } from '@testing-library/react'; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import AreaChart from './AreaChart'; +import type { ChartPoint } from './chart'; -let frames = new Map(); -let nextFrame = 0; -let observerCallback: IntersectionObserverCallback | null = null; -let renders = 0; - -const runFrame = (timestamp: number) => - act(() => { - const pending = [...frames.values()]; - - frames = new Map(); - for (const callback of pending) { - callback(timestamp); - } - }); - -const reportIntersection = (isIntersecting: boolean) => - act(() => observerCallback?.([{ isIntersecting } as IntersectionObserverEntry], {} as IntersectionObserver)); - -function Chart({ live }: { live: boolean }) { - const ref = useRef(null); - const visible = useElementVisible(ref); - const now = useAnimationClock(live && visible); - - renders++; - - return
; +interface FakeAnimation { + keyframes: Keyframe[]; + currentTime: number | null; + pause: ReturnType; + cancel: ReturnType; } -describe('chart animation clock', () => { - beforeEach(() => { - frames = new Map(); - renders = 0; - observerCallback = null; - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - frames.set(++nextFrame, callback); +let animations: FakeAnimation[] = []; +let resize: ResizeObserverCallback | null = null; - return nextFrame; - }); - vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id)); +const SERIES = [{ dataKey: 'value', color: 'var(--chart-1)' }]; + +const reportWidth = (width: number) => + act(() => resize?.([{ contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver)); + +const renderChart = (data: ChartPoint[], live = true) => + render(); + +describe('console area chart', () => { + // The chart lazy-loads recharts; a cold import can outlast waitFor's timeout. + beforeAll(() => import('recharts')); + + beforeEach(() => { + animations = []; + vi.spyOn(performance, 'now').mockReturnValue(10_000); vi.stubGlobal( - 'IntersectionObserver', + 'ResizeObserver', class { - constructor(callback: IntersectionObserverCallback) { - observerCallback = callback; + constructor(callback: ResizeObserverCallback) { + resize = callback; } observe() {} disconnect() {} } ); + // jsdom has no Web Animations API. + Object.defineProperty(Element.prototype, 'animate', { + configurable: true, + value: (keyframes: Keyframe[]) => { + const animation: FakeAnimation = { keyframes, currentTime: 0, pause: vi.fn(), cancel: vi.fn() }; + + animations.push(animation); + + return animation; + }, + }); }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); + Reflect.deleteProperty(Element.prototype, 'animate'); + resize = null; }); - it('stays idle until the chart is on screen', async () => { - const { container } = render(); - const before = renders; + it('starts the slide as far in as the newest sample is old', async () => { + renderChart([ + { t: 9_000, value: 10 }, + { t: 9_800, value: 20 }, + ]); + await reportWidth(572); - await runFrame(1_000); - await runFrame(2_000); + await waitFor(() => expect(animations).toHaveLength(1)); - expect(frames.size).toBe(0); - expect(renders).toBe(before); - - await reportIntersection(true); - await runFrame(3_000); - - expect(container.firstElementChild).toHaveAttribute('data-now', '3000'); + // 500px of plot shows 20s, so the 4s of slack beyond the right edge is 100px of travel. + expect(animations[0].keyframes.at(-1)).toEqual({ transform: 'translateX(-100px)' }); + // The newest sample arrived 200ms ago, so the slide starts that far in. + expect(animations[0].currentTime).toBe(200); + expect(animations[0].pause).not.toHaveBeenCalled(); }); - it('stops ticking when the chart leaves the screen, the tab hides, or the server is not live', async () => { - const { container, rerender } = render(); + it('restarts the slide when a sample arrives and holds it while the server is not live', async () => { + const { rerender } = renderChart([{ t: 9_800, value: 20 }]); - await reportIntersection(true); - await runFrame(1_000); - expect(container.firstElementChild).toHaveAttribute('data-now', '1000'); + await reportWidth(572); + await waitFor(() => expect(animations).toHaveLength(1)); - await reportIntersection(false); - expect(frames.size).toBe(0); + rerender( + + ); - await reportIntersection(true); - const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); + expect(animations[0].cancel).toHaveBeenCalled(); + expect(animations).toHaveLength(2); + expect(animations[1].currentTime).toBe(0); - await act(() => document.dispatchEvent(new Event('visibilitychange'))); - expect(frames.size).toBe(0); + rerender( + + ); - visibility.mockReturnValue('visible'); - await act(() => document.dispatchEvent(new Event('visibilitychange'))); - await runFrame(2_000); - expect(container.firstElementChild).toHaveAttribute('data-now', '2000'); + expect(animations).toHaveLength(3); + expect(animations[2].pause).toHaveBeenCalled(); + }); - rerender(); - expect(frames.size).toBe(0); - await runFrame(3_000); - expect(container.firstElementChild).toHaveAttribute('data-now', '2000'); + it('does not animate before the first sample', async () => { + renderChart([]); + await reportWidth(572); + await waitFor(() => expect(document.querySelector('.recharts-wrapper')).not.toBeNull()); + + expect(animations).toHaveLength(0); }); }); diff --git a/resources/scripts/components/server/console/chart.ts b/resources/scripts/components/server/console/chart.ts index de60382a4..11af5566e 100644 --- a/resources/scripts/components/server/console/chart.ts +++ b/resources/scripts/components/server/console/chart.ts @@ -39,39 +39,9 @@ export function useRollingData(keys: readonly string[]) { return { data, push, clear }; } -/** A performance.now() clock that re-renders at ~`fps` while `active`. */ -export function useAnimationClock(active: boolean, fps = 30): number { - const [now, setNow] = useState(() => performance.now()); - - useEffect(() => { - if (!active) { - return; - } - - const minDelta = 1000 / fps; - let frame = 0; - let last = 0; - - const tick = (timestamp: number) => { - frame = requestAnimationFrame(tick); - if (timestamp - last >= minDelta) { - last = timestamp; - setNow(timestamp); - } - }; - - frame = requestAnimationFrame(tick); - - return () => cancelAnimationFrame(frame); - }, [active, fps]); - - return now; -} - -/** Whether the element intersects the viewport while the document is visible. */ -export function useElementVisible(ref: RefObject): boolean { - const [intersecting, setIntersecting] = useState(false); - const [documentVisible, setDocumentVisible] = useState(() => document.visibilityState !== 'hidden'); +/** The element's width in whole pixels; 0 until it has been measured. */ +export function useElementWidth(ref: RefObject): number { + const [width, setWidth] = useState(0); useEffect(() => { const element = ref.current; @@ -80,11 +50,11 @@ export function useElementVisible(ref: RefObject): boolean { return; } - const observer = new IntersectionObserver((entries) => { + const observer = new ResizeObserver((entries) => { const entry = entries.at(-1); if (entry) { - setIntersecting(entry.isIntersecting); + setWidth(Math.floor(entry.contentRect.width)); } }); @@ -93,13 +63,5 @@ export function useElementVisible(ref: RefObject): boolean { return () => observer.disconnect(); }, [ref]); - useEffect(() => { - const update = () => setDocumentVisible(document.visibilityState !== 'hidden'); - - document.addEventListener('visibilitychange', update); - - return () => document.removeEventListener('visibilitychange', update); - }, []); - - return intersecting && documentVisible; + return width; } diff --git a/tests/Integration/Actions/Backups/InitiateBackupTest.php b/tests/Integration/Actions/Backups/InitiateBackupTest.php new file mode 100644 index 000000000..40a135650 --- /dev/null +++ b/tests/Integration/Actions/Backups/InitiateBackupTest.php @@ -0,0 +1,86 @@ +set('backups.throttles.period', 0); +}); + +test('a server at its limit rotates out the oldest backup once wings accepts the new one', function (): void { + $server = $this->createServerModel(['backup_limit' => 2]); + $oldest = Backup::factory()->create(['server_id' => $server->id, 'created_at' => CarbonImmutable::now()->subDays(2)]); + $newer = Backup::factory()->create(['server_id' => $server->id, 'created_at' => CarbonImmutable::now()->subDay()]); + $fake = new FakeDaemonBackup; + + $backup = $this->app->make(InitiatesBackups::class)->initiate($server, 'Rotated', true); + + $fake->assertBackedUp($backup->uuid); + $fake->assertDeleted($oldest->uuid); + $this->assertSoftDeleted($oldest); + $this->assertNotSoftDeleted($newer); + expect($backup->completed_at)->toBeNull(); +}); + +test('a backup wings rejects is marked failed and the oldest backup is kept', function (): void { + $server = $this->createServerModel(['backup_limit' => 1]); + $oldest = Backup::factory()->create(['server_id' => $server->id, 'created_at' => CarbonImmutable::now()->subDay()]); + $fake = new FakeDaemonBackup; + $fake->throwable = new DaemonConnectionException(Http::failedRequest([], 500)); + + try { + $this->app->make(InitiatesBackups::class)->setIsLocked(true)->initiate($server, 'Rejected', true); + $this->fail('Expected DaemonConnectionException to be thrown.'); + } catch (DaemonConnectionException) { + } + + expect($fake->callsFor('delete'))->toBeEmpty(); + $this->assertNotSoftDeleted($oldest); + $failed = Backup::query()->where('server_id', $server->id)->where('name', 'Rejected')->firstOrFail(); + expect($failed->is_successful)->toBeFalse() + ->and($failed->is_locked)->toBeFalse() + ->and($failed->completed_at)->not->toBeNull(); +}); + +test('a backup rotated out by another request that is still pending is not counted twice', function (): void { + // Two backups against a limit of two plus one more: the oldest was picked for rotation by an + // earlier request whose delete has not run yet. This request has to rotate the next one too. + $server = $this->createServerModel(['backup_limit' => 2]); + $first = Backup::factory()->create(['server_id' => $server->id, 'created_at' => CarbonImmutable::now()->subDays(3)]); + $second = Backup::factory()->create(['server_id' => $server->id, 'created_at' => CarbonImmutable::now()->subDays(2)]); + $third = Backup::factory()->create(['server_id' => $server->id, 'created_at' => CarbonImmutable::now()->subDay()]); + $fake = new FakeDaemonBackup; + + $backup = $this->app->make(InitiatesBackups::class)->initiate($server, 'Next', true); + + $fake->assertBackedUp($backup->uuid); + $this->assertSoftDeleted($first); + $this->assertSoftDeleted($second); + $this->assertNotSoftDeleted($third); + expect(Backup::query()->where('server_id', $server->id)->count())->toBe(2); +}); + +test('a server at its limit without an unlocked backup is rejected before wings is called', function (): void { + $server = $this->createServerModel(['backup_limit' => 1]); + Backup::factory()->create(['server_id' => $server->id, 'is_locked' => true]); + $fake = new FakeDaemonBackup; + + expect(fn () => $this->app->make(InitiatesBackups::class)->initiate($server, 'Blocked', true)) + ->toThrow(TooManyBackupsException::class); + + $fake->assertNothingHappened(); + $this->assertDatabaseMissing('backups', ['server_id' => $server->id, 'name' => 'Blocked']); +}); diff --git a/tests/Integration/Actions/Servers/DeleteServerTest.php b/tests/Integration/Actions/Servers/DeleteServerTest.php index b5a43b3fd..4f23a9ad0 100644 --- a/tests/Integration/Actions/Servers/DeleteServerTest.php +++ b/tests/Integration/Actions/Servers/DeleteServerTest.php @@ -5,15 +5,18 @@ declare(strict_types=1); namespace Pterodactyl\Tests\Pest\Integration\Actions\Servers\DeleteServerTest; use Exception; +use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Http; +use Pterodactyl\Contracts\Databases\DeletesDatabases; use Pterodactyl\Contracts\Servers\DeletesServers; use Pterodactyl\Events\Server\OperationCompleted; use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException; use Pterodactyl\Models\Database; use Pterodactyl\Models\DatabaseHost; +use Pterodactyl\Models\Server; use Pterodactyl\Services\Databases\DatabaseHostGateway; use Pterodactyl\Tests\Integration\IntegrationTestCase; use Pterodactyl\Tests\Support\Fakes\FakeDaemonServer; @@ -25,7 +28,7 @@ uses(IntegrationTestCase::class, DatabaseTransactions::class); /** * Stub out services that we don't want to test in here. */ -beforeEach(function () { +beforeEach(function (): void { $this->defaultLogger = config('logging.default'); // There will be some log calls during this test, don't actually write to the disk. config()->set('logging.default', 'null'); @@ -35,11 +38,11 @@ beforeEach(function () { /** * Reset the log driver. */ -afterEach(function () { +afterEach(function (): void { config()->set('logging.default', $this->defaultLogger); $this->defaultLogger = null; }); -test('regular delete fails if wings returns error', function () { +test('regular delete fails if wings returns error', function (): void { $server = $this->createServerModel(); $this->daemonServerRepository->throwable = new DaemonConnectionException(Http::failedRequest([], 200)); try { @@ -47,40 +50,75 @@ test('regular delete fails if wings returns error', function () { $this->fail('Expected DaemonConnectionException to be thrown.'); } catch (DaemonConnectionException) { } + $this->daemonServerRepository->assertDeleted(); $this->assertDatabaseHas('servers', ['id' => $server->id]); }); -test('regular delete ignores404 from wings', function () { +test('regular delete ignores404 from wings', function (): void { $server = $this->createServerModel(); $this->daemonServerRepository->throwable = new DaemonConnectionException(Http::failedRequest([], 404)); getService()->delete($server); $this->daemonServerRepository->assertDeleted(); $this->assertDatabaseMissing('servers', ['id' => $server->id]); }); -test('force delete ignores exception from wings', function () { +test('force delete ignores exception from wings', function (): void { $server = $this->createServerModel(); $this->daemonServerRepository->throwable = new DaemonConnectionException(Http::failedRequest([], 500)); getService()->withForce()->delete($server); $this->daemonServerRepository->assertDeleted(); $this->assertDatabaseMissing('servers', ['id' => $server->id]); }); -test('exception while deleting stops process', function () { +test('a remote database drop failure is reported without blocking the deletion', function (): void { + $server = $this->createServerModel(); + $host = DatabaseHost::factory()->create(); + /** @var Database $failing */ + $failing = Database::factory()->create(['database_host_id' => $host->id, 'server_id' => $server->id]); + /** @var Database $other */ + $other = Database::factory()->create(['database_host_id' => $host->id, 'server_id' => $server->id]); + $server->refresh(); + $this->gateway->throwOn['dropDatabase'] = new Exception(); + $reported = []; + $this->app->make(ExceptionHandler::class)->reportable(function (Exception $exception) use (&$reported): bool { + $reported[] = $exception; + + return false; + }); + + getService()->delete($server); + + $this->daemonServerRepository->assertDeleted(); + $this->assertDatabaseMissing('servers', ['id' => $server->id]); + $this->assertDatabaseMissing('databases', ['id' => $failing->id]); + $this->assertDatabaseMissing('databases', ['id' => $other->id]); + // Every database is still attempted after the first drop fails. + expect($this->gateway->count('dropDatabase'))->toBe(2) + ->and($reported)->toHaveCount(2); +}); +test('remote databases are dropped after the server rows are deleted', function (): void { $server = $this->createServerModel(); $host = DatabaseHost::factory()->create(); /** @var Database $db */ $db = Database::factory()->create(['database_host_id' => $host->id, 'server_id' => $server->id]); $server->refresh(); - $this->gateway->throwOn['dropDatabase'] = new Exception(); - try { - getService()->delete($server); - $this->fail('Expected Exception to be thrown.'); - } catch (Exception) { - } - $this->daemonServerRepository->assertDeleted(); - $this->assertDatabaseHas('servers', ['id' => $server->id]); - $this->assertDatabaseHas('databases', ['id' => $db->id]); + $serverExisted = null; + $this->app->instance(DeletesDatabases::class, new class($serverExisted, $server->id) implements DeletesDatabases + { + public function __construct(private ?bool &$serverExisted, private readonly int $serverId) {} + + public function delete(Database $database): bool + { + $this->serverExisted = Server::query()->whereKey($this->serverId)->exists(); + + return true; + } + }); + + getService()->delete($server); + + expect($serverExisted)->toBeFalse(); + $this->assertDatabaseMissing('databases', ['id' => $db->id]); }); -test('exception while deleting databases does not abort if force deleted', function () { +test('exception while deleting databases does not abort if force deleted', function (): void { $server = $this->createServerModel(); $host = DatabaseHost::factory()->create(); /** @var Database $db */ @@ -94,12 +132,10 @@ test('exception while deleting databases does not abort if force deleted', funct }); function getService(): DeletesServers { - return (function () { - return $this->app->make(DeletesServers::class); - })->call(pterodactylTestCase()); + return (fn () => $this->app->make(DeletesServers::class))->call(pterodactylTestCase()); } -test('deleting a server reads database hosts once for all databases', function () { +test('deleting a server reads database hosts once for all databases', function (): void { $server = $this->createServerModel(); $host = DatabaseHost::factory()->create(['node_id' => $server->node_id]); Database::factory()->count(10)->create(['server_id' => $server->id, 'database_host_id' => $host->id]); @@ -114,15 +150,17 @@ test('deleting a server reads database hosts once for all databases', function ( } finally { DB::disableQueryLog(); } + expect($gateway->count('dropDatabase'))->toBe(10); expect($gateway->count('dropUser'))->toBe(10); expect($gateway->count('flush'))->toBe(10); + $this->daemonServerRepository->assertDeleted(); $this->assertDatabaseMissing('servers', ['id' => $server->id]); $this->assertDatabaseMissing('databases', ['server_id' => $server->id]); }); -test('a deleted server is reported to operation listeners by uuid only', function () { +test('a deleted server is reported to operation listeners by uuid only', function (): void { Event::fake([OperationCompleted::class]); $server = $this->createServerModel(); $kept = $this->createServerModel(); @@ -131,6 +169,7 @@ test('a deleted server is reported to operation listeners by uuid only', functio getService()->delete($kept); } catch (DaemonConnectionException) { } + $this->daemonServerRepository->throwable = null; getService()->delete($server); diff --git a/tests/Integration/Api/Admin/Nodes/AllocationControllerTest.php b/tests/Integration/Api/Admin/Nodes/AllocationControllerTest.php index 354c35a41..ce401970f 100644 --- a/tests/Integration/Api/Admin/Nodes/AllocationControllerTest.php +++ b/tests/Integration/Api/Admin/Nodes/AllocationControllerTest.php @@ -133,6 +133,8 @@ test('bulk delete allocations', function (): void { test('ip block delete allocations', function (): void { $block = Allocation::factory()->times(2)->create(['node_id' => $this->node->id, 'ip' => '10.0.0.5']); $other = Allocation::factory()->create(['node_id' => $this->node->id, 'ip' => '10.0.0.6']); + $assigned = $this->createServerModel(['node_id' => $this->node->id])->allocation; + $assigned->forceFill(['ip' => '10.0.0.5'])->save(); $response = $this->deleteJson(route('api.admin.nodes.allocations.block', ['node' => $this->node->id]), ['ip' => '10.0.0.5']); $response->assertStatus(Response::HTTP_NO_CONTENT); foreach ($block as $allocation) { @@ -140,6 +142,7 @@ test('ip block delete allocations', function (): void { } $this->assertDatabaseHas('allocations', ['id' => $other->id]); + $this->assertDatabaseHas('allocations', ['id' => $assigned->id]); }); test('bulk delete requires ids', function (): void { $response = $this->deleteJson(route('api.admin.nodes.allocations.bulk-delete', ['node' => $this->node->id]), []); diff --git a/tests/Integration/Api/Admin/Servers/DatabaseControllerTest.php b/tests/Integration/Api/Admin/Servers/DatabaseControllerTest.php index 06123d440..543628b12 100644 --- a/tests/Integration/Api/Admin/Servers/DatabaseControllerTest.php +++ b/tests/Integration/Api/Admin/Servers/DatabaseControllerTest.php @@ -12,6 +12,7 @@ use Pterodactyl\Models\DatabaseHost; use Pterodactyl\Services\Databases\DatabaseHostGateway; use Pterodactyl\Tests\Integration\Api\Admin\AdminApiIntegrationTestCase; use Pterodactyl\Tests\Support\Fakes\FakeDatabaseHostGateway; +use RuntimeException; use function pterodactylTestCase; @@ -108,6 +109,22 @@ test('rotate password', function (): void { $gateway->assertFlushed(1); expect($gateway->count('createUser'))->toBe(1); + $this->assertDatabaseHas('activity_logs', ['event' => 'admin:server-database.rotate-password']); +}); +test('a failed password rotation keeps the stored password and logs no activity', function (): void { + $server = $this->createServerModel(); + $host = DatabaseHost::factory()->create(); + $database = Database::factory()->create(['server_id' => $server->id, 'database_host_id' => $host->id]); + $password = $database->password; + $this->app->instance(DatabaseHostGateway::class, $gateway = new FakeDatabaseHostGateway()); + $gateway->throwOn['createUser'] = new RuntimeException('remote failure'); + $this->withoutExceptionHandling(); + + expect(fn () => $this->postJson(route('api.admin.servers.databases.rotate-password', ['server' => $server->id, 'database' => hashid($database->id)]))) + ->toThrow(RuntimeException::class); + + expect($database->refresh()->password)->toBe($password); + $this->assertDatabaseMissing('activity_logs', ['event' => 'admin:server-database.rotate-password']); }); test('rotate password database not on server', function (): void { $server = $this->createServerModel(); diff --git a/tests/Integration/Api/Admin/Servers/ServerTransferControllerTest.php b/tests/Integration/Api/Admin/Servers/ServerTransferControllerTest.php index 2c1c30e25..7b568d38a 100644 --- a/tests/Integration/Api/Admin/Servers/ServerTransferControllerTest.php +++ b/tests/Integration/Api/Admin/Servers/ServerTransferControllerTest.php @@ -5,6 +5,8 @@ declare(strict_types=1); namespace Pterodactyl\Tests\Pest\Integration\Api\Admin\Servers\ServerTransferControllerTest; use Illuminate\Http\Response; +use Illuminate\Support\Facades\Http; +use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException; use Pterodactyl\Models\Allocation; use Pterodactyl\Models\Node; use Pterodactyl\Models\Server; @@ -131,3 +133,23 @@ test('non admin forbidden', function (): void { $response = $this->postJson(route('api.admin.servers.transfer', ['server' => $server->id]), []); $this->assertAccessDeniedJson($response); }); + +test('a transfer wings rejects is marked failed and releases the target allocations', function (): void { + $server = $this->createServerModel(); + /** @var Node $targetNode */ + $targetNode = Node::factory()->create(['location_id' => $server->node->location_id, 'memory' => 102400, 'disk' => 102400]); + /** @var Allocation $primary */ + $primary = Allocation::factory()->create(['node_id' => $targetNode->id, 'server_id' => null]); + /** @var Allocation $additional */ + $additional = Allocation::factory()->create(['node_id' => $targetNode->id, 'server_id' => null]); + $fake = new FakeDaemonTransfer; + $fake->throwable = new DaemonConnectionException(Http::failedRequest([], 500)); + + $response = $this->postJson(route('api.admin.servers.transfer', ['server' => $server->id]), ['node_id' => $targetNode->id, 'allocation_id' => $primary->id, 'allocation_additional' => [$additional->id]]); + + expect($response->status())->toBeGreaterThanOrEqual(400); + $this->assertDatabaseHas('server_transfers', ['server_id' => $server->id, 'new_node' => $targetNode->id, 'successful' => false]); + $this->assertDatabaseHas('allocations', ['id' => $primary->id, 'server_id' => null]); + $this->assertDatabaseHas('allocations', ['id' => $additional->id, 'server_id' => null]); + $this->assertDatabaseHas('servers', ['id' => $server->id, 'node_id' => $server->node_id]); +}); diff --git a/tests/Integration/Api/Admin/Users/UserControllerTest.php b/tests/Integration/Api/Admin/Users/UserControllerTest.php index fe57308ea..3278ccead 100644 --- a/tests/Integration/Api/Admin/Users/UserControllerTest.php +++ b/tests/Integration/Api/Admin/Users/UserControllerTest.php @@ -6,6 +6,7 @@ namespace Pterodactyl\Tests\Pest\Integration\Api\Admin\Users\UserControllerTest; use Illuminate\Http\Response; use Illuminate\Testing\Assert; +use Pterodactyl\Contracts\Users\DisablesTwoFactor; use Pterodactyl\Models\Subuser; use Pterodactyl\Models\User; use Pterodactyl\Tests\Integration\Api\Admin\AdminApiIntegrationTestCase; @@ -113,6 +114,24 @@ test('disable two factor', function (): void { $response->assertStatus(Response::HTTP_NO_CONTENT); $this->assertDatabaseHas('users', ['id' => $user->id, 'use_totp' => false, 'totp_secret' => null]); }); +test('disable two factor goes through the contract', function (): void { + $user = User::factory()->create(['use_totp' => true, 'totp_secret' => 'encrypted-secret']); + $spy = new class implements DisablesTwoFactor + { + public ?int $disabled = null; + + public function disable(User $user): void + { + $this->disabled = $user->id; + } + }; + $this->app->instance(DisablesTwoFactor::class, $spy); + + $this->postJson(route('api.admin.users.disable-2fa', ['user' => $user->id]))->assertStatus(Response::HTTP_NO_CONTENT); + + expect($spy->disabled)->toBe($user->id); + $this->assertDatabaseHas('users', ['id' => $user->id, 'use_totp' => true]); +}); test('delete user', function (): void { $user = User::factory()->create(); $this->assertDatabaseHas('users', ['id' => $user->id]); diff --git a/tests/Integration/Api/Client/TwoFactorControllerTest.php b/tests/Integration/Api/Client/TwoFactorControllerTest.php index 4ed2a60d6..033627ed7 100644 --- a/tests/Integration/Api/Client/TwoFactorControllerTest.php +++ b/tests/Integration/Api/Client/TwoFactorControllerTest.php @@ -76,7 +76,7 @@ test('two factor can be enabled on account', function () { test('two factor can be disabled on account', function () { Carbon::setTestNow(Carbon::now()); /** @var User $user */ - $user = User::factory()->create(['use_totp' => true]); + $user = User::factory()->create(['use_totp' => true, 'totp_secret' => encrypt('SECRET'), 'totp_authenticated_at' => Carbon::now()]); $response = $this->actingAs($user)->postJson('/api/client/account/two-factor/disable', ['password' => 'invalid']); $response->assertStatus(Response::HTTP_BAD_REQUEST); $response->assertJsonPath('errors.0.code', 'InvalidPasswordProvidedException'); @@ -85,8 +85,8 @@ test('two factor can be disabled on account', function () { $response->assertStatus(Response::HTTP_NO_CONTENT); $user = $user->refresh(); expect($user->use_totp)->toBeFalse(); - expect($user->totp_authenticated_at)->not->toBeNull(); - expect($user->totp_authenticated_at->toAtomString())->toBe(Carbon::now()->toAtomString()); + expect($user->totp_secret)->toBeNull(); + expect($user->totp_authenticated_at)->toBeNull(); }); test('no error is returned if two factor is not enabled', function () { Carbon::setTestNow(Carbon::now());