Return Http test cases to a passing state

This commit is contained in:
Dane Everitt 2020-06-23 21:59:37 -07:00
parent eaae74fe33
commit 536180ed0c
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
26 changed files with 140 additions and 1113 deletions

View file

@ -1,110 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: Stan
* Date: 26-5-2018
* Time: 21:06.
*/
namespace Tests\Unit\Http\Controllers\Admin;
use Mockery as m;
use Pterodactyl\Models\Node;
use Tests\Assertions\ControllerAssertionsTrait;
use Tests\Unit\Http\Controllers\ControllerTestCase;
use Pterodactyl\Contracts\Repository\EggRepositoryInterface;
use Pterodactyl\Http\Controllers\Admin\StatisticsController;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
class StatisticsControllerTest extends ControllerTestCase
{
use ControllerAssertionsTrait;
/**
* @var \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface|\Mockery\Mock
*/
private $allocationRepository;
/**
* @var \Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface|\Mockery\Mock
*/
private $databaseRepository;
/**
* @var \Pterodactyl\Contracts\Repository\EggRepositoryInterface|\Mockery\Mock
*/
private $eggRepository;
/**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface|\Mockery\Mock
*/
private $nodeRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface|\Mockery\Mock
*/
private $serverRepository;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface|\Mockery\Mock
*/
private $userRepository;
public function setUp(): void
{
parent::setUp();
$this->allocationRepository = m::mock(AllocationRepositoryInterface::class);
$this->databaseRepository = m::mock(DatabaseRepositoryInterface::class);
$this->eggRepository = m::mock(EggRepositoryInterface::class);
$this->nodeRepository = m::mock(NodeRepositoryInterface::class);
$this->serverRepository = m::mock(ServerRepositoryInterface::class);
$this->userRepository = m::mock(UserRepositoryInterface::class);
}
public function testIndexController()
{
$controller = $this->getController();
$this->serverRepository->shouldReceive('all')->withNoArgs();
$this->nodeRepository->shouldReceive('all')->withNoArgs()->andReturn(collect([factory(Node::class)->make(), factory(Node::class)->make()]));
$this->userRepository->shouldReceive('count')->withNoArgs();
$this->eggRepository->shouldReceive('count')->withNoArgs();
$this->databaseRepository->shouldReceive('count')->withNoArgs();
$this->allocationRepository->shouldReceive('count')->withNoArgs();
$this->serverRepository->shouldReceive('getSuspendedServersCount')->withNoArgs();
$this->nodeRepository->shouldReceive('getUsageStatsRaw')->twice()->andReturn([
'memory' => [
'value' => 1024,
'max' => 512,
],
'disk' => [
'value' => 1024,
'max' => 512,
],
]);
$controller->shouldReceive('injectJavascript')->once();
$response = $controller->index();
$this->assertIsViewResponse($response);
$this->assertViewNameEquals('admin.statistics', $response);
}
private function getController()
{
return $this->buildMockedController(StatisticsController::class, [$this->allocationRepository,
$this->databaseRepository,
$this->eggRepository,
$this->nodeRepository,
$this->serverRepository,
$this->userRepository, ]
);
}
}

View file

