diff --git a/app/Actions/Activity/IngestActivityLogs.php b/app/Actions/Activity/IngestActivityLogs.php index 14774f638..94b15346d 100644 --- a/app/Actions/Activity/IngestActivityLogs.php +++ b/app/Actions/Activity/IngestActivityLogs.php @@ -8,7 +8,9 @@ use DateTimeInterface; use Exception; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; +use Illuminate\Validation\ValidationException; use InvalidArgumentException; use Pterodactyl\Contracts\Activity\IngestsActivityLogs; use Pterodactyl\Models\ActivityLog; @@ -16,12 +18,78 @@ use Pterodactyl\Models\ActivityLogSubject; use Pterodactyl\Models\Node; use Pterodactyl\Models\Server; use Pterodactyl\Models\User; +use Pterodactyl\Support\JsonValueGuard; +/** + * @phpstan-type ActivityEvent array{user: string|null, server: string, event: string, metadata: array, ip: string|null, timestamp: string} + */ final class IngestActivityLogs implements IngestsActivityLogs { - /** @param ActivityEvents $events */ - public function ingest(Node $node, array $events): void + /** + * The activity Wings reports, under the field names of its protocol: `data` lists the + * events, each naming the server it happened on, the event, its metadata and when it + * happened, and optionally the user who caused it and their IP address. + * + * @return NormalizedValidationRules + */ + public static function rules(): array { + return [ + 'data' => ['required', 'array'], + 'data.*' => ['array'], + 'data.*.user' => ['sometimes', 'nullable', 'uuid'], + 'data.*.server' => ['required', 'uuid'], + 'data.*.event' => ['required', 'string'], + 'data.*.metadata' => ['present', 'nullable', 'array'], + 'data.*.ip' => ['sometimes', 'nullable', 'ip'], + 'data.*.timestamp' => ['required', 'string'], + ]; + } + + /** + * Validates reported activity and returns the events it lists. Metadata given as null + * is empty. + * + * @param ActionInput $input + * @return list + * + * @throws ValidationException + */ + public static function events(array $input): array + { + $input = Validator::make($input, self::rules())->safe(); + + $events = []; + foreach (array_keys($input->array('data')) as $key) { + $event = 'data.'.$key.'.'; + + // Metadata is whatever Wings recorded for the event, so Laravel's typed accessors + // have no type to give it; it is checked as the JSON object it was sent as. + $metadata = $input->array($event.'metadata'); + JsonValueGuard::assertPayload9($metadata); + + $events[] = [ + 'user' => $input->filled($event.'user') ? $input->string($event.'user')->toString() : null, + 'server' => $input->string($event.'server')->toString(), + 'event' => $input->string($event.'event')->toString(), + 'metadata' => $metadata, + 'ip' => $input->filled($event.'ip') ? $input->string($event.'ip')->toString() : null, + 'timestamp' => $input->string($event.'timestamp')->toString(), + ]; + } + + return $events; + } + + /** + * @param ActionInput $input + * + * @throws ValidationException + */ + public function ingest(Node $node, array $input): void + { + $events = self::events($input); + $tz = now()->getTimezone(); $servers = $node->servers()->whereIn('uuid', array_column($events, 'server'))->get()->keyBy('uuid'); $users = User::query()->whereIn('uuid', array_filter(array_column($events, 'user')))->get()->keyBy('uuid'); diff --git a/app/Actions/Servers/RecordServerInstallResult.php b/app/Actions/Servers/RecordServerInstallResult.php index 0abfb2e28..a31db25c8 100644 --- a/app/Actions/Servers/RecordServerInstallResult.php +++ b/app/Actions/Servers/RecordServerInstallResult.php @@ -17,6 +17,21 @@ final readonly class RecordServerInstallResult implements RecordsServerInstallRe { public function __construct(private ServerInstallService $serverInstallService) {} + /** + * An install report's fields, as Wings sends them: whether the install script + * succeeded, and whether it ran as a reinstall. The action takes both as bools, which + * always meet them. + * + * @return NormalizedValidationRules + */ + public static function rules(): array + { + return [ + 'successful' => ['present', 'boolean'], + 'reinstall' => ['sometimes', 'boolean'], + ]; + } + public function record(Request $request, string $uuid, bool $successful, bool $reinstall): Server { $server = $this->serverInstallService->resolveForNode($request, $uuid); diff --git a/app/Contracts/Activity/IngestsActivityLogs.php b/app/Contracts/Activity/IngestsActivityLogs.php index f82628692..8addf9bb9 100644 --- a/app/Contracts/Activity/IngestsActivityLogs.php +++ b/app/Contracts/Activity/IngestsActivityLogs.php @@ -4,10 +4,20 @@ declare(strict_types=1); namespace Pterodactyl\Contracts\Activity; +use Illuminate\Validation\ValidationException; use Pterodactyl\Models\Node; interface IngestsActivityLogs { - /** @param ActivityEvents $events */ - public function ingest(Node $node, array $events): void; + /** + * Record the activity a node reported against the servers it runs. The input is the + * report Wings sends, validated here under the field names of its protocol, so it can + * come straight from any caller. Events for servers on other nodes, and events outside + * the `server:` namespace, are dropped. + * + * @param ActionInput $input data: the events, each with server, event, metadata and timestamp, and optionally user and ip + * + * @throws ValidationException + */ + public function ingest(Node $node, array $input): void; } diff --git a/app/Http/Controllers/Api/Remote/ActivityProcessingController.php b/app/Http/Controllers/Api/Remote/ActivityProcessingController.php index 33cee93ca..4c60e71c2 100644 --- a/app/Http/Controllers/Api/Remote/ActivityProcessingController.php +++ b/app/Http/Controllers/Api/Remote/ActivityProcessingController.php @@ -12,6 +12,6 @@ class ActivityProcessingController extends Controller { public function __invoke(ActivityEventRequest $request, IngestsActivityLogs $ingestion): void { - $ingestion->ingest($request->node(), $request->events()); + $ingestion->ingest($request->node(), $request->actionInput()); } } diff --git a/app/Http/Controllers/Api/Remote/Servers/ServerInstallController.php b/app/Http/Controllers/Api/Remote/Servers/ServerInstallController.php index b6c33d46e..3ed57803d 100644 --- a/app/Http/Controllers/Api/Remote/Servers/ServerInstallController.php +++ b/app/Http/Controllers/Api/Remote/Servers/ServerInstallController.php @@ -27,7 +27,9 @@ class ServerInstallController extends Controller */ public function store(InstallationDataRequest $request, RecordsServerInstallResults $installResult, string $uuid): JsonResponse { - $installResult->record($request, $uuid, $request->boolean('successful'), $request->boolean('reinstall')); + $validated = $request->safe(); + + $installResult->record($request, $uuid, $validated->boolean('successful'), $validated->boolean('reinstall')); return new JsonResponse([], Response::HTTP_NO_CONTENT); } diff --git a/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php b/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php index 98950d547..46c181f20 100644 --- a/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php +++ b/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php @@ -22,7 +22,6 @@ use Pterodactyl\Models\Server; use Pterodactyl\Models\User; use Pterodactyl\Models\UserSSHKey; use Pterodactyl\Services\Servers\GetUserPermissionsService; -use Pterodactyl\Support\JsonValueGuard; use Pterodactyl\Traits\Helpers\ThrottlesLogins; use Pterodactyl\Validation\UserSSHKeyRules; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; @@ -42,7 +41,7 @@ class SftpAuthenticationController extends Controller */ public function __invoke(SftpAuthenticationFormRequest $request, GetUserPermissionsService $permissions): JsonResponse { - $connection = $this->parseUsername(JsonValueGuard::string($request->validated('username'))); + $connection = $this->parseUsername($request->safe()->string('username')->toString()); throw_if(empty($connection['server']), BadRequestHttpException::class, 'No valid server identifier was included in the request.'); $server = $this->getServer($request, $connection['server']); @@ -56,7 +55,7 @@ class SftpAuthenticationController extends Controller $user = User::query()->where('username', $connection['username'])->first(); if ($request->validated('type') !== 'public_key') { - $password = JsonValueGuard::string($request->validated('password')); + $password = $request->safe()->string('password')->toString(); if ($user === null) { Hash::make($password); $this->reject($request); @@ -69,7 +68,7 @@ class SftpAuthenticationController extends Controller } } else { $key = null; - $publicKey = mb_trim(JsonValueGuard::string($request->validated('password'))); + $publicKey = mb_trim($request->safe()->string('password')->toString()); if (UserSSHKeyRules::isSupportedPublicKey($publicKey)) { try { $key = PublicKeyLoader::loadPublicKey($publicKey); @@ -171,8 +170,7 @@ class SftpAuthenticationController extends Controller */ protected function throttleKey(Request $request): string { - $raw = JsonValueGuard::nullableString($request->input('username', '')) ?? ''; - $username = Str::transliterate(mb_strtolower(mb_rtrim($this->parseUsername($raw)['username'], ' '))); + $username = Str::transliterate(mb_strtolower(mb_rtrim($this->parseUsername($request->string('username')->toString())['username'], ' '))); return $username.'|'.($this->throttleServer->uuid ?? ''); } diff --git a/app/Http/Requests/Api/Remote/ActivityEventRequest.php b/app/Http/Requests/Api/Remote/ActivityEventRequest.php index c01b9a991..a76f98f53 100644 --- a/app/Http/Requests/Api/Remote/ActivityEventRequest.php +++ b/app/Http/Requests/Api/Remote/ActivityEventRequest.php @@ -4,12 +4,11 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Remote; -use Illuminate\Foundation\Http\FormRequest; +use Pterodactyl\Actions\Activity\IngestActivityLogs; +use Pterodactyl\Http\Requests\Api\ApiRequest; use Pterodactyl\Models\Node; -use Pterodactyl\Support\JsonValueGuard; -use UnexpectedValueException; -class ActivityEventRequest extends FormRequest +class ActivityEventRequest extends ApiRequest { public function authorize(): bool { @@ -21,76 +20,11 @@ class ActivityEventRequest extends FormRequest */ public function rules(): array { - return [ - 'data' => ['required', 'array'], - 'data.*' => ['array'], - 'data.*.user' => ['sometimes', 'nullable', 'uuid'], - 'data.*.server' => ['required', 'uuid'], - 'data.*.event' => ['required', 'string'], - 'data.*.metadata' => ['present', 'nullable', 'array'], - 'data.*.ip' => ['sometimes', 'nullable', 'ip'], - 'data.*.timestamp' => ['required', 'string'], - ]; - } - - /** - * The activity events submitted with this request. The "data" key is - * validated as a required array before these accessors are reachable; the - * guard is what keeps the type honest, since `input()` returns mixed. - * - * @return ActivityEvents - */ - public function events(): array - { - $data = $this->input('data'); - JsonValueGuard::assertValue($data); - throw_unless(is_array($data), UnexpectedValueException::class, 'Activity event data must be a list.'); - - $events = []; - foreach ($data as $value) { - throw_unless(is_array($value), UnexpectedValueException::class, 'Each activity event must be an object.'); - - $metadata = $value['metadata'] ?? []; - throw_unless(is_array($metadata), UnexpectedValueException::class, 'Activity event metadata must be an object.'); - - $normalizedMetadata = []; - foreach ($metadata as $key => $item) { - throw_unless(is_string($key), UnexpectedValueException::class, 'Activity event metadata keys must be strings.'); - - $normalizedMetadata[$key] = $item; - } - - $events[] = [ - 'user' => $this->nullableString($value['user'] ?? null, 'user'), - 'server' => $this->requiredString($value['server'] ?? null, 'server'), - 'event' => $this->requiredString($value['event'] ?? null, 'event'), - 'metadata' => $normalizedMetadata, - 'ip' => $this->nullableString($value['ip'] ?? null, 'ip'), - 'timestamp' => $this->requiredString($value['timestamp'] ?? null, 'timestamp'), - ]; - } - - return $events; + return IngestActivityLogs::rules(); } public function node(): Node { return RemoteRequestNode::get($this); } - - /** @param JsonInputValue $value */ - private function requiredString(mixed $value, string $key): string - { - if (! is_string($value)) { - throw new UnexpectedValueException(sprintf('Activity event field "%s" must be a string.', $key)); - } - - return $value; - } - - /** @param JsonInputValue $value */ - private function nullableString(mixed $value, string $key): ?string - { - return $value === null ? null : $this->requiredString($value, $key); - } } diff --git a/app/Http/Requests/Api/Remote/InstallationDataRequest.php b/app/Http/Requests/Api/Remote/InstallationDataRequest.php index 22b88fd91..bc600ed78 100644 --- a/app/Http/Requests/Api/Remote/InstallationDataRequest.php +++ b/app/Http/Requests/Api/Remote/InstallationDataRequest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Remote; use Illuminate\Foundation\Http\FormRequest; +use Pterodactyl\Actions\Servers\RecordServerInstallResult; class InstallationDataRequest extends FormRequest { @@ -18,9 +19,6 @@ class InstallationDataRequest extends FormRequest */ public function rules(): array { - return [ - 'successful' => ['present', 'boolean'], - 'reinstall' => ['sometimes', 'boolean'], - ]; + return RecordServerInstallResult::rules(); } } diff --git a/app/Http/Requests/Api/Remote/SftpAuthenticationFormRequest.php b/app/Http/Requests/Api/Remote/SftpAuthenticationFormRequest.php index bcf918dc8..4f018e1f9 100644 --- a/app/Http/Requests/Api/Remote/SftpAuthenticationFormRequest.php +++ b/app/Http/Requests/Api/Remote/SftpAuthenticationFormRequest.php @@ -29,19 +29,4 @@ class SftpAuthenticationFormRequest extends FormRequest 'password' => ['required', 'string'], ]; } - - /** - * Return only the fields that we are interested in from the request. - * This will include empty fields as a null value. - * - * @return SftpAuthenticationData - */ - public function normalize(): array - { - return [ - 'type' => $this->filled('type') ? $this->string('type')->toString() : null, - 'username' => $this->string('username')->toString(), - 'password' => $this->string('password')->toString(), - ]; - } } diff --git a/phpstan.neon b/phpstan.neon index 446d825d7..ccb304de6 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -35,8 +35,6 @@ parameters: ApiError: 'array{code: string, status: string, detail: string, source?: ApiErrorSource, meta?: ApiErrorMetadata}' ApiErrorOverride: 'array{code?: string, status?: string, detail?: string, source?: ApiErrorSource, meta?: ApiErrorMetadata}' ApiErrorEnvelope: 'array{errors: list}' - ActivityEvent: 'array{user: string|null, server: string, event: string, metadata: array, ip: string|null, timestamp: string}' - ActivityEvents: 'list' ViteManifestEntry: 'array{file: string, integrity?: string, css?: list, cssIntegrity?: array}' ViteManifest: 'array' JwtClaimValue: 'JsonValue|\DateTimeImmutable' @@ -82,7 +80,6 @@ parameters: DatabaseDeploymentData: 'array{database: string, remote: string, database_host_id?: int|null, max_connections?: int|null}' DatabaseModelCreationData: 'array{database: string, remote: string, database_host_id: int, max_connections?: int|null, server_id: int, username: string, password: string}' MultipartUploadPart: 'array{etag: string, part_number: int}' - SftpAuthenticationData: 'array{type: string|null, username: string, password: string}' BackupUploadParts: 'array{parts: list, 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}" diff --git a/tests/Integration/Actions/Activity/IngestActivityLogsTest.php b/tests/Integration/Actions/Activity/IngestActivityLogsTest.php new file mode 100644 index 000000000..aff01ae49 --- /dev/null +++ b/tests/Integration/Actions/Activity/IngestActivityLogsTest.php @@ -0,0 +1,101 @@ + $server->uuid, + 'event' => 'server:console.command', + 'metadata' => ['command' => 'say hello'], + 'timestamp' => CarbonImmutable::now()->subMinute()->toRfc3339String(), + ], ...$overrides]; +} + +/** + * Activity logged against the server. + * + * @return Builder + */ +function logged(Server $server): Builder +{ + return ActivityLog::query()->whereHas('subjects', fn (Builder $query) => $query->where('subject_id', $server->id)->where('subject_type', $server->getMorphClass())); +} + +test('activity ingested without the http api meets the same rules', function (array $overrides, string $field): void { + $server = $this->createServerModel(); + $event = reported($server, $overrides); + + try { + $this->app->make(IngestsActivityLogs::class)->ingest($server->node, ['data' => [reported($server), array_filter($event, fn (mixed $value): bool => $value !== 'unset')]]); + $this->fail('The activity was ingested.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect(logged($server)->exists())->toBeFalse(); +})->with([ + 'a server that is not a uuid' => [['server' => 'not-a-uuid'], 'data.1.server'], + 'a missing event' => [['event' => 'unset'], 'data.1.event'], + 'an event that is not a string' => [['event' => ['server:power.start']], 'data.1.event'], + 'metadata left out' => [['metadata' => 'unset'], 'data.1.metadata'], + 'metadata that is not an object' => [['metadata' => 'command'], 'data.1.metadata'], + 'a user that is not a uuid' => [['user' => 'someone'], 'data.1.user'], + 'an ip that is not an ip' => [['ip' => '999.0.0.1'], 'data.1.ip'], + 'a missing timestamp' => [['timestamp' => 'unset'], 'data.1.timestamp'], +]); + +test('a report without events, or with an event that is not an object, is refused', function (array $input, string $field): void { + $server = $this->createServerModel(); + + try { + $this->app->make(IngestsActivityLogs::class)->ingest($server->node, $input); + $this->fail('The activity was ingested.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toContain($field); + } +})->with([ + 'no events' => [[], 'data'], + 'events that are not a list' => [['data' => 'server:power.start'], 'data'], + 'an event that is not an object' => [['data' => ['server:power.start']], 'data.0'], +]); + +test('events are recorded with their actor, null metadata is empty, and other nodes\' servers are skipped', function (): void { + $server = $this->createServerModel(); + $other = $this->createServerModel(); + $user = User::factory()->create(); + + $this->app->make(IngestsActivityLogs::class)->ingest($server->node, ['data' => [ + reported($server, ['user' => $user->uuid, 'ip' => '10.0.0.5']), + reported($server, ['event' => 'server:power.start', 'metadata' => null]), + reported($other, ['event' => 'server:power.stop']), + ]]); + + $command = logged($server)->where('event', 'server:console.command')->sole(); + expect($command->actor_id)->toBe($user->id) + ->and($command->ip)->toBe('10.0.0.5') + ->and($command->properties->all())->toBe(['command' => 'say hello']); + + $start = logged($server)->where('event', 'server:power.start')->sole(); + expect($start->actor_id)->toBeNull() + ->and($start->ip)->toBe('127.0.0.1') + ->and($start->properties->all())->toBe([]); + + // The other server runs on another node, so the node cannot report activity for it. + expect(logged($other)->exists())->toBeFalse(); +}); diff --git a/tests/Integration/Api/Remote/ActivityProcessingControllerTest.php b/tests/Integration/Api/Remote/ActivityProcessingControllerTest.php index c11079619..2d11aba9e 100644 --- a/tests/Integration/Api/Remote/ActivityProcessingControllerTest.php +++ b/tests/Integration/Api/Remote/ActivityProcessingControllerTest.php @@ -49,6 +49,15 @@ test('events for other nodes and foreign namespaces are discarded', function () expect(logsFor($this->server)->count())->toBe(0); expect(logsFor($other)->count())->toBe(0); }); +test('malformed events are refused under the wings field names', function () { + $this->postJson('/api/remote/activity', ['data' => [['user' => 'someone', 'server' => $this->server->uuid, 'event' => 'server:console.command', 'ip' => 'nowhere', 'timestamp' => CarbonImmutable::now()->toRfc3339String()]]]) + ->assertUnprocessable() + ->assertJsonCount(3, 'errors') + ->assertJsonPath('errors.0.meta.source_field', 'data.0.user') + ->assertJsonPath('errors.1.meta.source_field', 'data.0.metadata') + ->assertJsonPath('errors.2.meta.source_field', 'data.0.ip'); + expect(logsFor($this->server)->count())->toBe(0); +}); test('unparsable timestamps do not fail the request', function () { $this->postJson('/api/remote/activity', ['data' => [['user' => $this->user->uuid, 'server' => $this->server->uuid, 'event' => 'server:console.command', 'metadata' => [], 'timestamp' => 'not a timestamp']]])->assertSuccessful(); $log = logsFor($this->server)->where('event', 'server:console.command')->sole(); diff --git a/tests/Integration/Api/Remote/RemoteServersApiTest.php b/tests/Integration/Api/Remote/RemoteServersApiTest.php index dfb52a2d7..5a920f709 100644 --- a/tests/Integration/Api/Remote/RemoteServersApiTest.php +++ b/tests/Integration/Api/Remote/RemoteServersApiTest.php @@ -54,6 +54,15 @@ test('node can report a failed install', function () { actingAsNode($server->node)->postJson("/api/remote/servers/{$server->uuid}/install", ['successful' => false, 'reinstall' => false])->assertNoContent(); expect($server->refresh()->status)->toBe(Server::STATUS_INSTALL_FAILED); }); +test('an install report takes boolean strings and needs its outcome', function () { + $server = $this->createServerModel(['status' => Server::STATUS_INSTALLING, 'installed_at' => null]); + actingAsNode($server->node)->postJson("/api/remote/servers/{$server->uuid}/install", ['reinstall' => '1']) + ->assertUnprocessable() + ->assertJsonCount(1, 'errors') + ->assertJsonPath('errors.0.meta.source_field', 'successful'); + actingAsNode($server->node)->postJson("/api/remote/servers/{$server->uuid}/install", ['successful' => '0', 'reinstall' => '1'])->assertNoContent(); + expect($server->refresh()->status)->toBe(Server::STATUS_REINSTALL_FAILED); +}); test('node can reset restoring servers', function () { $server = $this->createServerModel(); $server->update(['status' => Server::STATUS_RESTORING_BACKUP]);