Merge branch 'dane/sanctum' into v2

This commit is contained in:
Dane Everitt 2021-08-07 16:19:19 -07:00
commit 874e7afce3
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
253 changed files with 1480 additions and 3543 deletions

View file

@ -33,7 +33,7 @@ abstract class BrowserTestCase extends TestCase
* test. In most cases you probably wont need to do this, or can modify the test slightly to
* avoid the need to do so.
*/
public static function setUpBeforeClass()
public static function setUpBeforeClass(): void
{
parent::setUpBeforeClass();

View file

@ -3,14 +3,10 @@
namespace Pterodactyl\Tests\Integration\Api\Application;
use Pterodactyl\Models\User;
use PHPUnit\Framework\Assert;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Services\Acl\Api\AdminAcl;
use Pterodactyl\Models\PersonalAccessToken;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Pterodactyl\Tests\Traits\Integration\CreatesTestModels;
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
use Pterodactyl\Transformers\Api\Client\BaseClientTransformer;
use Pterodactyl\Tests\Traits\Http\IntegrationJsonRequestAssertions;
abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
@ -19,16 +15,19 @@ abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
use DatabaseTransactions;
use IntegrationJsonRequestAssertions;
/**
* @var \Pterodactyl\Models\ApiKey
*/
private $key;
/**
* @var \Pterodactyl\Models\User
*/
private $user;
/**
* @var string[]
*/
protected $defaultHeaders = [
'Accept' => 'application/vnd.pterodactyl.v1+json',
'Content-Type' => 'application/json',
];
/**
* Bootstrap application API tests. Creates a default admin user and associated API key
* and also sets some default headers required for accessing the API.
@ -37,111 +36,25 @@ abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
{
parent::setUp();
$this->user = $this->createApiUser();
$this->key = $this->createApiKey($this->user);
$this->user = User::factory()->create(['root_admin' => true]);
$this->withHeader('Accept', 'application/vnd.pterodactyl.v1+json');
$this->withHeader('Authorization', 'Bearer ' . $this->getApiKey()->identifier . decrypt($this->getApiKey()->token));
$this->withMiddleware('api..key:' . ApiKey::TYPE_APPLICATION);
$this->createNewAccessToken();
}
/**
* @return \Pterodactyl\Models\User
*/
public function getApiUser(): User
{
return $this->user;
}
/**
* @return \Pterodactyl\Models\ApiKey
*/
public function getApiKey(): ApiKey
{
return $this->key;
}
/**
* Creates a new default API key and refreshes the headers using it.
*
* @param \Pterodactyl\Models\User $user
* @param array $permissions
*
* @return \Pterodactyl\Models\ApiKey
*/
protected function createNewDefaultApiKey(User $user, array $permissions = []): ApiKey
protected function createNewAccessToken(array $abilities = ['*']): PersonalAccessToken
{
$this->key = $this->createApiKey($user, $permissions);
$this->refreshHeaders($this->key);
$token = $this->user->createToken('test', $abilities);
return $this->key;
}
$this->withHeader('Authorization', 'Bearer ' . $token->plainTextToken);
/**
* Refresh the authorization header for a request to use a different API key.
*
* @param \Pterodactyl\Models\ApiKey $key
*/
protected function refreshHeaders(ApiKey $key)
{
$this->withHeader('Authorization', 'Bearer ' . $key->identifier . decrypt($key->token));
}
/**
* Create an administrative user.
*
* @return \Pterodactyl\Models\User
*/
protected function createApiUser(): User
{
return User::factory()->create([
'root_admin' => true,
]);
}
/**
* Create a new application API key for a given user model.
*
* @param \Pterodactyl\Models\User $user
* @param array $permissions
*
* @return \Pterodactyl\Models\ApiKey
*/
protected function createApiKey(User $user, array $permissions = []): ApiKey
{
return ApiKey::factory()->create(array_merge([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_APPLICATION,
'r_servers' => AdminAcl::READ | AdminAcl::WRITE,
'r_nodes' => AdminAcl::READ | AdminAcl::WRITE,
'r_allocations' => AdminAcl::READ | AdminAcl::WRITE,
'r_users' => AdminAcl::READ | AdminAcl::WRITE,
'r_locations' => AdminAcl::READ | AdminAcl::WRITE,
'r_nests' => AdminAcl::READ | AdminAcl::WRITE,
'r_eggs' => AdminAcl::READ | AdminAcl::WRITE,
'r_database_hosts' => AdminAcl::READ | AdminAcl::WRITE,
'r_server_databases' => AdminAcl::READ | AdminAcl::WRITE,
], $permissions));
}
/**
* Return a transformer that can be used for testing purposes.
*
* @param string $abstract
*
* @return \Pterodactyl\Transformers\Api\Application\BaseTransformer
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
protected function getTransformer(string $abstract): BaseTransformer
{
/** @var \Pterodactyl\Transformers\Api\Application\BaseTransformer $transformer */
$transformer = $this->app->make($abstract);
$transformer->setKey($this->getApiKey());
Assert::assertInstanceOf(BaseTransformer::class, $transformer);
Assert::assertNotInstanceOf(BaseClientTransformer::class, $transformer);
return $transformer;
return $token->accessToken;
}
}

View file