@ -1,181 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Tests\Unit\Http\Controllers\Base;
use Mockery as m;
use Pterodactyl\Models\User;
use GuzzleHttp\Psr7\Response;
use Pterodactyl\Models\Server;
use GuzzleHttp\Psr7\ServerRequest;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use Tests\Assertions\ControllerAssertionsTrait;
use Tests\Unit\Http\Controllers\ControllerTestCase;
use Pterodactyl\Http\Controllers\Base\IndexController;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonServerRepositoryInterface;
class IndexControllerTest extends ControllerTestCase
{
use ControllerAssertionsTrait;
/**
* @var \Pterodactyl\Http\Controllers\Base\IndexController
*/
protected $controller;
/**
* @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface|\Mockery\Mock
*/
protected $daemonRepository;
/**
* @var \Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService|\Mockery\Mock
*/
protected $keyProviderService;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface|\Mockery\Mock
*/
protected $repository;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->daemonRepository = m::mock(DaemonServerRepositoryInterface::class);
$this->keyProviderService = m::mock(DaemonKeyProviderService::class);
$this->repository = m::mock(ServerRepositoryInterface::class);
$this->controller = new IndexController($this->keyProviderService, $this->daemonRepository, $this->repository);
}
/**
* Test the index controller.
*/
public function testIndexController()
{
$paginator = m::mock(LengthAwarePaginator::class);
$model = $this->generateRequestUserModel();
$this->request->shouldReceive('input')->with('query')->once()->andReturn('searchTerm');
$this->repository->shouldReceive('setSearchTerm')->with('searchTerm')->once()->andReturnSelf()
->shouldReceive('filterUserAccessServers')->with($model, User::FILTER_LEVEL_ALL, config('pterodactyl.paginate.frontend.servers'))
->once()->andReturn($paginator);
$response = $this->controller->index($this->request);
$this->assertIsViewResponse($response);
$this->assertViewNameEquals('templates.base.core', $response);
$this->assertViewHasKey('servers', $response);
$this->assertViewKeyEquals('servers', $paginator, $response);
}
/**
* Test the status controller.
*/
public function testStatusController()
{
$user = $this->generateRequestUserModel();
$server = factory(Server::class)->make(['suspended' => 0, 'installed' => 1]);
$psrResponse = new Response;
$this->repository->shouldReceive('findFirstWhere')->with([['uuidShort', '=', $server->uuidShort]])->once()->andReturn($server);
$this->keyProviderService->shouldReceive('handle')->with($server, $user)->once()->andReturn('test123');
$this->daemonRepository->shouldReceive('setServer')->with($server)->once()->andReturnSelf()
->shouldReceive('setToken')->with('test123')->once()->andReturnSelf()
->shouldReceive('details')->withNoArgs()->once()->andReturn($psrResponse);
$response = $this->controller->status($this->request, $server->uuidShort);
$this->assertIsJsonResponse($response);
$this->assertResponseJsonEquals(json_encode($psrResponse->getBody()), $response);
}
/**
* Test the status controller if a server is not installed.
*/
public function testStatusControllerWhenServerNotInstalled()
{
$user = $this->generateRequestUserModel();
$server = factory(Server::class)->make(['suspended' => 0, 'installed' => 0]);
$this->repository->shouldReceive('findFirstWhere')->with([['uuidShort', '=', $server->uuidShort]])->once()->andReturn($server);
$this->keyProviderService->shouldReceive('handle')->with($server, $user)->once()->andReturn('test123');
$response = $this->controller->status($this->request, $server->uuidShort);
$this->assertIsJsonResponse($response);
$this->assertResponseCodeEquals(200, $response);
$this->assertResponseJsonEquals(['status' => 20], $response);
}
/**
* Test the status controller when a server is suspended.
*/
public function testStatusControllerWhenServerIsSuspended()
{
$user = factory(User::class)->make();
$server = factory(Server::class)->make(['suspended' => 1, 'installed' => 1]);
$this->request->shouldReceive('user')->withNoArgs()->once()->andReturn($user);
$this->repository->shouldReceive('findFirstWhere')->with([['uuidShort', '=', $server->uuidShort]])->once()->andReturn($server);
$this->keyProviderService->shouldReceive('handle')->with($server, $user)->once()->andReturn('test123');
$response = $this->controller->status($this->request, $server->uuidShort);
$this->assertIsJsonResponse($response);
$this->assertResponseCodeEquals(200, $response);
$this->assertResponseJsonEquals(['status' => 30], $response);
}
/**
* Test the status controller with a ServerConnectionException.
*/
public function testStatusControllerWithServerConnectionException()
{
$user = factory(User::class)->make();
$server = factory(Server::class)->make(['suspended' => 0, 'installed' => 1]);
$this->request->shouldReceive('user')->withNoArgs()->once()->andReturn($user);
$this->repository->shouldReceive('findFirstWhere')->with([['uuidShort', '=', $server->uuidShort]])->once()->andReturn($server);
$this->keyProviderService->shouldReceive('handle')->with($server, $user)->once()->andReturn('test123');
$this->daemonRepository->shouldReceive('setServer')->with($server)->once()->andReturnSelf()
->shouldReceive('setToken')->with('test123')->once()->andReturnSelf()
->shouldReceive('details')->withNoArgs()->once()->andThrow(new ConnectException('bad connection', new ServerRequest('', '')));
$this->expectExceptionObject(new HttpException(500, 'bad connection'));
$this->controller->status($this->request, $server->uuidShort);
}
/**
* Test the status controller with a RequestException.
*/
public function testStatusControllerWithRequestException()
{
$user = factory(User::class)->make();
$server = factory(Server::class)->make(['suspended' => 0, 'installed' => 1]);
$this->request->shouldReceive('user')->withNoArgs()->once()->andReturn($user);
$this->repository->shouldReceive('findFirstWhere')->with([['uuidShort', '=', $server->uuidShort]])->once()->andReturn($server);
$this->keyProviderService->shouldReceive('handle')->with($server, $user)->once()->andReturn('test123');
$this->daemonRepository->shouldReceive('setServer')->with($server)->once()->andReturnSelf()
->shouldReceive('setToken')->with('test123')->once()->andReturnSelf()
->shouldReceive('details')->withNoArgs()->once()->andThrow(new RequestException('bad request', new ServerRequest('', '')));
$this->expectExceptionObject(new HttpException(500, 'bad request'));
$this->controller->status($this->request, $server->uuidShort);
}
}

