Path: blob/1.0-develop/tests/Integration/Api/Client/ApiKeyControllerTest.php
7459 views
<?php12namespace Pterodactyl\Tests\Integration\Api\Client;34use Pterodactyl\Models\User;5use Illuminate\Http\Response;6use Pterodactyl\Models\ApiKey;7use Illuminate\Support\Facades\Event;8use Pterodactyl\Events\ActivityLogged;910class ApiKeyControllerTest extends ClientApiIntegrationTestCase11{12/**13* Cleanup after tests.14*/15protected function tearDown(): void16{17ApiKey::query()->forceDelete();1819parent::tearDown();20}2122/**23* Test that the client's API key can be returned successfully.24*/25public function testApiKeysAreReturned()26{27/** @var User $user */28$user = User::factory()->create();29/** @var ApiKey $key */30$key = ApiKey::factory()->for($user)->create([31'key_type' => ApiKey::TYPE_ACCOUNT,32]);3334$response = $this->actingAs($user)->get('/api/client/account/api-keys')35->assertOk()36->assertJsonPath('object', 'list')37->assertJsonPath('data.0.object', ApiKey::RESOURCE_NAME);3839$this->assertJsonTransformedWith($response->json('data.0.attributes'), $key);40}4142/**43* Test that an API key can be created for the client account. This also checks that the44* API key secret is returned as metadata in the response since it will not be returned45* after that point.46*/47#[\PHPUnit\Framework\Attributes\DataProvider('validIPAddressDataProvider')]48public function testApiKeyCanBeCreatedForAccount(array $data)49{50/** @var User $user */51$user = User::factory()->create();5253// Small subtest to ensure we're always comparing the number of keys to the54// specific logged in account, and not just the total number of keys stored in55// the database.56ApiKey::factory()->times(10)->create([57'user_id' => User::factory()->create()->id,58'key_type' => ApiKey::TYPE_ACCOUNT,59]);6061$response = $this->actingAs($user)->postJson('/api/client/account/api-keys', [62'description' => 'Test Description',63'allowed_ips' => $data,64])65->assertOk()66->assertJsonPath('object', ApiKey::RESOURCE_NAME);6768/** @var ApiKey $key */69$key = ApiKey::query()->where('identifier', $response->json('attributes.identifier'))->firstOrFail();7071$this->assertJsonTransformedWith($response->json('attributes'), $key);72$response->assertJsonPath('meta.secret_token', decrypt($key->token));7374$this->assertActivityFor('user:api-key.create', $user, [$key, $user]);75}7677/**78* Block requests to create an API key specifying more than 50 IP addresses.79*/80public function testApiKeyCannotSpecifyMoreThanFiftyIps()81{82$ips = [];83for ($i = 0; $i < 100; ++$i) {84$ips[] = '127.0.0.' . $i;85}8687$this->actingAs(User::factory()->create())88->postJson('/api/client/account/api-keys', [89'description' => 'Test Data',90'allowed_ips' => $ips,91])92->assertUnprocessable()93->assertJsonPath('errors.0.detail', 'The allowed ips may not have more than 50 items.');94}9596/**97* Test that no more than 25 API keys can exist at any one time for an account. This prevents98* a DoS attack vector against the panel.99*100* @see https://github.com/pterodactyl/panel/security/advisories/GHSA-pjmh-7xfm-r4x9101* @see https://github.com/pterodactyl/panel/issues/4394102*/103public function testApiKeyLimitIsApplied()104{105/** @var User $user */106$user = User::factory()->create();107ApiKey::factory()->times(25)->for($user)->create([108'key_type' => ApiKey::TYPE_ACCOUNT,109]);110111$this->actingAs($user)->postJson('/api/client/account/api-keys', [112'description' => 'Test Description',113'allowed_ips' => ['127.0.0.1'],114])115->assertStatus(Response::HTTP_BAD_REQUEST)116->assertJsonPath('errors.0.code', 'DisplayException')117->assertJsonPath('errors.0.detail', 'You have reached the account limit for number of API keys.');118}119120/**121* Test that a bad request results in a validation error being returned by the API.122*123* @see https://github.com/pterodactyl/panel/issues/2457124*/125public function testValidationErrorIsReturnedForBadRequests()126{127$this->actingAs(User::factory()->create());128129$this->postJson('/api/client/account/api-keys', [130'description' => '',131'allowed_ips' => ['127.0.0.1'],132])133->assertUnprocessable()134->assertJsonPath('errors.0.meta.rule', 'required')135->assertJsonPath('errors.0.detail', 'The description field is required.');136137$this->postJson('/api/client/account/api-keys', [138'description' => str_repeat('a', 501),139'allowed_ips' => ['127.0.0.1'],140])141->assertUnprocessable()142->assertJsonPath('errors.0.meta.rule', 'max')143->assertJsonPath('errors.0.detail', 'The description may not be greater than 500 characters.');144145$this->postJson('/api/client/account/api-keys', [146'description' => 'Foobar',147'allowed_ips' => ['hodor', '127.0.0.1', 'hodor/24'],148])149->assertUnprocessable()150->assertJsonPath('errors.0.detail', '"hodor" is not a valid IP address or CIDR range.')151->assertJsonPath('errors.0.meta.source_field', 'allowed_ips.0')152->assertJsonPath('errors.1.detail', '"hodor/24" is not a valid IP address or CIDR range.')153->assertJsonPath('errors.1.meta.source_field', 'allowed_ips.2');154}155156/**157* Tests that an API key can be deleted from the account.158*/159public function testApiKeyCanBeDeleted()160{161/** @var User $user */162$user = User::factory()->create();163/** @var ApiKey $key */164$key = ApiKey::factory()->for($user)->create([165'key_type' => ApiKey::TYPE_ACCOUNT,166]);167168$response = $this->actingAs($user)->delete('/api/client/account/api-keys/' . $key->identifier);169$response->assertStatus(Response::HTTP_NO_CONTENT);170171$this->assertDatabaseMissing('api_keys', ['id' => $key->id]);172$this->assertActivityFor('user:api-key.delete', $user, $user);173}174175/**176* Test that trying to delete an API key that does not exist results in a 404.177*/178public function testNonExistentApiKeyDeletionReturns404Error()179{180/** @var User $user */181$user = User::factory()->create();182/** @var ApiKey $key */183$key = ApiKey::factory()->create([184'user_id' => $user->id,185'key_type' => ApiKey::TYPE_ACCOUNT,186]);187188$response = $this->actingAs($user)->delete('/api/client/account/api-keys/1234');189$response->assertNotFound();190191$this->assertDatabaseHas('api_keys', ['id' => $key->id]);192Event::assertNotDispatched(ActivityLogged::class);193}194195/**196* Test that an API key that exists on the system cannot be deleted if the user197* who created it is not the authenticated user.198*/199public function testApiKeyBelongingToAnotherUserCannotBeDeleted()200{201/** @var User $user */202$user = User::factory()->create();203/** @var User $user2 */204$user2 = User::factory()->create();205/** @var ApiKey $key */206$key = ApiKey::factory()->for($user2)->create([207'key_type' => ApiKey::TYPE_ACCOUNT,208]);209210$this->actingAs($user)211->deleteJson('/api/client/account/api-keys/' . $key->identifier)212->assertNotFound();213214$this->assertDatabaseHas('api_keys', ['id' => $key->id]);215Event::assertNotDispatched(ActivityLogged::class);216}217218/**219* Tests that an application API key also belonging to the logged-in user cannot be220* deleted through this endpoint if it exists.221*/222public function testApplicationApiKeyCannotBeDeleted()223{224/** @var User $user */225$user = User::factory()->create();226/** @var ApiKey $key */227$key = ApiKey::factory()->for($user)->create([228'key_type' => ApiKey::TYPE_APPLICATION,229]);230231$this->actingAs($user)232->deleteJson('/api/client/account/api-keys/' . $key->identifier)233->assertNotFound();234235$this->assertDatabaseHas('api_keys', ['id' => $key->id]);236}237238/**239* Provides some different IP address combinations that can be used when240* testing that we accept the expected IP values.241*/242public static function validIPAddressDataProvider(): array243{244return [245[[]],246[['127.0.0.1']],247[['127.0.0.1', '::1']],248[['::ffff:7f00:1']],249[['127.0.0.1', '192.168.1.100', '192.168.10.10/28']],250[['127.0.0.1/32', '192.168.100.100/27', '::1', '::1/128']],251];252}253}254255256