@ -56,7 +56,7 @@ class EggControllerTest extends ApplicationApiIntegrationTestCase
$egg = $eggs->where('id', '=', $datum['attributes']['id'])->first();
$expected = json_encode(Arr::sortRecursive($datum['attributes']));
$actual = json_encode(Arr::sortRecursive($this->getTransformer(EggTransformer::class)->transform($egg)));
$actual = json_encode(Arr::sortRecursive((new EggTransformer())->transform($egg)));
$this->assertSame(
$expected,
@ -84,7 +84,7 @@ class EggControllerTest extends ApplicationApiIntegrationTestCase
$response->assertJson([
'object' => 'egg',
'attributes' => $this->getTransformer(EggTransformer::class)->transform($egg),
'attributes' => (new EggTransformer())->transform($egg),
], true);
}
@ -124,11 +124,7 @@ class EggControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testErrorReturnedIfNoPermission()
{
$egg = $this->repository->find(1);
$this->createNewDefaultApiKey($this->getApiUser(), ['r_eggs' => 0]);
$response = $this->getJson('/api/application/nests/' . $egg->nest_id . '/eggs');
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
/**
@ -137,9 +133,6 @@ class EggControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testResourceIsNotExposedWithoutPermissions()
{
$this->createNewDefaultApiKey($this->getApiUser(), ['r_eggs' => 0]);
$response = $this->getJson('/api/application/eggs/nil');
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
}

View file

@ -118,7 +118,7 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
'data' => [
[
'object' => 'node',
'attributes' => $this->getTransformer(NodeTransformer::class)->transform($server->getRelation('node')),
'attributes' => (new NodeTransformer())->transform($server->getRelation('node')),
],
],
],
@ -127,7 +127,7 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
'data' => [
[
'object' => 'server',
'attributes' => $this->getTransformer(ServerTransformer::class)->transform($server),
'attributes' => (new ServerTransformer())->transform($server),
],
],
],
@ -142,33 +142,7 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testKeyWithoutPermissionCannotLoadRelationship()
{
$this->createNewDefaultApiKey($this->getApiUser(), ['r_nodes' => 0]);
$location = Location::factory()->create();
Node::factory()->create(['location_id' => $location->id]);
$response = $this->getJson('/api/application/locations/' . $location->id . '?include=nodes');
$response->assertStatus(Response::HTTP_OK);
$response->assertJsonCount(2)->assertJsonCount(1, 'attributes.relationships');
$response->assertJsonStructure([
'attributes' => [
'relationships' => [
'nodes' => ['object', 'attributes'],
],
],
]);
// Just assert that we see the expected relationship IDs in the response.
$response->assertJson([
'attributes' => [
'relationships' => [
'nodes' => [
'object' => 'null_resource',
'attributes' => null,
],
],
],
]);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
/**
@ -188,11 +162,7 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testErrorReturnedIfNoPermission()
{
$location = Location::factory()->create();
$this->createNewDefaultApiKey($this->getApiUser(), ['r_locations' => 0]);
$response = $this->getJson('/api/application/locations/' . $location->id);
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
/**
@ -201,9 +171,6 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testResourceIsNotExposedWithoutPermissions()
{
$this->createNewDefaultApiKey($this->getApiUser(), ['r_locations' => 0]);
$response = $this->getJson('/api/application/locations/nil');
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
}

View file

@ -59,7 +59,7 @@ class NestControllerTest extends ApplicationApiIntegrationTestCase
foreach ($nests as $nest) {
$response->assertJsonFragment([
'object' => 'nest',
'attributes' => $this->getTransformer(NestTransformer::class)->transform($nest),
'attributes' => (new NestTransformer())->transform($nest),
]);
}
}
@ -80,7 +80,7 @@ class NestControllerTest extends ApplicationApiIntegrationTestCase
$response->assertJson([
'object' => 'nest',
'attributes' => $this->getTransformer(NestTransformer::class)->transform($nest),
'attributes' => (new NestTransformer())->transform($nest),
]);
}
@ -122,11 +122,7 @@ class NestControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testErrorReturnedIfNoPermission()
{
$nest = $this->repository->find(1);
$this->createNewDefaultApiKey($this->getApiUser(), ['r_nests' => 0]);
$response = $this->getJson('/api/application/nests/' . $nest->id);
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
/**
@ -135,10 +131,6 @@ class NestControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testResourceIsNotExposedWithoutPermissions()
{
$nest = $this->repository->find(1);
$this->createNewDefaultApiKey($this->getApiUser(), ['r_nests' => 0]);
$response = $this->getJson('/api/application/nests/' . $nest->id);
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
}

View file

@ -58,11 +58,7 @@ class ExternalUserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testErrorReturnedIfNoPermission()
{
$user = User::factory()->create();
$this->createNewDefaultApiKey($this->getApiUser(), ['r_users' => 0]);
$response = $this->getJson('/api/application/users/external/' . $user->external_id);
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
/**
@ -71,9 +67,6 @@ class ExternalUserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testResourceIsNotExposedWithoutPermissions()
{
$this->createNewDefaultApiKey($this->getApiUser(), ['r_users' => 0]);
$response = $this->getJson('/api/application/users/external/nil');
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
}

View file

@ -16,7 +16,8 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testGetUsers()
{
$user = User::factory()->create();
$user = $this->getApiUser();
$created = User::factory()->create();
$response = $this->getJson('/api/application/users');
$response->assertStatus(Response::HTTP_OK);
@ -45,24 +46,6 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
],
],
])
->assertJsonFragment([
'object' => 'user',
'attributes' => [
'id' => $this->getApiUser()->id,
'external_id' => $this->getApiUser()->external_id,
'uuid' => $this->getApiUser()->uuid,
'username' => $this->getApiUser()->username,
'email' => $this->getApiUser()->email,
'language' => $this->getApiUser()->language,
'admin_role_id' => $this->getApiUser()->admin_role_id,
'root_admin' => (bool) $this->getApiUser()->root_admin,
'2fa' => (bool) $this->getApiUser()->totp_enabled,
'avatar_url' => $this->getApiUser()->avatarURL(),
'role_name' => $this->getApiUser()->adminRoleName(),
'created_at' => $this->formatTimestamp($this->getApiUser()->created_at),
'updated_at' => $this->formatTimestamp($this->getApiUser()->updated_at),
],
])
->assertJsonFragment([
'object' => 'user',
'attributes' => [
@ -80,6 +63,24 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
'created_at' => $this->formatTimestamp($user->created_at),
'updated_at' => $this->formatTimestamp($user->updated_at),
],
])
->assertJsonFragment([
'object' => 'user',
'attributes' => [
'id' => $created->id,
'external_id' => $created->external_id,
'uuid' => $created->uuid,
'username' => $created->username,
'email' => $created->email,
'language' => $created->language,
'admin_role_id' => $created->admin_role_id,
'root_admin' => (bool) $created->root_admin,
'2fa' => (bool) $created->totp_enabled,
'avatar_url' => $created->avatarURL(),
'role_name' => $created->adminRoleName(),
'created_at' => $this->formatTimestamp($created->created_at),
'updated_at' => $this->formatTimestamp($created->updated_at),
],
]);
}
@ -140,7 +141,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
'data' => [
[
'object' => 'server',
'attributes' => $this->getTransformer(ServerTransformer::class)->transform($server),
'attributes' => (new ServerTransformer())->transform($server),
],
],
]);
@ -152,33 +153,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testKeyWithoutPermissionCannotLoadRelationship()
{
$this->createNewDefaultApiKey($this->getApiUser(), ['r_servers' => 0]);
$user = User::factory()->create();
$this->createServerModel(['user_id' => $user->id]);
$response = $this->getJson('/api/application/users/' . $user->id . '?include=servers');
$response->assertStatus(Response::HTTP_OK);
$response->assertJsonCount(2)->assertJsonCount(1, 'attributes.relationships');
$response->assertJsonStructure([
'attributes' => [
'relationships' => [
'servers' => ['object', 'attributes'],
],
],
]);
// Just assert that we see the expected relationship IDs in the response.
$response->assertJson([
'attributes' => [
'relationships' => [
'servers' => [
'object' => 'null_resource',
'attributes' => null,
],
],
],
]);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
/**
@ -196,11 +171,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testErrorReturnedIfNoPermission()
{
$user = User::factory()->create();
$this->createNewDefaultApiKey($this->getApiUser(), ['r_users' => 0]);
$response = $this->getJson('/api/application/users/' . $user->id);
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
/**
@ -209,10 +180,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testResourceIsNotExposedWithoutPermissions()
{
$this->createNewDefaultApiKey($this->getApiUser(), ['r_users' => 0]);
$response = $this->getJson('/api/application/users/nil');
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
/**
@ -238,7 +206,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
$user = User::where('username', 'testuser')->first();
$response->assertJson([
'object' => 'user',
'attributes' => $this->getTransformer(UserTransformer::class)->transform($user),
'attributes' => (new UserTransformer())->transform($user),
'meta' => [
'resource' => route('api.application.users.view', $user->id),
],
@ -268,7 +236,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
$response->assertJson([
'object' => 'user',
'attributes' => $this->getTransformer(UserTransformer::class)->transform($user),
'attributes' => (new UserTransformer())->transform($user),
]);
}
@ -294,15 +262,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testApiKeyWithoutWritePermissions(string $method, string $url)
{
$this->createNewDefaultApiKey($this->getApiUser(), ['r_users' => AdminAcl::READ]);
if (str_contains($url, '{id}')) {
$user = User::factory()->create();
$url = str_replace('{id}', $user->id, $url);
}
$response = $this->$method($url);
$this->assertAccessDeniedJson($response);
$this->markTestSkipped('todo: implement proper admin api key permissions system');
}
/**

View file

@ -4,7 +4,8 @@ namespace Pterodactyl\Tests\Integration\Api\Client;
use Pterodactyl\Models\User;
use Illuminate\Http\Response;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Models\PersonalAccessToken;
use Pterodactyl\Transformers\Api\Client\PersonalAccessTokenTransformer;
class ApiKeyControllerTest extends ClientApiIntegrationTestCase
{
@ -13,7 +14,7 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
*/
protected function tearDown(): void
{
ApiKey::query()->forceDelete();
PersonalAccessToken::query()->forceDelete();
parent::tearDown();
}
@ -25,11 +26,8 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
{
/** @var \Pterodactyl\Models\User $user */
$user = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = ApiKey::factory()->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
$token = $user->createToken('test');
$token = $token->accessToken;
$response = $this->actingAs($user)->get('/api/client/account/api-keys');
@ -38,13 +36,14 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
'object' => 'list',
'data' => [
[
'object' => 'api_key',
'object' => 'personal_access_token',
'attributes' => [
'identifier' => $key->identifier,
'description' => $key->memo,
'allowed_ips' => $key->allowed_ips,
'token_id' => $token->token_id,
'description' => $token->description,
'abilities' => ['*'],
'last_used_at' => null,
'created_at' => $key->created_at->toIso8601String(),
'updated_at' => $this->formatTimestamp($token->updated_at),
'created_at' => $this->formatTimestamp($token->created_at),
],
],
],
@ -64,34 +63,24 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
// Small sub-test to ensure we're always comparing the number of keys to the
// specific logged in account, and not just the total number of keys stored in
// the database.
ApiKey::factory()->times(10)->create([
PersonalAccessToken::factory()->times(10)->create([
'user_id' => User::factory()->create()->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
$response = $this->actingAs($user)->postJson('/api/client/account/api-keys', [
'description' => 'Test Description',
'allowed_ips' => ['127.0.0.1'],
]);
$response->assertOk();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = ApiKey::query()->where('identifier', $response->json('attributes.identifier'))->firstOrFail();
$key = PersonalAccessToken::query()->where('token_id', $response->json('attributes.token_id'))->firstOrFail();
$response->assertJson([
'object' => 'api_key',
'attributes' => [
'identifier' => $key->identifier,
'description' => 'Test Description',
'allowed_ips' => ['127.0.0.1'],
'last_used_at' => null,
'created_at' => $key->created_at->toIso8601String(),
],
'meta' => [
'secret_token' => decrypt($key->token),
],
'object' => 'personal_access_token',
'attributes' => (new PersonalAccessTokenTransformer())->transform($key),
]);
$this->assertEquals($key->token, hash('sha256', substr($response->json('meta.secret_token'), 16)));
}
/**
@ -104,14 +93,10 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
{
/** @var \Pterodactyl\Models\User $user */
$user = User::factory()->create();
ApiKey::factory()->times(5)->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
PersonalAccessToken::factory()->times(10)->create(['user_id' => $user->id]);
$response = $this->actingAs($user)->postJson('/api/client/account/api-keys', [
'description' => 'Test Description',
'allowed_ips' => ['127.0.0.1'],
]);
$response->assertStatus(Response::HTTP_BAD_REQUEST);
@ -131,7 +116,6 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
$response = $this->actingAs($user)->postJson('/api/client/account/api-keys', [
'description' => '',
'allowed_ips' => ['127.0.0.1'],
]);
$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
@ -140,7 +124,6 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
$response = $this->actingAs($user)->postJson('/api/client/account/api-keys', [
'description' => str_repeat('a', 501),
'allowed_ips' => ['127.0.0.1'],
]);
$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
@ -155,16 +138,12 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
{
/** @var \Pterodactyl\Models\User $user */
$user = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = ApiKey::factory()->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
$token = $user->createToken('test');
$response = $this->actingAs($user)->delete('/api/client/account/api-keys/' . $key->identifier);
$response->assertStatus(Response::HTTP_NO_CONTENT);
$response = $this->actingAs($user)->delete('/api/client/account/api-keys/' . $token->accessToken->token_id);
$response->assertNoContent();
$this->assertDatabaseMissing('api_keys', ['id' => $key->id]);
$this->assertDatabaseMissing('personal_access_tokens', ['id' => $token->accessToken->id]);
}
/**
@ -174,16 +153,12 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
{
/** @var \Pterodactyl\Models\User $user */
$user = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = ApiKey::factory()->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
$token = $user->createToken('test');
$response = $this->actingAs($user)->delete('/api/client/account/api-keys/1234');
$response->assertNotFound();
$response = $this->actingAs($user)->delete('/api/client/account/api-keys/ptdl_1234');
$response->assertNoContent();
$this->assertDatabaseHas('api_keys', ['id' => $key->id]);
$this->assertDatabaseHas('personal_access_tokens', ['id' => $token->accessToken->id]);
}
/**
@ -196,35 +171,11 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
$user = User::factory()->create();
/** @var \Pterodactyl\Models\User $user2 */
$user2 = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = ApiKey::factory()->create([
'user_id' => $user2->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
$token = $user2->createToken('test');
$response = $this->actingAs($user)->delete('/api/client/account/api-keys/' . $key->identifier);
$response->assertNotFound();
$response = $this->actingAs($user)->delete('/api/client/account/api-keys/' . $token->accessToken->token_id);
$response->assertNoContent();
$this->assertDatabaseHas('api_keys', ['id' => $key->id]);
}
/**
* Tests that an application API key also belonging to the logged in user cannot be
* deleted through this endpoint if it exists.
*/
public function testApplicationApiKeyCannotBeDeleted()
{
/** @var \Pterodactyl\Models\User $user */
$user = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = ApiKey::factory()->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_APPLICATION,
]);
$response = $this->actingAs($user)->delete('/api/client/account/api-keys/' . $key->identifier);
$response->assertNotFound();
$this->assertDatabaseHas('api_keys', ['id' => $key->id]);
$this->assertDatabaseHas('personal_access_tokens', ['id' => $token->accessToken->id]);
}
}

View file

@ -6,7 +6,6 @@ use ReflectionClass;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Task;
use Pterodactyl\Models\User;
use Webmozart\Assert\Assert;
use InvalidArgumentException;
use Pterodactyl\Models\Backup;
use Pterodactyl\Models\Server;
@ -19,7 +18,6 @@ use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\DatabaseHost;
use Pterodactyl\Tests\Integration\TestResponse;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Transformers\Api\Client\BaseClientTransformer;
abstract class ClientApiIntegrationTestCase extends IntegrationTestCase
{
@ -61,7 +59,6 @@ abstract class ClientApiIntegrationTestCase extends IntegrationTestCase
*/
protected function link($model, $append = null): string
{
$link = '';
switch (get_class($model)) {
case Server::class:
$link = "/api/client/servers/{$model->uuid}";
@ -100,7 +97,6 @@ abstract class ClientApiIntegrationTestCase extends IntegrationTestCase
return [$user, $this->createServerModel(['user_id' => $user->id])];
}
/** @var \Pterodactyl\Models\Server $server */
$server = $this->createServerModel();
Subuser::query()->create([
@ -124,7 +120,6 @@ abstract class ClientApiIntegrationTestCase extends IntegrationTestCase
$transformer = sprintf('\\Pterodactyl\\Transformers\\Api\\Client\\%sTransformer', $reflect->getShortName());
$transformer = new $transformer();
$this->assertInstanceOf(BaseClientTransformer::class, $transformer);
$this->assertSame(
$transformer->transform($model),

View file

@ -89,7 +89,7 @@ class CreateServerScheduleTaskTest extends ClientApiIntegrationTestCase
}
/**
* Test that backups can not be tasked when the backup limit is 0
* Test that backups can not be tasked when the backup limit is 0.
*/
public function testBackupsCanNotBeTaskedIfLimit0()
{

View file

@ -23,7 +23,7 @@ class WebsocketControllerTest extends ClientApiIntegrationTestCase
$this->actingAs($user)->getJson("/api/client/servers/{$server->uuid}/websocket")
->assertStatus(Response::HTTP_FORBIDDEN)
->assertJsonPath('errors.0.code', 'HttpForbiddenException')
->assertJsonPath('errors.0.code', 'AccessDeniedHttpException')
->assertJsonPath('errors.0.detail', 'You do not have permission to connect to this server\'s websocket.');
}

View file

@ -6,7 +6,6 @@ use Carbon\CarbonImmutable;
use Pterodactyl\Tests\TestCase;
use Illuminate\Database\Eloquent\Model;
use Pterodactyl\Tests\Traits\Integration\CreatesTestModels;
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
abstract class IntegrationTestCase extends TestCase
{
@ -40,7 +39,7 @@ abstract class IntegrationTestCase extends TestCase
protected function formatTimestamp(string $timestamp): string
{
return CarbonImmutable::createFromFormat(CarbonImmutable::DEFAULT_TO_STRING_FORMAT, $timestamp)
->setTimezone(BaseTransformer::RESPONSE_TIMEZONE)
->setTimezone('UTC')
->toIso8601String();
}
}

View file

@ -3,12 +3,11 @@
namespace Pterodactyl\Tests\Integration\Jobs\Schedule;
use Mockery;
use Exception;
use Carbon\CarbonImmutable;
use Pterodactyl\Models\Task;
use GuzzleHttp\Psr7\Request;
use InvalidArgumentException;
use Pterodactyl\Models\Task;
use GuzzleHttp\Psr7\Response;
use InvalidArgumentException;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Schedule;
use Illuminate\Support\Facades\Bus;

View file

@ -8,7 +8,6 @@ use GuzzleHttp\Psr7\Response;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Allocation;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\TransferException;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Repositories\Wings\DaemonServerRepository;

View file

@ -20,7 +20,7 @@ trait IntegrationJsonRequestAssertions
[
'code' => 'NotFoundHttpException',
'status' => '404',
'detail' => 'The requested resource does not exist on this server.',
'detail' => 'The requested resource could not be found on the server.',
],
],
], true);

View file

@ -1,73 +0,0 @@
<?php
namespace Pterodactyl\Tests\Unit\Http\Middleware\Api;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Http\Middleware\Api\AuthenticateIPAccess;
use Pterodactyl\Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AuthenticateIPAccessTest extends MiddlewareTestCase
{
/**
* Test middleware when there are no IP restrictions.
*/
public function testWithNoIPRestrictions()
{
$model = ApiKey::factory()->make(['allowed_ips' => []]);
$this->setRequestAttribute('api_key', $model);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Test middleware works correctly when a valid IP accesses
* and there is an IP restriction.
*/
public function testWithValidIP()
{
$model = ApiKey::factory()->make(['allowed_ips' => ['127.0.0.1']]);
$this->setRequestAttribute('api_key', $model);
$this->request->shouldReceive('ip')->withNoArgs()->once()->andReturn('127.0.0.1');
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Test that a CIDR range can be used.
*/
public function testValidIPAgainstCIDRRange()
{
$model = ApiKey::factory()->make(['allowed_ips' => ['192.168.1.1/28']]);
$this->setRequestAttribute('api_key', $model);
$this->request->shouldReceive('ip')->withNoArgs()->once()->andReturn('192.168.1.15');
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Test that an exception is thrown when an invalid IP address
* tries to connect and there is an IP restriction.
*/
public function testWithInvalidIP()
{
$this->expectException(AccessDeniedHttpException::class);
$model = ApiKey::factory()->make(['allowed_ips' => ['127.0.0.1']]);
$this->setRequestAttribute('api_key', $model);
$this->request->shouldReceive('ip')->withNoArgs()->twice()->andReturn('127.0.0.2');
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Return an instance of the middleware to be used when testing.
*/
private function getMiddleware(): AuthenticateIPAccess
{
return new AuthenticateIPAccess();
}
}

View file

@ -1,168 +0,0 @@
<?php
namespace Pterodactyl\Tests\Unit\Http\Middleware\Api;
use Mockery as m;
use Carbon\CarbonImmutable;
use Pterodactyl\Models\User;
use Pterodactyl\Models\ApiKey;
use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Http\Middleware\Api\AuthenticateKey;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AuthenticateKeyTest extends MiddlewareTestCase
{
/**
* @var \Illuminate\Auth\AuthManager|\Mockery\Mock
*/
private $auth;
/**
* @var \Illuminate\Contracts\Encryption\Encrypter|\Mockery\Mock
*/
private $encrypter;
/**
* @var \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface|\Mockery\Mock
*/
private $repository;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->auth = m::mock(AuthManager::class);
$this->encrypter = m::mock(Encrypter::class);
$this->repository = m::mock(ApiKeyRepositoryInterface::class);
}
/**
* Test that a missing bearer token will throw an exception.
*/
public function testMissingBearerTokenThrowsException()
{
$this->request->shouldReceive('user')->andReturnNull();
$this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturnNull();
try {
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_APPLICATION);
} catch (HttpException $exception) {
$this->assertEquals(401, $exception->getStatusCode());
$this->assertEquals(['WWW-Authenticate' => 'Bearer'], $exception->getHeaders());
}
}
/**
* Test that an invalid API identifier throws an exception.
*/
public function testInvalidIdentifier()
{
$this->expectException(AccessDeniedHttpException::class);
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn('abcd1234');
$this->repository->shouldReceive('findFirstWhere')->andThrow(new RecordNotFoundException());
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_APPLICATION);
}
/**
* Test that a valid token can continue past the middleware.
*/
public function testValidToken()
{
$model = ApiKey::factory()->make();
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'decrypted');
$this->repository->shouldReceive('findFirstWhere')->with([
['identifier', '=', $model->identifier],
['key_type', '=', ApiKey::TYPE_APPLICATION],
])->once()->andReturn($model);
$this->encrypter->shouldReceive('decrypt')->with($model->token)->once()->andReturn('decrypted');
$this->auth->shouldReceive('guard->loginUsingId')->with($model->user_id)->once()->andReturnNull();
$this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, [
'last_used_at' => CarbonImmutable::now(),
])->once()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_APPLICATION);
$this->assertEquals($model, $this->request->attributes->get('api_key'));
}
/**
* Test that a valid token can continue past the middleware when set as a user token.
*/
public function testValidTokenWithUserKey()
{
$model = ApiKey::factory()->make();
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'decrypted');
$this->repository->shouldReceive('findFirstWhere')->with([
['identifier', '=', $model->identifier],
['key_type', '=', ApiKey::TYPE_ACCOUNT],
])->once()->andReturn($model);
$this->encrypter->shouldReceive('decrypt')->with($model->token)->once()->andReturn('decrypted');
$this->auth->shouldReceive('guard->loginUsingId')->with($model->user_id)->once()->andReturnNull();
$this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, [
'last_used_at' => CarbonImmutable::now(),
])->once()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_ACCOUNT);
$this->assertEquals($model, $this->request->attributes->get('api_key'));
}
/**
* Test that we can still make it though this middleware if the user is logged in and passing
* through a cookie.
*/
public function testAccessWithoutToken()
{
$user = User::factory()->make(['id' => 123]);
$this->request->shouldReceive('user')->andReturn($user);
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_ACCOUNT);
$model = $this->request->attributes->get('api_key');
$this->assertSame(ApiKey::TYPE_ACCOUNT, $model->key_type);
$this->assertSame(123, $model->user_id);
$this->assertNull($model->identifier);
}
/**
* Test that a valid token identifier with an invalid token attached to it
* triggers an exception.
*/
public function testInvalidTokenForIdentifier()
{
$this->expectException(AccessDeniedHttpException::class);
$model = ApiKey::factory()->make();
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'asdf');
$this->repository->shouldReceive('findFirstWhere')->with([
['identifier', '=', $model->identifier],
['key_type', '=', ApiKey::TYPE_APPLICATION],
])->once()->andReturn($model);
$this->encrypter->shouldReceive('decrypt')->with($model->token)->once()->andReturn('decrypted');
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_APPLICATION);
}
/**
* Return an instance of the middleware with mocked dependencies for testing.
*/
private function getMiddleware(): AuthenticateKey
{
return new AuthenticateKey($this->repository, $this->auth, $this->encrypter);
}
}