View file

@ -1,156 +0,0 @@
<?php
namespace Tests\Unit\Http\Controllers\Base;
use Mockery as m;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Prologue\Alerts\AlertsMessageBag;
use Illuminate\Contracts\Config\Repository;
use Tests\Unit\Http\Controllers\ControllerTestCase;
use Pterodactyl\Services\Users\TwoFactorSetupService;
use Pterodactyl\Services\Users\ToggleTwoFactorService;
use Pterodactyl\Http\Controllers\Base\SecurityController;
use Pterodactyl\Contracts\Repository\SessionRepositoryInterface;
use Pterodactyl\Exceptions\Service\User\TwoFactorAuthenticationTokenInvalid;
class SecurityControllerTest extends ControllerTestCase
{
/**
* @var \Prologue\Alerts\AlertsMessageBag|\Mockery\Mock
*/
protected $alert;
/**
* @var \Illuminate\Contracts\Config\Repository|\Mockery\Mock
*/
protected $config;
/**
* @var \Pterodactyl\Contracts\Repository\SessionRepositoryInterface|\Mockery\Mock
*/
protected $repository;
/**
* @var \Pterodactyl\Services\Users\ToggleTwoFactorService|\Mockery\Mock
*/
protected $toggleTwoFactorService;
/**
* @var \Pterodactyl\Services\Users\TwoFactorSetupService|\Mockery\Mock
*/
protected $twoFactorSetupService;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->alert = m::mock(AlertsMessageBag::class);
$this->config = m::mock(Repository::class);
$this->repository = m::mock(SessionRepositoryInterface::class);
$this->toggleTwoFactorService = m::mock(ToggleTwoFactorService::class);
$this->twoFactorSetupService = m::mock(TwoFactorSetupService::class);
}
/**
* Test TOTP generation controller.
*/
public function testIndexWithout2FactorEnabled()
{
$model = $this->generateRequestUserModel(['use_totp' => 0]);
$this->twoFactorSetupService->shouldReceive('handle')->with($model)->once()->andReturn(new Collection([
'image' => 'test-image',
'secret' => 'secret-code',
]));
$response = $this->getController()->index($this->request);
$this->assertIsJsonResponse($response);
$this->assertResponseCodeEquals(Response::HTTP_OK, $response);
$this->assertResponseJsonEquals(['enabled' => false, 'qr_image' => 'test-image', 'secret' => 'secret-code'], $response);
$this->assertResponseJsonEquals(['qrImage' => 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=qrCodeImage'], $response);
}
/**
* Test TOTP setting controller when no exception is thrown by the service.
*/
public function testIndexWith2FactorEnabled()
{
$this->generateRequestUserModel(['use_totp' => 1]);
$response = $this->getController()->index($this->request);
$this->assertIsJsonResponse($response);
$this->assertResponseCodeEquals(Response::HTTP_OK, $response);
$this->assertResponseJsonEquals(['enabled' => true], $response);
}
/**
* Test that a 2FA token can be stored or deleted.
*
* @param string $func
* @dataProvider functionCallDataProvider
*/
public function testStore(string $func)
{
$model = $this->generateRequestUserModel();
$this->mockRequestInput('token', 'some-token');
if ($func === 'delete') {
$this->toggleTwoFactorService->shouldReceive('handle')->with($model, 'some-token', false);
} else {
$this->toggleTwoFactorService->shouldReceive('handle')->with($model, 'some-token');
}
$response = $this->getController()->{$func}($this->request);
$this->assertIsJsonResponse($response);
$this->assertResponseCodeEquals(Response::HTTP_OK, $response);
$this->assertResponseJsonEquals(['success' => true], $response);
}
/**
* Test an invalid token exception is handled.
*
* @param string $func
* @dataProvider functionCallDataProvider
*/
public function testStoreWithInvalidTokenException(string $func)
{
$this->generateRequestUserModel();
$this->mockRequestInput('token');
$this->toggleTwoFactorService->shouldReceive('handle')->andThrow(new TwoFactorAuthenticationTokenInvalid);
$response = $this->getController()->{$func}($this->request);
$this->assertIsJsonResponse($response);
$this->assertResponseCodeEquals(Response::HTTP_OK, $response);
$this->assertResponseJsonEquals(['success' => false], $response);
}
/**
* @return array
*/
public function functionCallDataProvider()
{
return [['store'], ['delete']];
}
/**
* Return an instance of the controller for testing with mocked dependencies.
*
* @return \Pterodactyl\Http\Controllers\Base\SecurityController
*/
private function getController(): SecurityController
{
return new SecurityController(
$this->alert,
$this->config,
$this->repository,
$this->toggleTwoFactorService,
$this->twoFactorSetupService
);
}
}

View file

@ -4,6 +4,7 @@ namespace Tests\Unit\Http\Middleware;
use Pterodactyl\Models\User;
use Pterodactyl\Http\Middleware\AdminAuthenticate;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AdminAuthenticateTest extends MiddlewareTestCase
{
@ -21,11 +22,11 @@ class AdminAuthenticateTest extends MiddlewareTestCase
/**
* Test that a missing user in the request triggers an error.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testExceptionIsThrownIfUserDoesNotExist()
{
$this->expectException(AccessDeniedHttpException::class);
$this->request->shouldReceive('user')->withNoArgs()->once()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
@ -33,11 +34,11 @@ class AdminAuthenticateTest extends MiddlewareTestCase
/**
* Test that an exception is thrown if the user is not an admin.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testExceptionIsThrownIfUserIsNotAnAdmin()
{
$this->expectException(AccessDeniedHttpException::class);
$user = factory(User::class)->make(['root_admin' => 0]);
$this->request->shouldReceive('user')->withNoArgs()->twice()->andReturn($user);

View file

@ -1,19 +1,20 @@
<?php
namespace Tests\Unit\Http\Middleware\API\Application;
namespace Tests\Unit\Http\Middleware\Api\Application;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Pterodactyl\Http\Middleware\Api\Application\AuthenticateApplicationUser;
class AuthenticateUserTest extends MiddlewareTestCase
{
/**
* Test that no user defined results in an access denied exception.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testNoUserDefined()
{
$this->expectException(AccessDeniedHttpException::class);
$this->setRequestUserModel(null);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
@ -21,11 +22,11 @@ class AuthenticateUserTest extends MiddlewareTestCase
/**
* Test that a non-admin user results an an exception.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testNonAdminUser()
{
$this->expectException(AccessDeniedHttpException::class);
$this->generateRequestUserModel(['root_admin' => false]);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());

View file

@ -1,10 +1,11 @@
<?php
namespace Tests\Unit\Http\Middleware\API;
namespace Tests\Unit\Http\Middleware\Api;
use Pterodactyl\Models\ApiKey;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Http\Middleware\Api\AuthenticateIPAccess;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AuthenticateIPAccessTest extends MiddlewareTestCase
{
@ -49,11 +50,11 @@ class AuthenticateIPAccessTest extends MiddlewareTestCase
/**
* Test that an exception is thrown when an invalid IP address
* tries to connect and there is an IP restriction.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testWithInvalidIP()
{
$this->expectException(AccessDeniedHttpException::class);
$model = factory(ApiKey::class)->make(['allowed_ips' => '["127.0.0.1"]']);
$this->setRequestAttribute('api_key', $model);

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Unit\Http\Middleware\API;
namespace Tests\Unit\Http\Middleware\Api;
use Mockery as m;
use Cake\Chronos\Chronos;
@ -13,6 +13,7 @@ use Pterodactyl\Http\Middleware\Api\AuthenticateKey;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AuthenticateKeyTest extends MiddlewareTestCase
{
@ -62,11 +63,11 @@ class AuthenticateKeyTest extends MiddlewareTestCase
/**
* Test that an invalid API identifier throws an exception.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testInvalidIdentifier()
{
$this->expectException(AccessDeniedHttpException::class);
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn('abcd1234');
$this->repository->shouldReceive('findFirstWhere')->andThrow(new RecordNotFoundException);
@ -141,11 +142,11 @@ class AuthenticateKeyTest extends MiddlewareTestCase
/**
* Test that a valid token identifier with an invalid token attached to it
* triggers an exception.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testInvalidTokenForIdentifier()
{
$this->expectException(AccessDeniedHttpException::class);
$model = factory(ApiKey::class)->make();
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'asdf');

View file

@ -4,19 +4,27 @@ namespace Tests\Unit\Http\Middleware\Api\Daemon;
use Mockery as m;
use Pterodactyl\Models\Node;
use Illuminate\Contracts\Encryption\Encrypter;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Repositories\Eloquent\NodeRepository;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Http\Middleware\Api\Daemon\DaemonAuthenticate;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class DaemonAuthenticateTest extends MiddlewareTestCase
{
/**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface|\Mockery\Mock
* @var \Mockery\MockInterface
*/
private $repository;
/**
* @var \Mockery\MockInterface
*/
private $encrypter;
/**
* Setup tests.
*/
@ -24,7 +32,8 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
{
parent::setUp();
$this->repository = m::mock(NodeRepositoryInterface::class);
$this->encrypter = m::mock(Encrypter::class);
$this->repository = m::mock(NodeRepository::class);
}
/**
@ -33,7 +42,7 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
*/
public function testResponseShouldContinueIfRouteIsExempted()
{
$this->request->shouldReceive('route->getName')->withNoArgs()->once()->andReturn('daemon.configuration');
$this->request->expects('route->getName')->withNoArgs()->andReturn('daemon.configuration');
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
@ -44,8 +53,8 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
*/
public function testResponseShouldFailIfNoTokenIsProvided()
{
$this->request->shouldReceive('route->getName')->withNoArgs()->once()->andReturn('random.route');
$this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturnNull();
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturnNull();
try {
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
@ -58,17 +67,54 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
}
/**
* Test that passing in an invalid node daemon secret will result in a HTTP/403
* error response.
* Test that passing in an invalid node daemon secret will result in a bad request
* exception being returned.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
* @param string $token
* @dataProvider badTokenDataProvider
*/
public function testResponseShouldFailIfNoNodeIsFound()
public function testResponseShouldFailIfTokenFormatIsIncorrect(string $token)
{
$this->request->shouldReceive('route->getName')->withNoArgs()->once()->andReturn('random.route');
$this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturn('test1234');
$this->expectException(BadRequestHttpException::class);
$this->repository->shouldReceive('findFirstWhere')->with([['daemonSecret', '=', 'test1234']])->once()->andThrow(new RecordNotFoundException);
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn($token);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Test that an access denied error is returned if the node is valid but the token
* provided is not valid.
*/
public function testResponseShouldFailIfTokenIsNotValid()
{
$this->expectException(AccessDeniedHttpException::class);
/** @var \Pterodactyl\Models\Node $model */
$model = factory(Node::class)->make();
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn($model->daemon_token_id . '.random_string_123');
$this->repository->expects('findFirstWhere')->with(['daemon_token_id' => $model->daemon_token_id])->andReturn($model);
$this->encrypter->expects('decrypt')->with($model->daemon_token)->andReturns(decrypt($model->daemon_token));
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Test that an access denied exception is returned if the node is not found using
* the token ID provided.
*/
public function testResponseShouldFailIfNodeIsNotFound()
{
$this->expectException(AccessDeniedHttpException::class);
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn('abcd1234.random_string_123');
$this->repository->expects('findFirstWhere')->with(['daemon_token_id' => 'abcd1234'])->andThrow(RecordNotFoundException::class);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
@ -78,18 +124,39 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
*/
public function testSuccessfulMiddlewareProcess()
{
/** @var \Pterodactyl\Models\Node $model */
$model = factory(Node::class)->make();
$this->request->shouldReceive('route->getName')->withNoArgs()->once()->andReturn('random.route');
$this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturn($model->daemonSecret);
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn($model->daemon_token_id . '.' . decrypt($model->daemon_token));
$this->repository->shouldReceive('findFirstWhere')->with([['daemonSecret', '=', $model->daemonSecret]])->once()->andReturn($model);
$this->repository->expects('findFirstWhere')->with(['daemon_token_id' => $model->daemon_token_id])->andReturn($model);
$this->encrypter->expects('decrypt')->with($model->daemon_token)->andReturns(decrypt($model->daemon_token));
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestHasAttribute('node');
$this->assertRequestAttributeEquals($model, 'node');
}
/**
* Provides different tokens that should trigger a bad request exception due to
* their formatting.
*
* @return array|\string[][]
*/
public function badTokenDataProvider(): array
{
return [
['foo'],
['foobar'],
['foo-bar'],
['foo.bar.baz'],
['.foo'],
['foo.'],
['foo..bar'],
];
}
/**
* Return an instance of the middleware using mocked dependencies.
*
@ -97,6 +164,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
*/
private function getMiddleware(): DaemonAuthenticate
{
return new DaemonAuthenticate($this->repository);
return new DaemonAuthenticate($this->encrypter, $this->repository);
}
}

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Unit\Http\Middleware\API;
namespace Tests\Unit\Http\Middleware\Api;
use Mockery as m;
use Illuminate\Contracts\Config\Repository;

View file

@ -2,6 +2,7 @@
namespace Tests\Unit\Http\Middleware;
use Illuminate\Auth\AuthenticationException;
use Pterodactyl\Http\Middleware\Authenticate;
class AuthenticateTest extends MiddlewareTestCase
@ -18,11 +19,11 @@ class AuthenticateTest extends MiddlewareTestCase
/**
* Test that a logged out user results in an exception.
*
* @expectedException \Illuminate\Auth\AuthenticationException
*/
public function testLoggedOutUser()
{
$this->expectException(AuthenticationException::class);
$this->request->shouldReceive('user')->withNoArgs()->once()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());

View file

@ -1,78 +0,0 @@
<?php
namespace Tests\Unit\Http\Middleware;
use Mockery as m;
use Pterodactyl\Models\Node;
use Pterodactyl\Http\Middleware\DaemonAuthenticate;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
class DaemonAuthenticateTest extends MiddlewareTestCase
{
/**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface|\Mockery\Mock
*/
private $repository;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->repository = m::mock(NodeRepositoryInterface::class);
}
/**
* Test a valid daemon connection.
*/
public function testValidDaemonConnection()
{
$this->setRequestRouteName('random.name');
$node = factory(Node::class)->make();
$this->request->shouldReceive('header')->with('X-Access-Node')->twice()->andReturn($node->daemonSecret);
$this->repository->shouldReceive('findFirstWhere')->with(['daemonSecret' => $node->daemonSecret])->once()->andReturn($node);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestHasAttribute('node');
$this->assertRequestAttributeEquals($node, 'node');
}
/**
* Test that ignored routes do not continue through the middleware.
*/
public function testIgnoredRouteShouldContinue()
{
$this->setRequestRouteName('daemon.configuration');
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestMissingAttribute('node');
}
/**
* Test that a request missing a X-Access-Node header causes an exception.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testExceptionThrownIfMissingHeader()
{
$this->setRequestRouteName('random.name');
$this->request->shouldReceive('header')->with('X-Access-Node')->once()->andReturn(false);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\DaemonAuthenticate
*/
private function getMiddleware(): DaemonAuthenticate
{
return new DaemonAuthenticate($this->repository);
}
}

View file

@ -9,6 +9,8 @@ use Illuminate\Contracts\Routing\ResponseFactory;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Http\Middleware\Server\AccessingValidServer;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AccessingValidServerTest extends MiddlewareTestCase
{
@ -41,12 +43,12 @@ class AccessingValidServerTest extends MiddlewareTestCase
/**
* Test that an exception is thrown if the request is an API request and the server is suspended.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
* @expectedExceptionMessage Server is suspended and cannot be accessed.
*/
public function testExceptionIsThrownIfServerIsSuspended()
{
$this->expectException(AccessDeniedHttpException::class);
$this->expectExceptionMessage('Server is suspended and cannot be accessed.');
$model = factory(Server::class)->make(['suspended' => 1]);
$this->request->shouldReceive('route->parameter')->with('server')->once()->andReturn('123456');
@ -59,12 +61,12 @@ class AccessingValidServerTest extends MiddlewareTestCase
/**
* Test that an exception is thrown if the request is an API request and the server is not installed.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\ConflictHttpException
* @expectedExceptionMessage Server is still completing the installation process.
*/
public function testExceptionIsThrownIfServerIsNotInstalled()
{
$this->expectException(ConflictHttpException::class);
$this->expectExceptionMessage('Server is still completing the installation process.');
$model = factory(Server::class)->make(['installed' => 0]);
$this->request->shouldReceive('route->parameter')->with('server')->once()->andReturn('123456');

View file

@ -8,6 +8,7 @@ use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Http\Middleware\Server\AuthenticateAsSubuser;
use Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AuthenticateAsSubuserTest extends MiddlewareTestCase
{
@ -44,12 +45,12 @@ class AuthenticateAsSubuserTest extends MiddlewareTestCase
/**
* Test middleware handles missing token exception.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
* @expectedExceptionMessage This account does not have permission to access this server.
*/
public function testExceptionIsThrownIfNoTokenIsFound()
{
$this->expectException(AccessDeniedHttpException::class);
$this->expectExceptionMessage('This account does not have permission to access this server.');
$model = factory(Server::class)->make();
$user = $this->setRequestUser();
$this->setRequestAttribute('server', $model);

View file

@ -1,92 +0,0 @@
<?php
namespace Tests\Unit\Http\Middleware\Server;
use Mockery as m;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Database;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Http\Middleware\Server\DatabaseBelongsToServer;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
class DatabaseBelongsToServerTest extends MiddlewareTestCase
{
/**
* @var \Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface|\Mockery\Mock
*/
private $repository;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->repository = m::mock(DatabaseRepositoryInterface::class);
}
/**
* Test a successful middleware instance.
*/
public function testSuccessfulMiddleware()
{
$model = factory(Server::class)->make();
$database = factory(Database::class)->make([
'server_id' => $model->id,
]);
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('input')->with('database')->once()->andReturn($database->id);
$this->repository->shouldReceive('find')->with($database->id)->once()->andReturn($database);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestHasAttribute('database');
$this->assertRequestAttributeEquals($database, 'database');
}
/**
* Test that an exception is thrown if no database record is found.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testExceptionIsThrownIfNoDatabaseRecordFound()
{
$model = factory(Server::class)->make();
$database = factory(Database::class)->make();
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('input')->with('database')->once()->andReturn($database->id);
$this->repository->shouldReceive('find')->with($database->id)->once()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Test that an exception is found if the database server does not match the
* request server.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testExceptionIsThrownIfDatabaseServerDoesNotMatchCurrent()
{
$model = factory(Server::class)->make();
$database = factory(Database::class)->make();
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('input')->with('database')->once()->andReturn($database->id);
$this->repository->shouldReceive('find')->with($database->id)->once()->andReturn($database);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\Server\DatabaseBelongsToServer
*/
private function getMiddleware(): DatabaseBelongsToServer
{
return new DatabaseBelongsToServer($this->repository);
}
}

View file

@ -1,81 +0,0 @@
<?php
namespace Tests\Unit\Http\Middleware\Server;
use Mockery as m;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Schedule;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Contracts\Extensions\HashidsInterface;
use Pterodactyl\Http\Middleware\Server\ScheduleBelongsToServer;
use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface;
class ScheduleBelongsToServerTest extends MiddlewareTestCase
{
/**
* @var \Pterodactyl\Contracts\Extensions\HashidsInterface|\Mockery\Mock
*/
private $hashids;
/**
* @var \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface|\Mockery\Mock
*/
private $repository;
public function setUp(): void
{
parent::setUp();
$this->hashids = m::mock(HashidsInterface::class);
$this->repository = m::mock(ScheduleRepositoryInterface::class);
}
/**
* Test a successful middleware instance.
*/
public function testSuccessfulMiddleware()
{
$model = factory(Server::class)->make();
$schedule = factory(Schedule::class)->make([
'server_id' => $model->id,
]);
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('route->parameter')->with('schedule')->once()->andReturn('abc123');
$this->hashids->shouldReceive('decodeFirst')->with('abc123', 0)->once()->andReturn($schedule->id);
$this->repository->shouldReceive('getScheduleWithTasks')->with($schedule->id)->once()->andReturn($schedule);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestHasAttribute('schedule');
$this->assertRequestAttributeEquals($schedule, 'schedule');
}
/**
* Test that an exception is thrown if the schedule does not belong to
* the request server.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testExceptionIsThrownIfScheduleDoesNotBelongToServer()
{
$model = factory(Server::class)->make();
$schedule = factory(Schedule::class)->make();
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('route->parameter')->with('schedule')->once()->andReturn('abc123');
$this->hashids->shouldReceive('decodeFirst')->with('abc123', 0)->once()->andReturn($schedule->id);
$this->repository->shouldReceive('getScheduleWithTasks')->with($schedule->id)->once()->andReturn($schedule);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\Server\ScheduleBelongsToServer
*/
private function getMiddleware(): ScheduleBelongsToServer
{
return new ScheduleBelongsToServer($this->hashids, $this->repository);
}
}

View file

@ -1,156 +0,0 @@
<?php
namespace Tests\Unit\Http\Middleware\Server;
use Mockery as m;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Exceptions\PterodactylException;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Contracts\Extensions\HashidsInterface;
use Pterodactyl\Http\Middleware\Server\SubuserBelongsToServer;
use Pterodactyl\Contracts\Repository\SubuserRepositoryInterface;
class SubuserBelongsToServerTest extends MiddlewareTestCase
{
/**
* @var \Pterodactyl\Contracts\Extensions\HashidsInterface|\Mockery\Mock
*/
private $hashids;
/**
* @var \Pterodactyl\Contracts\Repository\SubuserRepositoryInterface|\Mockery\Mock
*/
private $repository;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->hashids = m::mock(HashidsInterface::class);
$this->repository = m::mock(SubuserRepositoryInterface::class);
}
/**
* Test a successful middleware instance.
*/
public function testSuccessfulMiddleware()
{
$model = factory(Server::class)->make();
$subuser = factory(Subuser::class)->make([
'server_id' => $model->id,
]);
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('route->parameter')->with('subuser', 0)->once()->andReturn('abc123');
$this->hashids->shouldReceive('decodeFirst')->with('abc123', 0)->once()->andReturn($subuser->id);
$this->repository->shouldReceive('find')->with($subuser->id)->once()->andReturn($subuser);
$this->request->shouldReceive('method')->withNoArgs()->once()->andReturn('GET');
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestHasAttribute('subuser');
$this->assertRequestAttributeEquals($subuser, 'subuser');
}
/**
* Test that a user can edit a user other than themselves.
*/
public function testSuccessfulMiddlewareWhenPatchRequest()
{
$this->setRequestUser();
$model = factory(Server::class)->make();
$subuser = factory(Subuser::class)->make([
'server_id' => $model->id,
]);
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('route->parameter')->with('subuser', 0)->once()->andReturn('abc123');
$this->hashids->shouldReceive('decodeFirst')->with('abc123', 0)->once()->andReturn($subuser->id);
$this->repository->shouldReceive('find')->with($subuser->id)->once()->andReturn($subuser);
$this->request->shouldReceive('method')->withNoArgs()->once()->andReturn('PATCH');
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestHasAttribute('subuser');
$this->assertRequestAttributeEquals($subuser, 'subuser');
}
/**
* Test that an exception is thrown if a user attempts to edit themself.
*/
public function testExceptionIsThrownIfUserTriesToEditSelf()
{
$user = $this->setRequestUser();
$model = factory(Server::class)->make();
$subuser = factory(Subuser::class)->make([
'server_id' => $model->id,
'user_id' => $user->id,
]);
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('route->parameter')->with('subuser', 0)->once()->andReturn('abc123');
$this->hashids->shouldReceive('decodeFirst')->with('abc123', 0)->once()->andReturn($subuser->id);
$this->repository->shouldReceive('find')->with($subuser->id)->once()->andReturn($subuser);
$this->request->shouldReceive('method')->withNoArgs()->once()->andReturn('PATCH');
try {
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
} catch (PterodactylException $exception) {
$this->assertInstanceOf(DisplayException::class, $exception);
$this->assertEquals(trans('exceptions.subusers.editing_self'), $exception->getMessage());
}
}
/**
* Test that an exception is thrown if a subuser server does not match the
* request server.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testExceptionIsThrownIfSubuserServerDoesNotMatchRequestServer()
{
$model = factory(Server::class)->make();
$subuser = factory(Subuser::class)->make();
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('route->parameter')->with('subuser', 0)->once()->andReturn('abc123');
$this->hashids->shouldReceive('decodeFirst')->with('abc123', 0)->once()->andReturn($subuser->id);
$this->repository->shouldReceive('find')->with($subuser->id)->once()->andReturn($subuser);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Test that an exception is thrown if no subuser is found.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testExceptionIsThrownIfNoSubuserIsFound()
{
$model = factory(Server::class)->make();
$subuser = factory(Subuser::class)->make();
$this->setRequestAttribute('server', $model);
$this->request->shouldReceive('route->parameter')->with('subuser', 0)->once()->andReturn('abc123');
$this->hashids->shouldReceive('decodeFirst')->with('abc123', 0)->once()->andReturn($subuser->id);
$this->repository->shouldReceive('find')->with($subuser->id)->once()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\Server\SubuserBelongsToServer
*/
private function getMiddleware(): SubuserBelongsToServer
{
return new SubuserBelongsToServer($this->hashids, $this->repository);
}
}