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

1
.phpunit.result.cache Normal file

File diff suppressed because one or more lines are too long

View File

@ -30,10 +30,7 @@ use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Pterodactyl\Http\Middleware\Server\AccessingValidServer; use Pterodactyl\Http\Middleware\Server\AccessingValidServer;
use Pterodactyl\Http\Middleware\Server\AuthenticateAsSubuser; use Pterodactyl\Http\Middleware\Server\AuthenticateAsSubuser;
use Pterodactyl\Http\Middleware\Api\Daemon\DaemonAuthenticate; use Pterodactyl\Http\Middleware\Api\Daemon\DaemonAuthenticate;
use Pterodactyl\Http\Middleware\Server\SubuserBelongsToServer;
use Pterodactyl\Http\Middleware\RequireTwoFactorAuthentication; use Pterodactyl\Http\Middleware\RequireTwoFactorAuthentication;
use Pterodactyl\Http\Middleware\Server\DatabaseBelongsToServer;
use Pterodactyl\Http\Middleware\Server\ScheduleBelongsToServer;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode; use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode;
use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull; use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
use Pterodactyl\Http\Middleware\Api\Client\SubstituteClientApiBindings; use Pterodactyl\Http\Middleware\Api\Client\SubstituteClientApiBindings;
@ -113,14 +110,6 @@ class Kernel extends HttpKernel
'recaptcha' => VerifyReCaptcha::class, 'recaptcha' => VerifyReCaptcha::class,
'node.maintenance' => MaintenanceMiddleware::class, 'node.maintenance' => MaintenanceMiddleware::class,
// Server specific middleware (used for authenticating access to resources)
//
// These are only used for individual server authentication, and not global
// actions from other resources. They are defined in the route files.
'server..database' => DatabaseBelongsToServer::class,
'server..subuser' => SubuserBelongsToServer::class,
'server..schedule' => ScheduleBelongsToServer::class,
// API Specific Middleware // API Specific Middleware
'api..key' => AuthenticateKey::class, 'api..key' => AuthenticateKey::class,
]; ];

View File