View file

@ -1,44 +0,0 @@
<?php
namespace Pterodactyl\Tests\Unit\Http\Middleware\Api;
use Mockery as m;
use Illuminate\Contracts\Config\Repository;
use Pterodactyl\Http\Middleware\Api\SetSessionDriver;
use Pterodactyl\Tests\Unit\Http\Middleware\MiddlewareTestCase;
class SetSessionDriverTest extends MiddlewareTestCase
{
/**
* @var \Illuminate\Contracts\Config\Repository|\Mockery\Mock
*/
private $config;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->config = m::mock(Repository::class);
}
/**
* Test that a production environment does not try to disable debug bar.
*/
public function testMiddleware()
{
$this->config->shouldReceive('set')->once()->with('session.driver', 'array')->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Return an instance of the middleware with mocked dependencies for testing.
*/
private function getMiddleware(): SetSessionDriver
{
return new SetSessionDriver($this->config);
}
}

View file

@ -6,8 +6,8 @@ use Mockery as m;
use Pterodactyl\Models\User;
use Pterodactyl\Models\WebauthnKey;
use Prologue\Alerts\AlertsMessageBag;
use Pterodactyl\Http\Middleware\RequireTwoFactorAuthentication;
use Pterodactyl\Exceptions\Http\TwoFactorAuthRequiredException;
use Pterodactyl\Http\Middleware\RequireTwoFactorAuthentication;
class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
{
@ -23,7 +23,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->alerts = m::mock(AlertsMessageBag::class);
}
public function testNoRequirement__userWithout_2fa()
public function testNoRequirementUserWithout2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_NONE);
@ -41,7 +41,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testNoRequirement__userWithTotp_2fa()
public function testNoRequirementUserWithTotp2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_NONE);
@ -59,7 +59,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testNoRequirement__userWithWebauthn_2fa()
public function testNoRequirementUserWithWebauthn2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_NONE);
@ -82,7 +82,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testNoRequirement__guestUser()
public function testNoRequirementGuestUser()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_NONE);
@ -96,7 +96,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAllRequirement__userWithout_2fa()
public function testAllRequirementUserWithout2fa()
{
$this->expectException(TwoFactorAuthRequiredException::class);
@ -116,7 +116,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAllRequirement__userWithTotp_2fa()
public function testAllRequirementUserWithTotp2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_ALL);
@ -134,7 +134,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAllRequirement__ruserWithWebauthn_2fa()
public function testAllRequirementRuserWithWebauthn2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_ALL);
@ -157,7 +157,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAllRequirement__guestUser()
public function testAllRequirementGuestUser()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_ALL);
@ -171,7 +171,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAdminRequirement__userWithout_2fa()
public function testAdminRequirementUserWithout2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_ADMIN);
@ -190,7 +190,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAdminRequirement__adminUserWithout_2fa()
public function testAdminRequirementAdminUserWithout2fa()
{
$this->expectException(TwoFactorAuthRequiredException::class);
@ -211,7 +211,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAdminRequirement__userWithTotp_2fa()
public function testAdminRequirementUserWithTotp2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_ADMIN);
@ -230,7 +230,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAdminRequirement__adminUserWithTotp_2fa()
public function testAdminRequirementAdminUserWithTotp2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_ADMIN);
@ -249,7 +249,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAdminRequirement__userWithWebauthn_2fa()
public function testAdminRequirementUserWithWebauthn2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_ADMIN);
@ -271,7 +271,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAdminRequirement__adminUserWithWebauthn_2fa()
public function testAdminRequirementAdminUserWithWebauthn2fa()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_ADMIN);
@ -295,7 +295,7 @@ class RequireTwoFactorAuthenticationTest extends MiddlewareTestCase
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
public function testAdminRequirement__guestUser()
public function testAdminRequirementGuestUser()
{
// Disable the 2FA requirement
config()->set('pterodactyl.auth.2fa_required', RequireTwoFactorAuthentication::LEVEL_ADMIN);

View file

@ -1,46 +0,0 @@
<?php
namespace Pterodactyl\Tests\Unit\Services\Acl\Api;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Tests\TestCase;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class AdminAclTest extends TestCase
{
/**
* Test that permissions return the expects values.
*
* @dataProvider permissionsDataProvider
*/
public function testPermissions(int $permission, int $check, bool $outcome)
{
$this->assertSame($outcome, AdminAcl::can($permission, $check));
}
/**
* Test that checking against a model works as expected.
*/
public function testCheck()
{
$model = ApiKey::factory()->make(['r_servers' => AdminAcl::READ | AdminAcl::WRITE]);
$this->assertTrue(AdminAcl::check($model, AdminAcl::RESOURCE_SERVERS, AdminAcl::WRITE));
}
/**
* Provide valid and invalid permissions combos for testing.
*/
public function permissionsDataProvider(): array
{
return [
[AdminAcl::READ, AdminAcl::READ, true],
[AdminAcl::READ | AdminAcl::WRITE, AdminAcl::READ, true],
[AdminAcl::READ | AdminAcl::WRITE, AdminAcl::WRITE, true],
[AdminAcl::WRITE, AdminAcl::WRITE, true],
[AdminAcl::READ, AdminAcl::WRITE, false],
[AdminAcl::NONE, AdminAcl::READ, false],
[AdminAcl::NONE, AdminAcl::WRITE, false],
];
}
}

View file

@ -1,167 +0,0 @@
<?php
namespace Pterodactyl\Tests\Unit\Services\Api;
use Mockery as m;
use phpmock\phpunit\PHPMock;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Tests\TestCase;
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Services\Api\KeyCreationService;
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
class KeyCreationServiceTest extends TestCase
{
use PHPMock;
/**
* @var \Illuminate\Contracts\Encryption\Encrypter|\Mockery\Mock
*/
private $encrypter;
/**
* @var \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface|\Mockery\Mock
*/
private $repository;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->encrypter = m::mock(Encrypter::class);
$this->repository = m::mock(ApiKeyRepositoryInterface::class);
}
/**
* Test that the service is able to create a keypair and assign the correct permissions.
*/
public function testKeyIsCreated()
{
$model = ApiKey::factory()->make();
$this->getFunctionMock('\\Pterodactyl\\Services\\Api', 'str_random')
->expects($this->exactly(2))->willReturnCallback(function ($length) {
return 'str_' . $length;
});
$this->encrypter->shouldReceive('encrypt')->with('str_' . ApiKey::KEY_LENGTH)->once()->andReturn($model->token);
$this->repository->shouldReceive('create')->with([
'test-data' => 'test',
'key_type' => ApiKey::TYPE_NONE,
'identifier' => 'str_' . ApiKey::IDENTIFIER_LENGTH,
'token' => $model->token,
], true, true)->once()->andReturn($model);
$response = $this->getService()->handle(['test-data' => 'test']);
$this->assertNotEmpty($response);
$this->assertInstanceOf(ApiKey::class, $response);
$this->assertSame($model, $response);
}
/**
* Test that an identifier is only set by the function.
*/
public function testIdentifierAndTokenAreOnlySetByFunction()
{
$model = ApiKey::factory()->make();
$this->getFunctionMock('\\Pterodactyl\\Services\\Api', 'str_random')
->expects($this->exactly(2))->willReturnCallback(function ($length) {
return 'str_' . $length;
});
$this->encrypter->shouldReceive('encrypt')->with('str_' . ApiKey::KEY_LENGTH)->once()->andReturn($model->token);
$this->repository->shouldReceive('create')->with([
'key_type' => ApiKey::TYPE_NONE,
'identifier' => 'str_' . ApiKey::IDENTIFIER_LENGTH,
'token' => $model->token,
], true, true)->once()->andReturn($model);
$response = $this->getService()->handle(['identifier' => 'customIdentifier', 'token' => 'customToken']);
$this->assertNotEmpty($response);
$this->assertInstanceOf(ApiKey::class, $response);
$this->assertSame($model, $response);
}
/**
* Test that permissions passed in are loaded onto the key data.
*/
public function testPermissionsAreRetrievedForApplicationKeys()
{
$model = ApiKey::factory()->make();
$this->getFunctionMock('\\Pterodactyl\\Services\\Api', 'str_random')
->expects($this->exactly(2))->willReturnCallback(function ($length) {
return 'str_' . $length;
});
$this->encrypter->shouldReceive('encrypt')->with('str_' . ApiKey::KEY_LENGTH)->once()->andReturn($model->token);
$this->repository->shouldReceive('create')->with([
'key_type' => ApiKey::TYPE_APPLICATION,
'identifier' => 'str_' . ApiKey::IDENTIFIER_LENGTH,
'token' => $model->token,
'permission-key' => 'exists',
], true, true)->once()->andReturn($model);
$response = $this->getService()->setKeyType(ApiKey::TYPE_APPLICATION)->handle([], ['permission-key' => 'exists']);
$this->assertNotEmpty($response);
$this->assertInstanceOf(ApiKey::class, $response);
$this->assertSame($model, $response);
}
/**
* Test that permissions are not retrieved for any key that is not an application key.
*
* @dataProvider keyTypeDataProvider
*/
public function testPermissionsAreNotRetrievedForNonApplicationKeys($keyType)
{
$model = ApiKey::factory()->make();
$this->getFunctionMock('\\Pterodactyl\\Services\\Api', 'str_random')
->expects($this->exactly(2))->willReturnCallback(function ($length) {
return 'str_' . $length;
});
$this->encrypter->shouldReceive('encrypt')->with('str_' . ApiKey::KEY_LENGTH)->once()->andReturn($model->token);
$this->repository->shouldReceive('create')->with([
'key_type' => $keyType,
'identifier' => 'str_' . ApiKey::IDENTIFIER_LENGTH,
'token' => $model->token,
], true, true)->once()->andReturn($model);
$response = $this->getService()->setKeyType($keyType)->handle([], ['fake-permission' => 'should-not-exist']);
$this->assertNotEmpty($response);
$this->assertInstanceOf(ApiKey::class, $response);
$this->assertSame($model, $response);
}
/**
* Provide key types that are not an application specific key.
*/
public function keyTypeDataProvider(): array
{
return [
[ApiKey::TYPE_NONE], [ApiKey::TYPE_ACCOUNT], [ApiKey::TYPE_DAEMON_USER], [ApiKey::TYPE_DAEMON_APPLICATION],
];
}
/**
* Return an instance of the service with mocked dependencies for testing.
*/
private function getService(): KeyCreationService
{
return new KeyCreationService($this->repository, $this->encrypter);
}
}