diff --git a/app/Http/Resources/Api/Admin/ServerDatabaseResource.php b/app/Http/Resources/Api/Admin/ServerDatabaseResource.php new file mode 100644 index 000000000..c267e04d6 --- /dev/null +++ b/app/Http/Resources/Api/Admin/ServerDatabaseResource.php @@ -0,0 +1,75 @@ + + */ +#[ResponseField('max_connections', 'integer', example: 0, nullable: true)] +class ServerDatabaseResource extends AdminResource +{ + protected array $eagerLoads = ['host']; + + /** + * @var list + */ + protected array $availableIncludes = ['password']; + + public function resourceName(): string + { + return Database::RESOURCE_NAME; + } + + /** + * @return ApiPayload + */ + public function toArray(Request $request): array + { + $this->resource->loadMissing('host'); + $host = $this->resource->host; + + return [ + 'id' => Hashids::encode($this->resource->id), + 'host' => [ + 'address' => $host->host, + 'port' => $host->port, + ], + 'name' => $this->resource->database, + 'username' => $this->resource->username, + 'connections_from' => $this->resource->remote, + 'max_connections' => $this->resource->max_connections, + 'relationships' => [], + ]; + } + + protected function resolveInclude(string $include): ?IncludedResource + { + return match ($include) { + 'password' => $this->includePassword(), + default => parent::resolveInclude($include), + }; + } + + /** + * No per-server subuser permission check here; admin API access is gated on root-admin alone. + * + * @return ApiResource + */ + private function includePassword(): ApiResource + { + return $this->item($this->resource, fn (Database $model): array => [ + 'password' => Arr::string(['password' => Crypt::decrypt($model->password)], 'password'), + ], 'database_password'); + } +} diff --git a/app/Http/Resources/Api/Application/EggVariableResource.php b/app/Http/Resources/Api/Application/EggVariableResource.php new file mode 100644 index 000000000..d346d5c2e --- /dev/null +++ b/app/Http/Resources/Api/Application/EggVariableResource.php @@ -0,0 +1,32 @@ + + */ +class EggVariableResource extends ApplicationResource +{ + public function resourceName(): string + { + return Egg::RESOURCE_NAME; + } + + /** + * @return ApiPayload + */ + public function toArray(Request $request): array + { + $attributes = $this->resource->attributesToArray(); + JsonValueGuard::assertPayload($attributes); + + return $attributes; + } +} diff --git a/app/Http/Resources/Api/Application/ServerVariableResource.php b/app/Http/Resources/Api/Application/ServerVariableResource.php new file mode 100644 index 000000000..7c499bf96 --- /dev/null +++ b/app/Http/Resources/Api/Application/ServerVariableResource.php @@ -0,0 +1,67 @@ + + */ +class ServerVariableResource extends ApplicationResource +{ + /** + * List of resources that can be included. + * + * @var list + */ + protected array $availableIncludes = ['parent']; + + public function resourceName(): string + { + return ServerVariable::RESOURCE_NAME; + } + + /** + * Return a generic transformed server variable array. + * + * @return ApiPayload + */ + public function toArray(Request $request): array + { + $attributes = $this->resource->attributesToArray(); + JsonValueGuard::assertPayload($attributes); + + return $attributes; + } + + protected function resolveInclude(string $include): ?IncludedResource + { + return match ($include) { + 'parent' => $this->includeParent(), + default => parent::resolveInclude($include), + }; + } + + /** + * Return the parent service variable data. + * + * @return ApiResource|NullResource + */ + private function includeParent(): ApiResource|NullResource + { + if (! $this->authorize(AdminAcl::RESOURCE_EGGS)) { + return $this->null(); + } + + return $this->item($this->resource, EggVariableResource::class, 'variable'); + } +} diff --git a/app/Http/Resources/Api/Client/DatabaseResource.php b/app/Http/Resources/Api/Client/DatabaseResource.php new file mode 100644 index 000000000..9edcd1f1e --- /dev/null +++ b/app/Http/Resources/Api/Client/DatabaseResource.php @@ -0,0 +1,80 @@ + + */ +#[ResponseField('max_connections', 'integer', example: 0, nullable: true)] +class DatabaseResource extends ClientResource +{ + protected array $eagerLoads = ['host', 'server.subusers']; + + /** + * @var list + */ + protected array $availableIncludes = ['password']; + + public function resourceName(): string + { + return Database::RESOURCE_NAME; + } + + /** + * @return ApiPayload + */ + public function toArray(Request $request): array + { + $this->resource->loadMissing('host'); + $host = $this->resource->host; + + return [ + 'id' => Hashids::encode($this->resource->id), + 'host' => [ + 'address' => $host->host, + 'port' => $host->port, + ], + 'name' => $this->resource->database, + 'username' => $this->resource->username, + 'connections_from' => $this->resource->remote, + 'max_connections' => $this->resource->max_connections, + ]; + } + + protected function resolveInclude(string $include): ?IncludedResource + { + return match ($include) { + 'password' => $this->includePassword(), + default => parent::resolveInclude($include), + }; + } + + /** + * Include the database password in the request. + * + * @return ApiResource|NullResource + */ + private function includePassword(): ApiResource|NullResource + { + if (! $this->getUser()->can(Permissions::DatabaseViewPassword->value, $this->resource->server)) { + return $this->null(); + } + + return $this->item($this->resource, fn (Database $model): array => [ + 'password' => Arr::string(['password' => Crypt::decrypt($model->password)], 'password'), + ], 'database_password'); + } +} diff --git a/app/Http/Resources/Api/Client/UserSSHKeyResource.php b/app/Http/Resources/Api/Client/UserSSHKeyResource.php new file mode 100644 index 000000000..e09140b27 --- /dev/null +++ b/app/Http/Resources/Api/Client/UserSSHKeyResource.php @@ -0,0 +1,34 @@ + + */ +class UserSSHKeyResource extends ClientResource +{ + public function resourceName(): string + { + return UserSSHKey::RESOURCE_NAME; + } + + /** + * Return's a user's SSH key in an API response format. + * + * @return ApiPayload + */ + public function toArray(Request $request): array + { + return [ + 'name' => $this->resource->name, + 'fingerprint' => $this->resource->fingerprint, + 'public_key' => $this->resource->public_key, + 'created_at' => $this->formatTimestamp($this->resource->created_at), + ]; + } +} diff --git a/tests/Integration/Api/Parity/ResourceParity.php b/tests/Integration/Api/Parity/ResourceParity.php new file mode 100644 index 000000000..6e53af88f --- /dev/null +++ b/tests/Integration/Api/Parity/ResourceParity.php @@ -0,0 +1,232 @@ + */ + private array $forced = []; + + /** @var array */ + private array $meta = []; + + private bool $extensionFields = false; + + private ?int $status = null; + + /** + * @param class-string $transformer + * @param class-string> $resource + * @param Closure(): mixed $data + */ + private function __construct( + private readonly string $transformer, + private readonly string $resource, + private readonly Closure $data, + private readonly bool $list, + ) {} + + /** + * One model, as Fractal::item($data) renders it. + * + * @param class-string $transformer + * @param class-string> $resource + * @param Closure(): mixed $data + */ + public static function item(string $transformer, string $resource, Closure $data): self + { + return new self($transformer, $resource, $data, false); + } + + /** + * A list or a paginator, as Fractal::collection($data) renders it. + * + * @param class-string $transformer + * @param class-string> $resource + * @param Closure(): mixed $data + */ + public static function list(string $transformer, string $resource, Closure $data): self + { + return new self($transformer, $resource, $data, true); + } + + public function request(string $uri): self + { + $this->uri = $uri; + + return $this; + } + + public function actingAs(User $user, ?ApiKey $key = null): self + { + $this->user = $user->id; + $this->key = $key?->id; + + return $this; + } + + /** + * Includes the controller always returns: parseIncludes() and withIncludes(). + */ + public function forcing(string ...$includes): self + { + $this->forced = [...$this->forced, ...array_values($includes)]; + + return $this; + } + + /** + * @param array $meta + */ + public function withMeta(array $meta): self + { + $this->meta = [...$this->meta, ...$meta]; + + return $this; + } + + public function withExtensionFields(): self + { + $this->extensionFields = true; + + return $this; + } + + /** + * Responds through respond($status) on both sides instead of returning the payload. + */ + public function respond(int $status): self + { + $this->status = $status; + + return $this; + } + + /** + * Asserts both sides render the same response with the same queries, and returns the body. + */ + public function assertSame(): string + { + $fractal = $this->render(fn (Request $request): JsonResponse => $this->fractal()); + $resource = $this->render(fn (Request $request): JsonResponse => $this->resource($request)); + + expect($resource['body'])->toBe($fractal['body']) + ->and($resource['status'])->toBe($fractal['status']) + ->and($resource['queries'])->toBe($fractal['queries']); + + return $fractal['body']; + } + + /** + * The response a controller builds with Fractal. + */ + private function fractal(): JsonResponse + { + $transformer = App::make($this->transformer); + if ($this->extensionFields) { + $transformer->withExtensionFields(); + } + + $data = ($this->data)(); + $fractal = ($this->list ? Fractal::collection($data) : Fractal::item($data))->transformWith($transformer); + if ($this->forced !== []) { + $fractal->parseIncludes($this->forced); + } + + if ($this->meta !== []) { + $fractal->addMeta($this->meta); + } + + // A controller returns the payload array and the router turns it into a JsonResponse. + return $this->status === null ? new JsonResponse($fractal->toResponseArray()) : $fractal->respond($this->status); + } + + /** + * The response a controller builds with the resource. + */ + private function resource(Request $request): JsonResponse + { + $data = ($this->data)(); + $resource = $this->list ? $this->resource::collection($data) : new $this->resource($data); + if ($this->extensionFields && $resource instanceof ApiResource) { + $resource->withExtensionFields(); + } + + if ($this->forced !== []) { + $resource->withIncludes(...$this->forced); + } + + if ($this->meta !== []) { + $resource->withMeta($this->meta); + } + + return $this->status === null ? $resource->toResponse($request) : $resource->respond($this->status); + } + + /** + * @param Closure(Request): JsonResponse $respond + * @return array{status: int, body: string, queries: list}>} + */ + private function render(Closure $respond): array + { + // Bound as the HTTP kernel binds a request, since transformers read it through the + // Request facade. Binding resets the user resolver, so the user is set afterwards. + $request = Request::create($this->uri, server: ['HTTP_ACCEPT' => 'application/json']); + App::instance('request', $request); + App::instance(Request::class, $request); + Facade::clearResolvedInstance('request'); + + if ($this->user !== null) { + $user = User::query()->findOrFail($this->user); + if ($this->key !== null) { + $user->withAccessToken(ApiKey::query()->findOrFail($this->key)); + } + + $request->setUserResolver(fn (): User => $user); + } + + DB::flushQueryLog(); + DB::enableQueryLog(); + try { + $response = $respond($request); + } finally { + DB::disableQueryLog(); + } + + return [ + 'status' => $response->getStatusCode(), + 'body' => (string) $response->getContent(), + 'queries' => array_map(fn (array $query): array => [$query['query'], $query['bindings']], DB::getQueryLog()), + ]; + } +} diff --git a/tests/Integration/Api/Parity/ResourceParityTest.php b/tests/Integration/Api/Parity/ResourceParityTest.php new file mode 100644 index 000000000..7a2ce14e2 --- /dev/null +++ b/tests/Integration/Api/Parity/ResourceParityTest.php @@ -0,0 +1,125 @@ +} + */ +function serverWithDatabases(IntegrationTestCase $test): array +{ + $server = (fn (): Server => $this->createServerModel())->call($test); + $host = DatabaseHost::factory()->create(['node_id' => $server->node_id]); + $databases = Database::factory()->count(2)->create(['server_id' => $server->id, 'database_host_id' => $host->id]); + + return [$server, $databases->modelKeys()]; +} + +test('client ssh keys render the same', function (): void { + $user = User::factory()->create(); + $first = UserSSHKey::factory()->create(['user_id' => $user->id]); + UserSSHKey::factory()->dsa()->create(['user_id' => $user->id]); + UserSSHKey::factory()->rsa()->create(['user_id' => $user->id]); + + $one = fn (): UserSSHKey => UserSSHKey::query()->findOrFail($first->id); + $keys = fn () => UserSSHKey::query()->where('user_id', $user->id)->get(); + $page = fn () => UserSSHKey::query()->where('user_id', $user->id)->paginate(1)->appends(['sort' => 'name']); + + expect(ResourceParity::item(UserSSHKeyTransformer::class, UserSSHKeyResource::class, $one)->actingAs($user)->assertSame()) + ->toStartWith('{"object":"ssh_key","attributes":{"name":'); + expect(ResourceParity::list(UserSSHKeyTransformer::class, UserSSHKeyResource::class, $keys)->actingAs($user)->assertSame()) + ->toStartWith('{"object":"list","data":[{"object":"ssh_key"'); + expect(ResourceParity::list(UserSSHKeyTransformer::class, UserSSHKeyResource::class, $page)->request('/api/client/account/ssh-keys?page=2')->actingAs($user)->assertSame()) + ->toContain('"pagination":{"total":3,"count":1,"per_page":1,"current_page":2,"total_pages":3,"links":{"previous":'); + expect(ResourceParity::list(UserSSHKeyTransformer::class, UserSSHKeyResource::class, fn () => UserSSHKey::query()->whereKey(0)->paginate())->actingAs($user)->assertSame()) + ->toContain('"data":[],"meta":{"pagination":{"total":0,"count":0,"per_page":15,"current_page":1,"total_pages":1,"links":{}}}'); +}); + +test('client databases render the same, with the password only for users who may see it', function (): void { + [$server, $ids] = serverWithDatabases($this); + $owner = User::query()->findOrFail($server->owner_id); + $subuser = User::factory()->create(); + Subuser::query()->create(['user_id' => $subuser->id, 'server_id' => $server->id, 'permissions' => [Permissions::DatabaseRead->value]]); + + $one = fn (): Database => Database::query()->findOrFail($ids[0]); + $all = fn () => Database::query()->where('server_id', $server->id)->get(); + + expect(ResourceParity::item(DatabaseTransformer::class, DatabaseResource::class, $one)->request('/?include=password')->actingAs($owner)->assertSame()) + ->toContain('"relationships":{"password":{"object":"database_password","attributes":{"password":'); + expect(ResourceParity::item(DatabaseTransformer::class, DatabaseResource::class, $one)->request('/?include=password')->actingAs($subuser)->assertSame()) + ->toContain('"relationships":{"password":{"object":"null_resource","attributes":null}}'); + ResourceParity::item(DatabaseTransformer::class, DatabaseResource::class, $one)->forcing('password')->actingAs($owner)->assertSame(); + ResourceParity::item(DatabaseTransformer::class, DatabaseResource::class, $one)->actingAs($subuser)->assertSame(); + ResourceParity::list(DatabaseTransformer::class, DatabaseResource::class, $all)->request('/?include=password')->actingAs($owner)->assertSame(); + ResourceParity::list(DatabaseTransformer::class, DatabaseResource::class, $all)->request('/?include=password')->actingAs($subuser)->assertSame(); +}); + +test('admin server databases render the same', function (): void { + [$server, $ids] = serverWithDatabases($this); + $admin = User::factory()->create(['root_admin' => true]); + + $one = fn (): Database => Database::query()->findOrFail($ids[0]); + $all = fn () => Database::query()->where('server_id', $server->id)->get(); + $page = fn () => Database::query()->where('server_id', $server->id)->paginate(1); + + expect(ResourceParity::item(ServerDatabaseTransformer::class, ServerDatabaseResource::class, $one)->actingAs($admin)->assertSame()) + ->toEndWith('"relationships":[]}}'); + ResourceParity::item(ServerDatabaseTransformer::class, ServerDatabaseResource::class, $one)->request('/?include=password')->actingAs($admin)->assertSame(); + expect(ResourceParity::item(ServerDatabaseTransformer::class, ServerDatabaseResource::class, $one) + ->forcing('password') + ->withMeta(['resource' => 'https://panel.example.test/api/admin/servers/1/databases/1']) + ->respond(201) + ->actingAs($admin) + ->assertSame())->toEndWith('"meta":{"resource":"https:\/\/panel.example.test\/api\/admin\/servers\/1\/databases\/1"}}'); + ResourceParity::list(ServerDatabaseTransformer::class, ServerDatabaseResource::class, $all)->actingAs($admin)->assertSame(); + ResourceParity::list(ServerDatabaseTransformer::class, ServerDatabaseResource::class, $page)->request('/api/admin/servers/1/databases?include=password')->actingAs($admin)->assertSame(); +}); + +test('application server variables render the same for keys with and without egg access', function (int $type, int $eggs, string $parent): void { + $server = $this->createServerModel(); + $admin = User::factory()->create(['root_admin' => true]); + $key = ApiKey::factory()->create(['user_id' => $admin->id, 'key_type' => $type, AdminAcl::COLUMN_IDENTIFIER.AdminAcl::RESOURCE_EGGS => $eggs]); + + $variables = fn () => App::make(EnvironmentService::class)->variables(Server::query()->findOrFail($server->id)); + + expect(ResourceParity::list(ServerVariableTransformer::class, ServerVariableResource::class, $variables)->request('/?include=parent')->actingAs($admin, $key)->assertSame()) + ->toContain('"relationships":{"parent":{"object":'.$parent); + ResourceParity::item(ServerVariableTransformer::class, ServerVariableResource::class, fn () => $variables()->firstOrFail())->request('/?include=parent')->actingAs($admin, $key)->assertSame(); + ResourceParity::item(ServerVariableTransformer::class, ServerVariableResource::class, fn () => $variables()->firstOrFail())->actingAs($admin, $key)->assertSame(); +})->with([ + 'an application key that reads eggs' => [ApiKey::TYPE_APPLICATION, AdminAcl::READ, '"variable"'], + 'an application key without eggs' => [ApiKey::TYPE_APPLICATION, AdminAcl::NONE, '"null_resource"'], + 'a root admin account key' => [ApiKey::TYPE_ACCOUNT, AdminAcl::NONE, '"variable"'], +]);