@ -5,8 +5,8 @@ namespace Pterodactyl\Http\Middleware\Api\Daemon;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Repositories\Eloquent\NodeRepository;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@ -14,10 +14,15 @@ use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class DaemonAuthenticate class DaemonAuthenticate
{ {
/** /**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface * @var \Pterodactyl\Repositories\Eloquent\NodeRepository
*/ */
private $repository; private $repository;
/**
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
private $encrypter;
/** /**
* Daemon routes that this middleware should be skipped on. * Daemon routes that this middleware should be skipped on.
* *
@ -27,18 +32,13 @@ class DaemonAuthenticate
'daemon.configuration', 'daemon.configuration',
]; ];
/**
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
private $encrypter;
/** /**
* DaemonAuthenticate constructor. * DaemonAuthenticate constructor.
* *
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter * @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
* @param \Pterodactyl\Contracts\Repository\NodeRepositoryInterface $repository * @param \Pterodactyl\Repositories\Eloquent\NodeRepository $repository
*/ */
public function __construct(Encrypter $encrypter, NodeRepositoryInterface $repository) public function __construct(Encrypter $encrypter, NodeRepository $repository)
{ {
$this->repository = $repository; $this->repository = $repository;
$this->encrypter = $encrypter; $this->encrypter = $encrypter;

View File

@ -1,56 +0,0 @@
<?php
namespace Pterodactyl\Http\Middleware\Server;
use Closure;
use Illuminate\Http\Request;
use Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class DatabaseBelongsToServer
{
/**
* @var \Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface
*/
private $repository;
/**
* DatabaseAccess constructor.
*
* @param \Pterodactyl\Contracts\Repository\DatabaseRepositoryInterface $repository
*/
public function __construct(DatabaseRepositoryInterface $repository)
{
$this->repository = $repository;
}
/**
* Check if a database being requested belongs to the currently loaded server.
* If it does not, throw a 404 error, otherwise continue on with the request
* and set an attribute with the database.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function handle(Request $request, Closure $next)
{
$server = $request->attributes->get('server');
$database = $request->input('database') ?? $request->route()->parameter('database');
if (! is_digit($database)) {
throw new NotFoundHttpException;
}
$database = $this->repository->find($database);
if (is_null($database) || $database->server_id !== $server->id) {
throw new NotFoundHttpException;
}
$request->attributes->set('database', $database);
return $next($request);
}
}

View File

@ -1,60 +0,0 @@
<?php
namespace Pterodactyl\Http\Middleware\Server;
use Closure;
use Illuminate\Http\Request;
use Pterodactyl\Contracts\Extensions\HashidsInterface;
use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ScheduleBelongsToServer
{
/**
* @var \Pterodactyl\Contracts\Extensions\HashidsInterface
*/
private $hashids;
/**
* @var \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface
*/
private $repository;
/**
* TaskAccess constructor.
*
* @param \Pterodactyl\Contracts\Extensions\HashidsInterface $hashids
* @param \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface $repository
*/
public function __construct(HashidsInterface $hashids, ScheduleRepositoryInterface $repository)
{
$this->hashids = $hashids;
$this->repository = $repository;
}
/**
* Determine if a task is assigned to the active server.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function handle(Request $request, Closure $next)
{
$server = $request->attributes->get('server');
$scheduleId = $this->hashids->decodeFirst($request->route()->parameter('schedule'), 0);
$schedule = $this->repository->getScheduleWithTasks($scheduleId);
if ($schedule->server_id !== $server->id) {
throw new NotFoundHttpException;
}
$request->attributes->set('schedule', $schedule);
return $next($request);
}
}

View File

@ -1,67 +0,0 @@
<?php
namespace Pterodactyl\Http\Middleware\Server;
use Closure;
use Illuminate\Http\Request;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Contracts\Extensions\HashidsInterface;
use Pterodactyl\Contracts\Repository\SubuserRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class SubuserBelongsToServer
{
/**
* @var \Pterodactyl\Contracts\Extensions\HashidsInterface
*/
private $hashids;
/**
* @var \Pterodactyl\Contracts\Repository\SubuserRepositoryInterface
*/
private $repository;
/**
* SubuserAccess constructor.
*
* @param \Pterodactyl\Contracts\Extensions\HashidsInterface $hashids
* @param \Pterodactyl\Contracts\Repository\SubuserRepositoryInterface $repository
*/
public function __construct(HashidsInterface $hashids, SubuserRepositoryInterface $repository)
{
$this->hashids = $hashids;
$this->repository = $repository;
}
/**
* Determine if a user has permission to access and modify subuser.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function handle(Request $request, Closure $next)
{
$server = $request->attributes->get('server');
$hash = $request->route()->parameter('subuser', 0);
$subuser = $this->repository->find($this->hashids->decodeFirst($hash, 0));
if (is_null($subuser) || $subuser->server_id !== $server->id) {
throw new NotFoundHttpException;
}
if ($request->method() === 'PATCH') {
if ($subuser->user_id === $request->user()->id) {
throw new DisplayException(trans('exceptions.subusers.editing_self'));
}
}
$request->attributes->set('subuser', $subuser);
return $next($request);
}
}

View File

@ -44,7 +44,7 @@
"require-dev": { "require-dev": {
"barryvdh/laravel-debugbar": "^3.3", "barryvdh/laravel-debugbar": "^3.3",
"barryvdh/laravel-ide-helper": "^2.7", "barryvdh/laravel-ide-helper": "^2.7",
"codedungeon/phpunit-result-printer": "0.25.1", "codedungeon/phpunit-result-printer": "^0.28.0",
"friendsofphp/php-cs-fixer": "2.16.1", "friendsofphp/php-cs-fixer": "2.16.1",
"fzaninotto/faker": "^1.9", "fzaninotto/faker": "^1.9",
"laravel/dusk": "^6.3", "laravel/dusk": "^6.3",

15
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "79af09c27859a87b05f58bde40a29576", "content-hash": "155b8e930e604c0476fa975b1084ca3f",
"packages": [ "packages": [
{ {
"name": "appstract/laravel-blade-directives", "name": "appstract/laravel-blade-directives",
@ -6252,16 +6252,16 @@
}, },
{ {
"name": "codedungeon/phpunit-result-printer", "name": "codedungeon/phpunit-result-printer",
"version": "0.25.1", "version": "0.28.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/mikeerickson/phpunit-pretty-result-printer.git", "url": "https://github.com/mikeerickson/phpunit-pretty-result-printer.git",
"reference": "4a689ac40366eb4adf166cf4676da7ef30d82315" "reference": "bc023b0311589bee19047425083163ffa3f0cf88"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/mikeerickson/phpunit-pretty-result-printer/zipball/4a689ac40366eb4adf166cf4676da7ef30d82315", "url": "https://api.github.com/repos/mikeerickson/phpunit-pretty-result-printer/zipball/bc023b0311589bee19047425083163ffa3f0cf88",
"reference": "4a689ac40366eb4adf166cf4676da7ef30d82315", "reference": "bc023b0311589bee19047425083163ffa3f0cf88",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -6269,10 +6269,9 @@
"codedungeon/php-cli-colors": "^1.10.2", "codedungeon/php-cli-colors": "^1.10.2",
"hassankhan/config": "^0.11.2", "hassankhan/config": "^0.11.2",
"php": "^7.1", "php": "^7.1",
"symfony/yaml": "^2.7|^3.0|^4.0" "symfony/yaml": "^2.7|^3.0|^4.0|^5.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "7.5.*",
"spatie/phpunit-watcher": "^1.6" "spatie/phpunit-watcher": "^1.6"
}, },
"type": "library", "type": "library",
@ -6301,7 +6300,7 @@
"result-printer", "result-printer",
"testing" "testing"
], ],
"time": "2019-02-01T19:13:43+00:00" "time": "2020-06-24T00:16:05+00:00"
}, },
{ {
"name": "composer/ca-bundle", "name": "composer/ca-bundle",

View File

@ -95,7 +95,7 @@ $factory->define(Pterodactyl\Models\Node::class, function (Faker $faker) {
'disk_overallocate' => 0, 'disk_overallocate' => 0,
'upload_size' => 100, 'upload_size' => 100,
'daemon_token_id' => Str::random(Node::DAEMON_TOKEN_ID_LENGTH), 'daemon_token_id' => Str::random(Node::DAEMON_TOKEN_ID_LENGTH),
'daemon_token' => Str::random(Node::DAEMON_TOKEN_LENGTH), 'daemon_token' => encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH)),
'daemonListen' => 8080, 'daemonListen' => 8080,
'daemonSFTP' => 2022, 'daemonSFTP' => 2022,
'daemonBase' => '/var/lib/pterodactyl/volumes', 'daemonBase' => '/var/lib/pterodactyl/volumes',

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
<?php <?php
namespace Tests\Unit\Http\Middleware\API; namespace Tests\Unit\Http\Middleware\Api;
use Mockery as m; use Mockery as m;
use Cake\Chronos\Chronos; use Cake\Chronos\Chronos;
@ -13,6 +13,7 @@ use Pterodactyl\Http\Middleware\Api\AuthenticateKey;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface; use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AuthenticateKeyTest extends MiddlewareTestCase class AuthenticateKeyTest extends MiddlewareTestCase
{ {
@ -62,11 +63,11 @@ class AuthenticateKeyTest extends MiddlewareTestCase
/** /**
* Test that an invalid API identifier throws an exception. * Test that an invalid API identifier throws an exception.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/ */
public function testInvalidIdentifier() public function testInvalidIdentifier()
{ {
$this->expectException(AccessDeniedHttpException::class);
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn('abcd1234'); $this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn('abcd1234');
$this->repository->shouldReceive('findFirstWhere')->andThrow(new RecordNotFoundException); $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 * Test that a valid token identifier with an invalid token attached to it
* triggers an exception. * triggers an exception.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/ */
public function testInvalidTokenForIdentifier() public function testInvalidTokenForIdentifier()
{ {
$this->expectException(AccessDeniedHttpException::class);
$model = factory(ApiKey::class)->make(); $model = factory(ApiKey::class)->make();
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'asdf'); $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 Mockery as m;
use Pterodactyl\Models\Node; use Pterodactyl\Models\Node;
use Illuminate\Contracts\Encryption\Encrypter;
use Tests\Unit\Http\Middleware\MiddlewareTestCase; use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Repositories\Eloquent\NodeRepository;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Http\Middleware\Api\Daemon\DaemonAuthenticate; use Pterodactyl\Http\Middleware\Api\Daemon\DaemonAuthenticate;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class DaemonAuthenticateTest extends MiddlewareTestCase class DaemonAuthenticateTest extends MiddlewareTestCase
{ {
/** /**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface|\Mockery\Mock * @var \Mockery\MockInterface
*/ */
private $repository; private $repository;
/**
* @var \Mockery\MockInterface
*/
private $encrypter;
/** /**
* Setup tests. * Setup tests.
*/ */
@ -24,7 +32,8 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
{ {
parent::setUp(); 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() 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()); $this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
} }
@ -44,8 +53,8 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
*/ */
public function testResponseShouldFailIfNoTokenIsProvided() public function testResponseShouldFailIfNoTokenIsProvided()
{ {
$this->request->shouldReceive('route->getName')->withNoArgs()->once()->andReturn('random.route'); $this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturnNull(); $this->request->expects('bearerToken')->withNoArgs()->andReturnNull();
try { try {
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions()); $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 * Test that passing in an invalid node daemon secret will result in a bad request
* error response. * 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->expectException(BadRequestHttpException::class);
$this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturn('test1234');
$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()); $this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
} }
@ -78,18 +124,39 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
*/ */
public function testSuccessfulMiddlewareProcess() public function testSuccessfulMiddlewareProcess()
{ {
/** @var \Pterodactyl\Models\Node $model */
$model = factory(Node::class)->make(); $model = factory(Node::class)->make();
$this->request->shouldReceive('route->getName')->withNoArgs()->once()->andReturn('random.route'); $this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturn($model->daemonSecret); $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->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestHasAttribute('node'); $this->assertRequestHasAttribute('node');
$this->assertRequestAttributeEquals($model, '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. * Return an instance of the middleware using mocked dependencies.
* *
@ -97,6 +164,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
*/ */
private function getMiddleware(): DaemonAuthenticate private function getMiddleware(): DaemonAuthenticate
{ {
return new DaemonAuthenticate($this->repository); return new DaemonAuthenticate($this->encrypter, $this->repository);
} }
} }

View File

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

View File

@ -2,6 +2,7 @@
namespace Tests\Unit\Http\Middleware; namespace Tests\Unit\Http\Middleware;
use Illuminate\Auth\AuthenticationException;
use Pterodactyl\Http\Middleware\Authenticate; use Pterodactyl\Http\Middleware\Authenticate;
class AuthenticateTest extends MiddlewareTestCase class AuthenticateTest extends MiddlewareTestCase
@ -18,11 +19,11 @@ class AuthenticateTest extends MiddlewareTestCase
/** /**
* Test that a logged out user results in an exception. * Test that a logged out user results in an exception.
*
* @expectedException \Illuminate\Auth\AuthenticationException
*/ */
public function testLoggedOutUser() public function testLoggedOutUser()
{ {
$this->expectException(AuthenticationException::class);
$this->request->shouldReceive('user')->withNoArgs()->once()->andReturnNull(); $this->request->shouldReceive('user')->withNoArgs()->once()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions()); $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 Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Http\Middleware\Server\AccessingValidServer; use Pterodactyl\Http\Middleware\Server\AccessingValidServer;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface; use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AccessingValidServerTest extends MiddlewareTestCase 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. * 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() public function testExceptionIsThrownIfServerIsSuspended()
{ {
$this->expectException(AccessDeniedHttpException::class);
$this->expectExceptionMessage('Server is suspended and cannot be accessed.');
$model = factory(Server::class)->make(['suspended' => 1]); $model = factory(Server::class)->make(['suspended' => 1]);
$this->request->shouldReceive('route->parameter')->with('server')->once()->andReturn('123456'); $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. * 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() public function testExceptionIsThrownIfServerIsNotInstalled()
{ {
$this->expectException(ConflictHttpException::class);
$this->expectExceptionMessage('Server is still completing the installation process.');
$model = factory(Server::class)->make(['installed' => 0]); $model = factory(Server::class)->make(['installed' => 0]);
$this->request->shouldReceive('route->parameter')->with('server')->once()->andReturn('123456'); $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\Http\Middleware\Server\AuthenticateAsSubuser;
use Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService; use Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException; use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AuthenticateAsSubuserTest extends MiddlewareTestCase class AuthenticateAsSubuserTest extends MiddlewareTestCase
{ {
@ -44,12 +45,12 @@ class AuthenticateAsSubuserTest extends MiddlewareTestCase
/** /**
* Test middleware handles missing token exception. * 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() public function testExceptionIsThrownIfNoTokenIsFound()
{ {
$this->expectException(AccessDeniedHttpException::class);
$this->expectExceptionMessage('This account does not have permission to access this server.');
$model = factory(Server::class)->make(); $model = factory(Server::class)->make();
$user = $this->setRequestUser(); $user = $this->setRequestUser();
$this->setRequestAttribute('server', $model); $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);
}
}