backup actions

This commit is contained in:
robert dennis
2026-10-12 05:18:56 -04:00
parent 89d8cd8717
commit ac7f9a889a
17 changed files with 353 additions and 135 deletions
+60 -7
View File
@@ -7,6 +7,8 @@ namespace Pterodactyl\Actions\Backups;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Backups\CompletesBackups;
use Pterodactyl\Events\Server\OperationCompleted;
use Pterodactyl\Exceptions\DisplayException;
@@ -15,36 +17,87 @@ use Pterodactyl\Extensions\Filesystem\S3Filesystem;
use Pterodactyl\Models\Backup;
use Throwable;
/**
* @phpstan-type CompletionAttributes array{successful: bool, checksum: string|null, checksum_type: string|null, size: int, parts: list<MultipartUploadPart>|null}
*/
final readonly class CompleteBackup implements CompletesBackups
{
public function __construct(private BackupManager $backupManager) {}
/**
* The outcome Wings reports for a backup, under the field names of its protocol. A
* successful backup carries its checksum, the checksum's type and its size in bytes. An
* S3 backup may list the parts of its multipart upload.
*
* @return NormalizedValidationRules
*/
public static function rules(): array
{
return [
'successful' => ['required', 'boolean'],
'checksum' => ['nullable', 'string', 'required_if:successful,true'],
'checksum_type' => ['nullable', 'string', 'required_if:successful,true'],
'size' => ['nullable', 'integer', 'required_if:successful,true'],
'parts' => ['nullable', 'array', 'list'],
'parts.*.etag' => ['required', 'string'],
'parts.*.part_number' => ['required', 'integer'],
];
}
/**
* Validates a reported outcome and returns the outcome it describes. A size left out is
* 0, and parts left out or null are null, so the upload's parts are listed from S3.
*
* @param ActionInput $input
* @return CompletionAttributes
*/
public static function attributes(array $input): array
{
$input = Validator::make($input, self::rules())->safe();
return [
'successful' => $input->boolean('successful'),
'checksum' => $input->filled('checksum') ? $input->string('checksum')->toString() : null,
'checksum_type' => $input->filled('checksum_type') ? $input->string('checksum_type')->toString() : null,
'size' => $input->integer('size'),
'parts' => $input->filled('parts')
? array_map(fn (int|string $key): array => [
'etag' => $input->string('parts.'.$key.'.etag')->toString(),
'part_number' => $input->integer('parts.'.$key.'.part_number'),
], array_keys($input->array('parts')))
: null,
];
}
/**
* Records the outcome Wings reported for a backup and, for S3 storage, closes the
* multipart upload it belongs to.
*
* @param BackupCompletionData $data
* @param ActionInput $input
*
* @throws DisplayException
* @throws ValidationException
* @throws Throwable
*/
public function complete(Backup $backup, array $data): void
public function complete(Backup $backup, array $input): void
{
DB::transaction(function () use ($backup, $data): void {
$successful = $data['successful'];
$attributes = self::attributes($input);
DB::transaction(function () use ($backup, $attributes): void {
$successful = $attributes['successful'];
$backup->fill([
'is_successful' => $successful,
// A failed backup is unlocked so it can be deleted easily.
'is_locked' => $successful && $backup->is_locked,
'checksum' => $successful ? ($data['checksum_type'].':'.$data['checksum']) : null,
'bytes' => $successful ? $data['size'] : 0,
'checksum' => $successful ? ($attributes['checksum_type'].':'.$attributes['checksum']) : null,
'bytes' => $successful ? $attributes['size'] : 0,
'completed_at' => CarbonImmutable::now(),
])->save();
$adapter = $this->backupManager->adapter();
if ($adapter instanceof S3Filesystem) {
$this->completeMultipartUpload($backup, $adapter, $successful, $data['parts']);
$this->completeMultipartUpload($backup, $adapter, $successful, $attributes['parts']);
}
Event::dispatch(new OperationCompleted($backup->server->uuid, 'backup', $successful, $backup->uuid));
+51 -10
View File
@@ -7,6 +7,8 @@ namespace Pterodactyl\Actions\Backups;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Backups\DeletesBackups;
use Pterodactyl\Contracts\Backups\InitiatesBackups;
use Pterodactyl\Exceptions\Service\Backup\TooManyBackupsException;
@@ -22,7 +24,7 @@ use UnexpectedValueException;
final class InitiateBackup implements InitiatesBackups
{
/** @var array<int, string> */
/** @var list<string> */
private array $ignoredFiles = [];
private bool $isLocked = false;
@@ -32,6 +34,44 @@ final class InitiateBackup implements InitiatesBackups
private readonly BackupManager $backupManager,
) {}
/**
* A backup's fields: an optional name, whether it is locked against deletion, and the
* files and folders to leave out of it.
*
* @return NormalizedValidationRules
*/
public static function rules(): array
{
return [
'name' => ['nullable', 'string', 'max:191'],
'is_locked' => ['nullable', 'boolean'],
'ignored_files' => ['nullable', 'array', 'list'],
'ignored_files.*' => ['string'],
];
}
/**
* Validates backup input and returns the backup it describes. A name left out or blank
* is null, and empty entries are dropped from the ignored files.
*
* @param ActionInput $input
* @return array{name: string|null, is_locked: bool, ignored_files: list<string>}
*/
public static function attributes(array $input): array
{
$input = Validator::make($input, self::rules())->safe();
// Don't use the PHP empty function here in case anything that is "empty" by default
// (0, false, etc.) was passed as a file or folder name.
$ignored = array_map(fn (int|string $key): string => $input->string('ignored_files.'.$key)->toString(), array_keys($input->array('ignored_files')));
return [
'name' => $input->filled('name') ? $input->string('name')->toString() : null,
'is_locked' => $input->boolean('is_locked'),
'ignored_files' => array_values(array_filter($ignored, fn (string $file): bool => $file !== '')),
];
}
/**
* Set if the backup should be locked once it is created which will prevent
* its deletion by users or automated system processes.
@@ -44,16 +84,14 @@ final class InitiateBackup implements InitiatesBackups
}
/**
* Sets the files to be ignored by this backup.
* Sets the files to be ignored by this backup. They are validated when the backup is
* initiated.
*
* @param list<string>|null $ignored
*/
public function setIgnoredFiles(?array $ignored): InitiatesBackups
{
// Set the ignored files to be any values that are not empty in the array. Don't use
// the PHP empty function here incase anything that is "empty" by default (0, false, etc.)
// were passed as a file or folder name.
$this->ignoredFiles = ($ignored) === null ? [] : array_filter($ignored, fn (string $value): bool => $value !== '');
$this->ignoredFiles = $ignored ?? [];
return $this;
}
@@ -69,10 +107,13 @@ final class InitiateBackup implements InitiatesBackups
* @throws Throwable
* @throws TooManyBackupsException
* @throws TooManyRequestsHttpException
* @throws ValidationException
*/
public function initiate(Server $server, ?string $name = null, bool $override = false): Backup
{
[$backup, $rotated] = DB::transaction(/** @return array{Backup, Collection<int, Backup>} */ function () use ($server, $name, $override): array {
$attributes = self::attributes(['name' => $name, 'is_locked' => $this->isLocked, 'ignored_files' => $this->ignoredFiles]);
[$backup, $rotated] = DB::transaction(/** @return array{Backup, Collection<int, Backup>} */ function () use ($server, $attributes, $override): array {
$limit = JsonValueGuard::integer(config('backups.throttles.limit'));
$period = JsonValueGuard::integer(config('backups.throttles.period'));
if ($period > 0) {
@@ -122,10 +163,10 @@ final class InitiateBackup implements InitiatesBackups
$backup = $server->backups()->create([
'uuid' => Uuid::uuid4()->toString(),
'name' => mb_trim($name ?? '') ?: sprintf('Backup at %s', CarbonImmutable::now()->toDateTimeString()),
'ignored_files' => array_values($this->ignoredFiles),
'name' => mb_trim($attributes['name'] ?? '') ?: sprintf('Backup at %s', CarbonImmutable::now()->toDateTimeString()),
'ignored_files' => $attributes['ignored_files'],
'disk' => $this->backupManager->getDefaultAdapter(),
'is_locked' => $this->isLocked,
'is_locked' => $attributes['is_locked'],
]);
return [$backup, $rotated];
+13
View File
@@ -20,6 +20,19 @@ final readonly class RestoreBackup implements RestoresBackups
private GeneratesBackupDownloadLinks $downloadLink,
) {}
/**
* A restore's fields: whether the server's files are deleted before the backup is
* unpacked over them. The action takes the flag as a bool, which always meets them.
*
* @return NormalizedValidationRules
*/
public static function rules(): array
{
return [
'truncate' => ['required', 'boolean'],
];
}
/**
* Marks the server as restoring and asks Wings to unpack the backup over its files.
* S3 backups are handed to Wings as a signed download link.
+11 -2
View File
@@ -4,15 +4,24 @@ declare(strict_types=1);
namespace Pterodactyl\Contracts\Backups;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Models\Backup;
use Throwable;
interface CompletesBackups
{
/** @param BackupCompletionData $data
/**
* Record the outcome Wings reported for a backup. The input is validated here, so it can
* come straight from any caller, under the field names of the Wings protocol. A
* successful backup needs its checksum, checksum type and size; S3 parts left out are
* listed from S3 when the multipart upload is completed.
*
* @param ActionInput $input successful, checksum, checksum_type, size and optionally parts, each with an etag and part_number
*
* @throws DisplayException
* @throws ValidationException
* @throws Throwable
*/
public function complete(Backup $backup, array $data): void;
public function complete(Backup $backup, array $input): void;
}
+14 -1
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pterodactyl\Contracts\Backups;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Models\Backup;
use Pterodactyl\Models\Server;
@@ -11,8 +12,20 @@ interface InitiatesBackups
{
public function setIsLocked(bool $isLocked): self;
/** @param list<string>|null $ignored */
/**
* The files and folders to leave out of the backup. Empty entries are dropped.
*
* @param list<string>|null $ignored
*/
public function setIgnoredFiles(?array $ignored): self;
/**
* Start a backup of the server on Wings. The name and the ignored files are validated
* here, so they can come straight from any caller: a name is at most 191 characters,
* and the ignored files are a list of strings, reported under `ignored_files`. A name
* left out or blank becomes one with the time the backup started.
*
* @throws ValidationException
*/
public function initiate(Server $server, ?string $name = null, bool $override = false): Backup;
}
@@ -69,9 +69,7 @@ class BackupController extends ClientApiController
#[ResponseFromTransformer(BackupTransformer::class, Backup::class, description: 'Server backups returned.', collection: true, resourceKey: 'backup', paginate: [IlluminatePaginatorAdapter::class, 20], meta: ['backup_count' => 1])]
public function index(ListBackupsRequest $request, Server $server): array
{
$validated = $request->payload();
return Fractal::collection($server->backups()->paginate($validated['per_page']))
return Fractal::collection($server->backups()->paginate($request->perPage()))
->transformWith($this->getTransformer(BackupTransformer::class))
->addMeta([
'backup_count' => $server->backups()->nonFailed()->count(),
@@ -94,19 +92,18 @@ class BackupController extends ClientApiController
public function store(StoreBackupRequest $request, InitiatesBackups $initiate, Server $server): array
{
$user = $this->authenticatedUser($request);
$validated = $request->payload();
$action = $initiate
->setIgnoredFiles(explode(PHP_EOL, $validated['ignored'] ?? ''));
$validated = $request->safe();
$action = $initiate->setIgnoredFiles($request->ignoredFiles());
// Only set the lock status if the user even has permission to delete backups,
// otherwise ignore this status. This gets a little funky since it isn't clear
// how best to allow a user to create a backup that is locked without also preventing
// them from just filling up a server with backups that can never be deleted?
if ($user->can(Permissions::BackupDelete->value, $server)) {
$action->setIsLocked($validated['is_locked']);
$action->setIsLocked($validated->boolean('is_locked'));
}
$backup = $action->initiate($server, $validated['name']);
$backup = $action->initiate($server, $validated->filled('name') ? $validated->string('name')->toString() : null);
Activity::event('server:backup.start')->subject($backup)->property([
'name' => $backup->name,
@@ -213,8 +210,7 @@ class BackupController extends ClientApiController
public function restore(RestoreBackupRequest $request, RestoresBackups $restore, Server $server, Backup $backup): JsonResponse
{
$user = $this->authenticatedUser($request);
$validated = $request->payload();
$truncate = $validated['truncate'];
$truncate = $request->safe()->boolean('truncate');
$restore->restore($server, $backup, $user, $truncate);
@@ -39,11 +39,9 @@ class BackupStatusController extends Controller
throw_if($model->is_successful, BadRequestHttpException::class, 'Cannot update the status of a backup that is already marked as completed.');
$data = $request->payload();
$completeBackup->complete($model, $request->actionInput());
$completeBackup->complete($model, $data);
Activity::event($data['successful'] ? 'server:backup.complete' : 'server:backup.fail')
Activity::event($request->safe()->boolean('successful') ? 'server:backup.complete' : 'server:backup.fail')
->subject($model, $model->server)
->property('name', $model->name)
->log();
@@ -62,9 +60,7 @@ class BackupStatusController extends Controller
{
$model = $restoreStatus->restoreStatus($backup, RemoteRequestNode::get($request));
$successful = $request->payload()['successful'];
Activity::event($successful ? 'server:backup.restore-complete' : 'server:backup.restore-failed')
Activity::event($request->safe()->boolean('successful') ? 'server:backup.restore-complete' : 'server:backup.restore-failed')
->subject($model, $model->server)
->property('name', $model->name)
->log();
@@ -4,11 +4,9 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Client\Servers\Backups;
use Illuminate\Support\Arr;
use Pterodactyl\Contracts\Http\ClientPermissionsRequest;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
use Pterodactyl\Support\JsonValueGuard;
class ListBackupsRequest extends ClientApiRequest implements ClientPermissionsRequest
{
@@ -28,16 +26,10 @@ class ListBackupsRequest extends ClientApiRequest implements ClientPermissionsRe
}
/**
* @return array{per_page: int}
* The number of backups to list per page: 20 unless one is given, and at most 50.
*/
public function payload(): array
public function perPage(int $default = 20): int
{
$data = parent::validated();
$perPage = Arr::get($data, 'per_page', 20);
return [
'per_page' => min(JsonValueGuard::integer($perPage), 50),
];
return min($this->safe()->integer('per_page', $default), 50);
}
}
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Client\Servers\Backups;
use Pterodactyl\Actions\Backups\RestoreBackup;
use Pterodactyl\Contracts\Http\ClientPermissionsRequest;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
@@ -20,16 +21,6 @@ class RestoreBackupRequest extends ClientApiRequest implements ClientPermissions
*/
public function rules(): array
{
return ['truncate' => ['required', 'boolean']];
}
/**
* @return array{truncate: bool}
*/
public function payload(): array
{
return [
'truncate' => $this->boolean('truncate'),
];
return RestoreBackup::rules();
}
}
@@ -4,11 +4,10 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Client\Servers\Backups;
use Illuminate\Support\Arr;
use Pterodactyl\Actions\Backups\InitiateBackup;
use Pterodactyl\Contracts\Http\ClientPermissionsRequest;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
use Pterodactyl\Support\JsonValueGuard;
class StoreBackupRequest extends ClientApiRequest implements ClientPermissionsRequest
{
@@ -18,28 +17,30 @@ class StoreBackupRequest extends ClientApiRequest implements ClientPermissionsRe
}
/**
* The backup's name and lock take the action's rules. The files to ignore are sent as
* one string, a file or folder per line, which ignoredFiles() splits into the list the
* action takes.
*
* @return ValidationRules
*/
public function rules(): array
{
$rules = InitiateBackup::rules();
return [
'name' => ['nullable', 'string', 'max:191'],
'is_locked' => ['nullable', 'boolean'],
'name' => $rules['name'],
'is_locked' => $rules['is_locked'],
'ignored' => ['nullable', 'string'],
];
}
/**
* @return array{name: string|null, is_locked: bool, ignored: string|null}
* The files and folders to leave out of the backup, one per line of the ignored field.
*
* @return list<string>
*/
public function payload(): array
public function ignoredFiles(): array
{
$data = parent::validated();
return [
'name' => JsonValueGuard::nullableString(Arr::get($data, 'name')),
'is_locked' => $this->boolean('is_locked'),
'ignored' => JsonValueGuard::nullableString(Arr::get($data, 'ignored')),
];
return explode(PHP_EOL, $this->safe()->string('ignored')->toString());
}
}
@@ -4,64 +4,16 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Requests\Api\Remote;
use Illuminate\Foundation\Http\FormRequest;
use Pterodactyl\Support\JsonValueGuard;
use UnexpectedValueException;
use Pterodactyl\Actions\Backups\CompleteBackup;
use Pterodactyl\Http\Requests\Api\ApiRequest;
class ReportBackupCompleteRequest extends FormRequest
class ReportBackupCompleteRequest extends ApiRequest
{
/**
* @return ValidationRules
*/
public function rules(): array
{
return [
'successful' => ['required', 'boolean'],
'checksum' => ['nullable', 'string', 'required_if:successful,true'],
'checksum_type' => ['nullable', 'string', 'required_if:successful,true'],
'size' => ['nullable', 'integer', 'required_if:successful,true'],
'parts' => ['nullable', 'array', 'list'],
'parts.*.etag' => ['required', 'string'],
'parts.*.part_number' => ['required', 'integer'],
];
}
/**
* @return BackupCompletionData
*/
public function payload(): array
{
return [
'successful' => $this->boolean('successful'),
'checksum' => JsonValueGuard::nullableString($this->input('checksum')),
'checksum_type' => JsonValueGuard::nullableString($this->input('checksum_type')),
'size' => $this->integer('size'),
'parts' => $this->parts(),
];
}
/**
* @return list<MultipartUploadPart>|null
*/
private function parts(): ?array
{
$parts = $this->input('parts');
if ($parts === null) {
return null;
}
throw_if(! is_array($parts) || ! array_is_list($parts), UnexpectedValueException::class, 'Multipart upload parts must be a list.');
$normalized = [];
foreach ($parts as $part) {
throw_unless(is_array($part), UnexpectedValueException::class, 'Each multipart upload part must be a string-keyed array.');
$normalized[] = [
'etag' => JsonValueGuard::string($part['etag'] ?? null),
'part_number' => JsonValueGuard::integer($part['part_number'] ?? null),
];
}
return $normalized;
return CompleteBackup::rules();
}
}
@@ -14,6 +14,8 @@ class ReportBackupRestoreRequest extends FormRequest
}
/**
* Whether the restore succeeded only picks the activity event that is logged.
*
* @return ValidationRules
*/
public function rules(): array
@@ -22,14 +24,4 @@ class ReportBackupRestoreRequest extends FormRequest
'successful' => ['required', 'boolean'],
];
}
/**
* @return array{successful: bool}
*/
public function payload(): array
{
return [
'successful' => $this->boolean('successful'),
];
}
}
-1
View File
@@ -84,7 +84,6 @@ parameters:
MultipartUploadPart: 'array{etag: string, part_number: int}'
SftpAuthenticationData: 'array{type: string|null, username: string, password: string}'
ServerTransferData: 'array{node_id: int, allocation_id: int, allocation_additional: list<int>}'
BackupCompletionData: 'array{successful: bool, checksum: string|null, checksum_type: string|null, size: int, parts: list<MultipartUploadPart>|null}'
BackupUploadParts: 'array{parts: list<string>, part_size: int}'
GeneralSettingsData: "array{'app:name': string, 'pterodactyl:auth:2fa_required': int, 'app:locale': string}"
AdvancedSettingsData: "array{'recaptcha:enabled': string, 'recaptcha:secret_key'?: string, 'recaptcha:website_key': string, 'pterodactyl:guzzle:timeout': int, 'pterodactyl:guzzle:connect_timeout': int, 'pterodactyl:client_features:allocations:enabled': string, 'pterodactyl:client_features:allocations:range_start': int|null, 'pterodactyl:client_features:allocations:range_end': int|null}"
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Integration\Actions\Backups\CompleteBackupTest;
use Aws\MockHandler;
use Aws\Result;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Backups\CompletesBackups;
use Pterodactyl\Extensions\Backups\BackupManager;
use Pterodactyl\Models\Backup;
use Pterodactyl\Models\Server;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Tests\Support\Fakes\FakeBackupManager;
use Pterodactyl\Tests\Support\Fakes\FakeS3Filesystem;
uses(IntegrationTestCase::class, DatabaseTransactions::class);
/** A backup of the server that Wings is still running. */
function runningBackup(Server $server, array $attributes = []): Backup
{
return Backup::factory()->create([...['server_id' => $server->id, 'is_successful' => false, 'completed_at' => null], ...$attributes]);
}
test('outcomes reported without the http api meet the same rules', function (array $input, array $fields): void {
$backup = runningBackup($this->createServerModel());
try {
$this->app->make(CompletesBackups::class)->complete($backup, $input);
$this->fail('The backup was completed.');
} catch (ValidationException $validationException) {
expect(array_keys($validationException->errors()))->toBe($fields);
}
expect($backup->fresh()->completed_at)->toBeNull();
})->with([
'no outcome' => [[], ['successful']],
'an outcome that is not a boolean' => [['successful' => 'yes', 'checksum' => 'abc', 'checksum_type' => 'sha1', 'size' => 1], ['successful']],
'a success without its checksum or size' => [['successful' => true], ['checksum', 'checksum_type', 'size']],
'a size that is not an integer' => [['successful' => true, 'checksum' => 'abc', 'checksum_type' => 'sha1', 'size' => '10.5'], ['size']],
'parts that are not a list' => [['successful' => false, 'parts' => ['first' => ['etag' => 'a', 'part_number' => 1]]], ['parts']],
'a part without its number' => [['successful' => false, 'parts' => [['etag' => 'a']]], ['parts.0.part_number']],
]);
test('values are coerced the way laravel validates them', function (bool|int|string $successful): void {
$backup = runningBackup($this->createServerModel(), ['is_locked' => true]);
$this->app->make(CompletesBackups::class)->complete($backup, ['successful' => $successful, 'checksum' => 'abc123', 'checksum_type' => 'sha1', 'size' => '1024']);
$backup->refresh();
expect($backup->is_successful)->toBeTrue()
->and($backup->is_locked)->toBeTrue()
->and($backup->checksum)->toBe('sha1:abc123')
->and($backup->bytes)->toBe(1024)
->and($backup->completed_at)->not->toBeNull();
})->with([true, 1, '1']);
test('a failed backup is unlocked and keeps no checksum or size', function (bool|int|string $successful): void {
$backup = runningBackup($this->createServerModel(), ['is_locked' => true]);
$this->app->make(CompletesBackups::class)->complete($backup, ['successful' => $successful, 'checksum' => 'abc123', 'checksum_type' => 'sha1', 'size' => 1024]);
$backup->refresh();
expect($backup->is_successful)->toBeFalse()
->and($backup->is_locked)->toBeFalse()
->and($backup->checksum)->toBeNull()
->and($backup->bytes)->toBe(0)
->and($backup->completed_at)->not->toBeNull();
})->with([false, 0, '0']);
test('the parts wings uploaded close the multipart upload, and parts left out are listed from s3', function (): void {
$filesystem = new FakeS3Filesystem('backups');
$mock = new MockHandler([new Result([]), new Result(['Parts' => [['ETag' => 'listed', 'PartNumber' => 1]]]), new Result([])]);
$filesystem->getClient()->getHandlerList()->setHandler($mock);
$this->app->instance(BackupManager::class, new FakeBackupManager($filesystem));
$completes = $this->app->make(CompletesBackups::class);
$completes->complete(runningBackup($this->createServerModel(), ['disk' => Backup::ADAPTER_AWS_S3, 'upload_id' => 'upload-1']), [
'successful' => true, 'checksum' => 'abc123', 'checksum_type' => 'sha1', 'size' => 1024,
'parts' => [['etag' => 'first', 'part_number' => '1'], ['etag' => 'second', 'part_number' => 2]],
]);
expect($mock->getLastCommand()->getName())->toBe('CompleteMultipartUpload')
->and($mock->getLastCommand()['UploadId'])->toBe('upload-1')
->and($mock->getLastCommand()['MultipartUpload']['Parts'])->toBe([['ETag' => 'first', 'PartNumber' => 1], ['ETag' => 'second', 'PartNumber' => 2]]);
$completes->complete(runningBackup($this->createServerModel(), ['disk' => Backup::ADAPTER_AWS_S3, 'upload_id' => 'upload-2']), ['successful' => true, 'checksum' => 'abc123', 'checksum_type' => 'sha1', 'size' => 1024, 'parts' => null]);
expect($mock->getLastCommand()->getName())->toBe('CompleteMultipartUpload')
->and($mock->getLastCommand()['MultipartUpload']['Parts'])->toBe([['ETag' => 'listed', 'PartNumber' => 1]]);
});
@@ -7,6 +7,7 @@ namespace Pterodactyl\Tests\Pest\Integration\Actions\Backups\InitiateBackupTest;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Contracts\Backups\InitiatesBackups;
use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException;
use Pterodactyl\Exceptions\Service\Backup\TooManyBackupsException;
@@ -73,6 +74,46 @@ test('a backup rotated out by another request that is still pending is not count
expect(Backup::query()->where('server_id', $server->id)->count())->toBe(2);
});
test('backups initiated without the http api meet the same rules', function (?string $name, ?array $ignored, string $field): void {
$server = $this->createServerModel(['backup_limit' => 3]);
$fake = new FakeDaemonBackup;
try {
$this->app->make(InitiatesBackups::class)->setIgnoredFiles($ignored)->initiate($server, $name);
$this->fail('The backup was initiated.');
} catch (ValidationException $validationException) {
expect(array_keys($validationException->errors()))->toBe([$field]);
}
$fake->assertNothingHappened();
expect($server->backups()->exists())->toBeFalse();
})->with([
'a name that is too long' => [str_repeat('a', 192), null, 'name'],
'ignored files that are not a list' => ['Named', ['logs' => 'logs/'], 'ignored_files'],
'an ignored file that is not a string' => ['Named', ['logs/', ['cache/']], 'ignored_files.1'],
'an ignored file that is null' => ['Named', [null], 'ignored_files.0'],
]);
test('a backup keeps its ignored files without empty entries, and a blank name is replaced', function (): void {
$server = $this->createServerModel(['backup_limit' => 3]);
$fake = new FakeDaemonBackup;
$backup = $this->app->make(InitiatesBackups::class)
->setIgnoredFiles(['logs/', '', '0', 'cache/'])
->setIsLocked(true)
->initiate($server, ' ');
$fake->assertBackedUp($backup->uuid);
expect($backup->ignored_files)->toBe(['logs/', '0', 'cache/'])
->and($backup->is_locked)->toBeTrue()
->and($backup->name)->toStartWith('Backup at ');
$named = $this->app->make(InitiatesBackups::class)->initiate($server, 'Named');
expect($named->name)->toBe('Named')
->and($named->ignored_files)->toBe([])
->and($named->is_locked)->toBeFalse();
});
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]);
@@ -52,6 +52,23 @@ test('backup lock accepts null and every value the boolean rule allows', functio
->assertOk()
->assertJsonPath('attributes.is_locked', $expected);
})->with([[null, false], [1, true], ['1', true], [0, false]]);
test('backup ignores the files sent one per line and keeps its own rules', function (): void {
$user = User::factory()->create();
$server = $this->createServerModel(['owner_id' => $user->id, 'backup_limit' => 3]);
new FakeDaemonBackup;
$uuid = $this->actingAs($user)->postJson($this->link($server, '/backups'), ['name' => 'Ignoring', 'ignored' => "logs/\n\ncache/"])
->assertOk()
->json('attributes.uuid');
expect(Backup::query()->where('uuid', $uuid)->firstOrFail()->ignored_files)->toBe(['logs/', 'cache/']);
$this->actingAs($user)->postJson($this->link($server, '/backups'), ['name' => str_repeat('a', 192), 'is_locked' => 'yes', 'ignored' => ['logs/']])
->assertUnprocessable()
->assertJsonCount(3, 'errors')
->assertJsonPath('errors.0.meta.source_field', 'name')
->assertJsonPath('errors.1.meta.source_field', 'is_locked')
->assertJsonPath('errors.2.meta.source_field', 'ignored');
});
test('backup cannot be created past the server limit', function () {
$user = User::factory()->create();
$server = $this->createServerModel(['owner_id' => $user->id, 'backup_limit' => 1]);
@@ -76,6 +76,25 @@ test('node can mark a backup as completed', function () {
expect($backup->bytes)->toBe(1024);
expect($backup->completed_at)->not->toBeNull();
});
test('a backup report keeps the wings field names and rules', function () {
$server = $this->createServerModel();
$backup = Backup::factory()->create(['server_id' => $server->id, 'is_successful' => false, 'completed_at' => null]);
actingAsNode($server->node)->postJson("/api/remote/backups/{$backup->uuid}", ['successful' => true, 'parts' => [['etag' => 'a']]])
->assertUnprocessable()
->assertJsonCount(4, 'errors')
->assertJsonPath('errors.0.meta.source_field', 'checksum')
->assertJsonPath('errors.1.meta.source_field', 'checksum_type')
->assertJsonPath('errors.2.meta.source_field', 'size')
->assertJsonPath('errors.3.meta.source_field', 'parts.0.part_number');
expect($backup->refresh()->completed_at)->toBeNull();
actingAsNode($server->node)->postJson("/api/remote/backups/{$backup->uuid}", ['successful' => '0'])->assertNoContent();
$backup->refresh();
expect($backup->is_successful)->toBeFalse();
expect($backup->completed_at)->not->toBeNull();
expect($server->activity()->where('event', 'server:backup.fail')->exists())->toBeTrue();
});
test('completed backup cannot be reported again', function () {
$server = $this->createServerModel();
$backup = Backup::factory()->create(['server_id' => $server->id, 'is_successful' => true]);