Initial pass at deleting as much removed logic as possible; still need to migrate old keys and permissions over

This commit is contained in:
Dane Everitt 2021-07-28 21:23:10 -07:00
parent dfff8ad667
commit b47d262ee0
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
19 changed files with 4 additions and 1036 deletions

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

@ -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);
}
}