Merge branch 'develop' into dane/restore-backups

This commit is contained in:
Dane Everitt 2021-01-25 19:16:40 -08:00
commit 663143de0b
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
575 changed files with 6080 additions and 6864 deletions

View file

@ -1,26 +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\Assertions;
use PHPUnit\Framework\Assert;
trait CommandAssertionsTrait
{
/**
* Assert that an output table contains a value.
*
* @param mixed $string
* @param string $display
*/
public function assertTableContains($string, $display)
{
Assert::assertRegExp('/\|(\s+)' . preg_quote($string) . '(\s+)\|/', $display, 'Assert that a response table contains a value.');
}
}

View file

@ -1,207 +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\Assertions;
use Illuminate\View\View;
use Illuminate\Http\Response;
use PHPUnit\Framework\Assert;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
trait ControllerAssertionsTrait
{
/**
* Assert that a response is an instance of Illuminate View.
*
* @param mixed $response
*/
public function assertIsViewResponse($response)
{
Assert::assertInstanceOf(View::class, $response);
}
/**
* Assert that a response is an instance of Illuminate Redirect Response.
*
* @param mixed $response
*/
public function assertIsRedirectResponse($response)
{
Assert::assertInstanceOf(RedirectResponse::class, $response);
}
/**
* Assert that a response is an instance of Illuminate Json Response.
*
* @param mixed $response
*/
public function assertIsJsonResponse($response)
{
Assert::assertInstanceOf(JsonResponse::class, $response);
}
/**
* Assert that a response is an instance of Illuminate Response.
*
* @param mixed $response
*/
public function assertIsResponse($response)
{
Assert::assertInstanceOf(Response::class, $response);
}
/**
* Assert that a view name equals the passed name.
*
* @param string $name
* @param mixed $view
*/
public function assertViewNameEquals($name, $view)
{
Assert::assertEquals($name, $view->getName());
}
/**
* Assert that a view name does not equal a provided name.
*
* @param string $name
* @param mixed $view
*/
public function assertViewNameNotEquals($name, $view)
{
Assert::assertNotEquals($name, $view->getName());
}
/**
* Assert that a view has an attribute passed into it.
*
* @param string $attribute
* @param mixed $view
*/
public function assertViewHasKey($attribute, $view)
{
if (str_contains($attribute, '.')) {
Assert::assertNotEquals(
'__TEST__FAIL',
array_get($view->getData(), $attribute, '__TEST__FAIL')
);
} else {
Assert::assertArrayHasKey($attribute, $view->getData());
}
}
/**
* Assert that a view does not have a specific attribute passed in.
*
* @param string $attribute
* @param mixed $view
*/
public function assertViewNotHasKey($attribute, $view)
{
if (str_contains($attribute, '.')) {
Assert::assertEquals(
'__TEST__PASS',
array_get($view->getData(), $attribute, '__TEST__PASS')
);
} else {
Assert::assertArrayNotHasKey($attribute, $view->getData());
}
}
/**
* Assert that a view attribute equals a given parameter.
*
* @param string $attribute
* @param mixed $value
* @param mixed $view
*/
public function assertViewKeyEquals($attribute, $value, $view)
{
Assert::assertEquals($value, array_get($view->getData(), $attribute, '__TEST__FAIL'));
}
/**
* Assert that a view attribute does not equal a given parameter.
*
* @param string $attribute
* @param mixed $value
* @param mixed $view
*/
public function assertViewKeyNotEquals($attribute, $value, $view)
{
Assert::assertNotEquals($value, array_get($view->getData(), $attribute, '__TEST__FAIL'));
}
/**
* Assert that a route redirect equals a given route name.
*
* @param string $route
* @param mixed $response
* @param array $args
*/
public function assertRedirectRouteEquals($route, $response, array $args = [])
{
Assert::assertEquals(route($route, $args), $response->getTargetUrl());
}
/**
* Assert that a route redirect URL equals as passed URL.
*
* @param string $url
* @param mixed $response
*/
public function assertRedirectUrlEquals($url, $response)
{
Assert::assertEquals($url, $response->getTargetUrl());
}
/**
* Assert that a response code equals a given code.
*
* @param int $code
* @param mixed $response
*/
public function assertResponseCodeEquals($code, $response)
{
Assert::assertEquals($code, $response->getStatusCode());
}
/**
* Assert that a response code does not equal a given code.
*
* @param int $code
* @param mixed $response
*/
public function assertResponseCodeNotEquals($code, $response)
{
Assert::assertNotEquals($code, $response->getStatusCode());
}
/**
* Assert that a response is in a JSON format.
*
* @param mixed $response
*/
public function assertResponseHasJsonHeaders($response)
{
Assert::assertEquals('application/json', $response->headers->get('content-type'));
}
/**
* Assert that response JSON matches a given JSON string.
*
* @param array|string $json
* @param mixed $response
*/
public function assertResponseJsonEquals($json, $response)
{
Assert::assertEquals(is_array($json) ? json_encode($json) : $json, $response->getContent());
}
}

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Assertions;
namespace Pterodactyl\Tests\Assertions;
use PHPUnit\Framework\Assert;
@ -8,8 +8,6 @@ trait MiddlewareAttributeAssertionsTrait
{
/**
* Assert a request has an attribute assigned to it.
*
* @param string $attribute
*/
public function assertRequestHasAttribute(string $attribute)
{
@ -18,8 +16,6 @@ trait MiddlewareAttributeAssertionsTrait
/**
* Assert a request does not have an attribute assigned to it.
*
* @param string $attribute
*/
public function assertRequestMissingAttribute(string $attribute)
{
@ -29,8 +25,7 @@ trait MiddlewareAttributeAssertionsTrait
/**
* Assert a request attribute matches an expected value.
*
* @param mixed $expected
* @param string $attribute
* @param mixed $expected
*/
public function assertRequestAttributeEquals($expected, string $attribute)
{

View file

@ -1,47 +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\Assertions;
use PHPUnit\Framework\Assert;
use PHPUnit_Util_InvalidArgumentHelper;
trait NestedObjectAssertionsTrait
{
/**
* Assert that an object value matches an expected value.
*
* @param string $key
* @param mixed $expected
* @param object $object
*/
public function assertObjectNestedValueEquals(string $key, $expected, $object)
{
if (! is_object($object)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(3, 'object');
}
Assert::assertEquals($expected, object_get_strict($object, $key, '__TEST_FAILURE'), 'Assert that an object value equals a provided value.');
}
/**
* Assert that an object contains a nested key.
*
* @param string $key
* @param object $object
*/
public function assertObjectHasNestedAttribute(string $key, $object)
{
if (! is_object($object)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'object');
}
Assert::assertNotEquals('__TEST_FAILURE', object_get_strict($object, $key, '__TEST_FAILURE'), 'Assert that an object contains a nested key.');
}
}

View file

@ -5,10 +5,10 @@ namespace Pterodactyl\Tests\Browser;
use Laravel\Dusk\TestCase;
use BadMethodCallException;
use Pterodactyl\Models\User;
use Tests\CreatesApplication;
use Pterodactyl\Console\Kernel;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Eloquent\Model;
use Pterodactyl\Tests\CreatesApplication;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
@ -70,14 +70,16 @@ abstract class BrowserTestCase extends TestCase
*/
protected function driver()
{
$options = (new ChromeOptions)->addArguments([
$options = (new ChromeOptions())->addArguments([
'--disable-gpu',
'--disable-infobars',
]);
return RemoteWebDriver::create(
'http://host.pterodactyl.local:4444/wd/hub', DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY, $options
'http://host.pterodactyl.local:4444/wd/hub',
DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY,
$options
)
);
}
@ -86,6 +88,7 @@ abstract class BrowserTestCase extends TestCase
* Return an instance of the browser to be used for tests.
*
* @param \Facebook\WebDriver\Remote\RemoteWebDriver $driver
*
* @return \Pterodactyl\Tests\Browser\PterodactylBrowser
*/
protected function newBrowser($driver): PterodactylBrowser
@ -109,13 +112,10 @@ abstract class BrowserTestCase extends TestCase
/**
* Return a user model to authenticate aganist and use in the tests.
*
* @param array $attributes
* @return \Pterodactyl\Models\User
*/
protected function user(array $attributes = []): User
{
return factory(User::class)->create(array_merge([
return User::factory()->create(array_merge([
'password' => Hash::make(static::$userPassword),
], $attributes));
}

View file

@ -4,9 +4,6 @@ namespace Pterodactyl\Tests\Browser\Pages;
class LoginPage extends BasePage
{
/**
* @return string
*/
public function url(): string
{
return '/auth/login';

View file

@ -15,7 +15,7 @@ class ForgotPasswordProcessTest extends BrowserTestCase
public function testResetPasswordWithInvalidAccount()
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->visit(new LoginPage)
$browser->visit(new LoginPage())
->assertSee(trans('auth.forgot_password.label'))
->click('@forgotPassword')
->waitForLocation('/auth/password')
@ -39,7 +39,7 @@ class ForgotPasswordProcessTest extends BrowserTestCase
public function testEmailCarryover()
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->visit(new LoginPage)
$browser->visit(new LoginPage())
->type('@username', 'dane@example.com')
->click('@forgotPassword')
->waitForLocation('/auth/password')

View file

@ -27,7 +27,7 @@ class LoginProcessTest extends BrowserTestCase
public function testLoginUsingEmail()
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->visit(new LoginPage)
$browser->visit(new LoginPage())
->waitFor('@username')
->type('@username', $this->user->email)
->type('@password', self::$userPassword)
@ -44,7 +44,7 @@ class LoginProcessTest extends BrowserTestCase
public function testLoginUsingUsername()
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->visit(new LoginPage)
$browser->visit(new LoginPage())
->waitFor('@username')
->type('@username', $this->user->username)
->type('@password', self::$userPassword)

View file

@ -14,7 +14,7 @@ class AccountEmailProcessTest extends DashboardTestCase
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->loginAs($this->user)
->visit(new AccountPage)
->visit(new AccountPage())
->assertValue('@email', $this->user->email)
->type('@email', 'new.email@example.com')
->type('@password', 'Password123')
@ -34,7 +34,7 @@ class AccountEmailProcessTest extends DashboardTestCase
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->loginAs($this->user)
->visit(new AccountPage)
->visit(new AccountPage())
->assertMissing('@email ~ .input-help.error')
->type('@email', 'admin')
->assertVisible('@email ~ .input-help.error')
@ -51,7 +51,7 @@ class AccountEmailProcessTest extends DashboardTestCase
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->loginAs($this->user)
->visit(new AccountPage)
->visit(new AccountPage())
->type('@email', 'new.email@example.com')
->click('@submit')
->assertFocused('@password')

View file

@ -14,7 +14,7 @@ class AccountPasswordProcessTest extends DashboardTestCase
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->loginAs($this->user)
->visit(new AccountPage)
->visit(new AccountPage())
->type('@current_password', self::$userPassword)
->assertMissing('@new_password ~ .input-help.error')
->type('@new_password', 'test')
@ -42,7 +42,7 @@ class AccountPasswordProcessTest extends DashboardTestCase
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->loginAs($this->user)
->visit(new AccountPage)
->visit(new AccountPage())
->type('@current_password', 'badpassword')
->type('@new_password', 'testtest')
->type('@confirm_password', 'testtest')

View file

@ -17,7 +17,7 @@ class TwoFactorAuthenticationProcessTest extends DashboardTestCase
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->loginAs($this->user)
->visit(new AccountPage)
->visit(new AccountPage())
->assertMissing('.modal-mask')
->click('@2fa_button')
->waitFor('@2fa_modal')
@ -42,7 +42,7 @@ class TwoFactorAuthenticationProcessTest extends DashboardTestCase
{
$this->browse(function (PterodactylBrowser $browser) {
$browser->loginAs($this->user)
->visit(new AccountPage)
->visit(new AccountPage())
->click('@2fa_button')
->waitForText(trans('dashboard/account.two_factor.setup.title'))
->assertFocused('@2fa_token')
@ -76,7 +76,7 @@ class TwoFactorAuthenticationProcessTest extends DashboardTestCase
*/
public function testTwoFactorCanBeDisabled()
{
$secret = (new Google2FA)->generateSecretKey(16);
$secret = (new Google2FA())->generateSecretKey(16);
$this->user->update([
'use_totp' => true,
@ -85,7 +85,7 @@ class TwoFactorAuthenticationProcessTest extends DashboardTestCase
$this->browse(function (PterodactylBrowser $browser) use ($secret) {
$browser->loginAs($this->user)
->visit(new AccountPage)
->visit(new AccountPage())
->click('@2fa_button')
->waitForText(trans('dashboard/account.two_factor.disable.title'))
->click('@2fa_cancel')

View file

@ -11,8 +11,6 @@ class PterodactylBrowser extends Browser
/**
* Move the mouse to a specific location and then perform a left click action.
*
* @param int $x
* @param int $y
* @return $this
*/
public function clickPosition(int $x, int $y)
@ -26,6 +24,7 @@ class PterodactylBrowser extends Browser
* Perform a case insensitive search for a string in the body.
*
* @param string $text
*
* @return \Pterodactyl\Tests\Browser\PterodactylBrowser
*/
public function assertSee($text)
@ -38,6 +37,7 @@ class PterodactylBrowser extends Browser
*
* @param string $selector
* @param string $text
*
* @return \Pterodactyl\Tests\Browser\PterodactylBrowser
*/
public function assertSeeIn($selector, $text)

View file

@ -1,6 +1,6 @@
<?php
namespace Tests;
namespace Pterodactyl\Tests;
use Illuminate\Contracts\Console\Kernel;

View file

@ -6,16 +6,18 @@ use Pterodactyl\Models\User;
use PHPUnit\Framework\Assert;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Services\Acl\Api\AdminAcl;
use Tests\Traits\Integration\CreatesTestModels;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\Traits\Http\IntegrationJsonRequestAssertions;
use Pterodactyl\Tests\Traits\Integration\CreatesTestModels;
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
use Pterodactyl\Transformers\Api\Client\BaseClientTransformer;
use Pterodactyl\Tests\Traits\Http\IntegrationJsonRequestAssertions;
abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
{
use CreatesTestModels, DatabaseTransactions, IntegrationJsonRequestAssertions;
use CreatesTestModels;
use DatabaseTransactions;
use IntegrationJsonRequestAssertions;
/**
* @var \Pterodactyl\Models\ApiKey
@ -44,17 +46,11 @@ abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
$this->withMiddleware('api..key:' . ApiKey::TYPE_APPLICATION);
}
/**
* @return \Pterodactyl\Models\User
*/
public function getApiUser(): User
{
return $this->user;
}
/**
* @return \Pterodactyl\Models\ApiKey
*/
public function getApiKey(): ApiKey
{
return $this->key;
@ -62,10 +58,6 @@ abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
/**
* Creates a new default API key and refreshes the headers using it.
*
* @param \Pterodactyl\Models\User $user
* @param array $permissions
* @return \Pterodactyl\Models\ApiKey
*/
protected function createNewDefaultApiKey(User $user, array $permissions = []): ApiKey
{
@ -77,8 +69,6 @@ abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
/**
* Refresh the authorization header for a request to use a different API key.
*
* @param \Pterodactyl\Models\ApiKey $key
*/
protected function refreshHeaders(ApiKey $key)
{
@ -87,26 +77,20 @@ abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
/**
* Create an administrative user.
*
* @return \Pterodactyl\Models\User
*/
protected function createApiUser(): User
{
return factory(User::class)->create([
return User::factory()->create([
'root_admin' => true,
]);
}
/**
* Create a new application API key for a given user model.
*
* @param \Pterodactyl\Models\User $user
* @param array $permissions
* @return \Pterodactyl\Models\ApiKey
*/
protected function createApiKey(User $user, array $permissions = []): ApiKey
{
return factory(ApiKey::class)->create(array_merge([
return ApiKey::factory()->create(array_merge([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_APPLICATION,
'r_servers' => AdminAcl::READ | AdminAcl::WRITE,
@ -123,9 +107,6 @@ abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
/**
* Return a transformer that can be used for testing purposes.
*
* @param string $abstract
* @return \Pterodactyl\Transformers\Api\Application\BaseTransformer
*/
protected function getTransformer(string $abstract): BaseTransformer
{

View file

@ -16,7 +16,7 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testGetLocations()
{
$locations = factory(Location::class)->times(2)->create();
$locations = Location::factory()->times(2)->create();
$response = $this->getJson('/api/application/locations');
$response->assertStatus(Response::HTTP_OK);
@ -70,7 +70,7 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testGetSingleLocation()
{
$location = factory(Location::class)->create();
$location = Location::factory()->create();
$response = $this->getJson('/api/application/locations/' . $location->id);
$response->assertStatus(Response::HTTP_OK);
@ -93,7 +93,7 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testRelationshipsCanBeLoaded()
{
$location = factory(Location::class)->create();
$location = Location::factory()->create();
$server = $this->createServerModel(['user_id' => $this->getApiUser()->id, 'location_id' => $location->id]);
$response = $this->getJson('/api/application/locations/' . $location->id . '?include=servers,nodes');
@ -143,8 +143,8 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
{
$this->createNewDefaultApiKey($this->getApiUser(), ['r_nodes' => 0]);
$location = factory(Location::class)->create();
factory(Node::class)->create(['location_id' => $location->id]);
$location = Location::factory()->create();
Node::factory()->create(['location_id' => $location->id]);
$response = $this->getJson('/api/application/locations/' . $location->id . '?include=nodes');
$response->assertStatus(Response::HTTP_OK);
@ -187,7 +187,7 @@ class LocationControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testErrorReturnedIfNoPermission()
{
$location = factory(Location::class)->create();
$location = Location::factory()->create();
$this->createNewDefaultApiKey($this->getApiUser(), ['r_locations' => 0]);
$response = $this->getJson('/api/application/locations/' . $location->id);

View file

@ -61,7 +61,9 @@ class EggControllerTest extends ApplicationApiIntegrationTestCase
$expected = json_encode(Arr::sortRecursive($datum['attributes']));
$actual = json_encode(Arr::sortRecursive($this->getTransformer(EggTransformer::class)->transform($egg)));
$this->assertSame($expected, $actual,
$this->assertSame(
$expected,
$actual,
'Unable to find JSON fragment: ' . PHP_EOL . PHP_EOL . "[{$expected}]" . PHP_EOL . PHP_EOL . 'within' . PHP_EOL . PHP_EOL . "[{$actual}]."
);
}

View file

@ -13,7 +13,7 @@ class ExternalUserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testGetRemoteUser()
{
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->getJson('/api/application/users/external/' . $user->external_id);
$response->assertStatus(Response::HTTP_OK);
@ -60,7 +60,7 @@ class ExternalUserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testErrorReturnedIfNoPermission()
{
$user = factory(User::class)->create();
$user = User::factory()->create();
$this->createNewDefaultApiKey($this->getApiUser(), ['r_users' => 0]);
$response = $this->getJson('/api/application/users/external/' . $user->external_id);

View file

@ -16,7 +16,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testGetUsers()
{
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->getJson('/api/application/users');
$response->assertStatus(Response::HTTP_OK);
@ -85,7 +85,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testGetSingleUser()
{
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->getJson('/api/application/users/' . $user->id);
$response->assertStatus(Response::HTTP_OK);
@ -119,7 +119,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testRelationshipsCanBeLoaded()
{
$user = factory(User::class)->create();
$user = User::factory()->create();
$server = $this->createServerModel(['user_id' => $user->id]);
$response = $this->getJson('/api/application/users/' . $user->id . '?include=servers');
@ -152,7 +152,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
{
$this->createNewDefaultApiKey($this->getApiUser(), ['r_servers' => 0]);
$user = factory(User::class)->create();
$user = User::factory()->create();
$this->createServerModel(['user_id' => $user->id]);
$response = $this->getJson('/api/application/users/' . $user->id . '?include=servers');
@ -194,7 +194,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testErrorReturnedIfNoPermission()
{
$user = factory(User::class)->create();
$user = User::factory()->create();
$this->createNewDefaultApiKey($this->getApiUser(), ['r_users' => 0]);
$response = $this->getJson('/api/application/users/' . $user->id);
@ -250,7 +250,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testUpdateUser()
{
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->patchJson('/api/application/users/' . $user->id, [
'username' => 'new.test.name',
@ -279,7 +279,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
*/
public function testDeleteUser()
{
$user = factory(User::class)->create();
$user = User::factory()->create();
$this->assertDatabaseHas('users', ['id' => $user->id]);
$response = $this->delete('/api/application/users/' . $user->id);
@ -292,9 +292,6 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
* Test that an API key without write permissions cannot create, update, or
* delete a user model.
*
* @param string $method
* @param string $url
*
* @dataProvider userWriteEndpointsDataProvider
*/
public function testApiKeyWithoutWritePermissions(string $method, string $url)
@ -302,7 +299,7 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
$this->createNewDefaultApiKey($this->getApiUser(), ['r_users' => AdminAcl::READ]);
if (str_contains($url, '{id}')) {
$user = factory(User::class)->create();
$user = User::factory()->create();
$url = str_replace('{id}', $user->id, $url);
}
@ -313,8 +310,6 @@ class UserControllerTest extends ApplicationApiIntegrationTestCase
/**
* Endpoints that should return a 403 error when the key does not have write
* permissions for user management.
*
* @return array
*/
public function userWriteEndpointsDataProvider(): array
{

View file

@ -15,7 +15,7 @@ class AccountControllerTest extends ClientApiIntegrationTestCase
public function testAccountDetailsAreReturned()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->actingAs($user)->get('/api/client/account');
@ -39,7 +39,7 @@ class AccountControllerTest extends ClientApiIntegrationTestCase
public function testEmailIsUpdated()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->actingAs($user)->putJson('/api/client/account/email', [
'email' => 'hodor@example.com',
@ -58,7 +58,7 @@ class AccountControllerTest extends ClientApiIntegrationTestCase
public function testEmailIsNotUpdatedWhenPasswordIsInvalid()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->actingAs($user)->putJson('/api/client/account/email', [
'email' => 'hodor@example.com',
@ -77,7 +77,7 @@ class AccountControllerTest extends ClientApiIntegrationTestCase
public function testEmailIsNotUpdatedWhenNotValid()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->actingAs($user)->putJson('/api/client/account/email', [
'email' => '',
@ -104,7 +104,7 @@ class AccountControllerTest extends ClientApiIntegrationTestCase
public function testPasswordIsUpdated()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
$mock = Mockery::mock(AuthManager::class);
$mock->expects('logoutOtherDevices')->with('New_Password1');
@ -127,7 +127,7 @@ class AccountControllerTest extends ClientApiIntegrationTestCase
public function testPasswordIsNotUpdatedIfCurrentPasswordIsInvalid()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->actingAs($user)->putJson('/api/client/account/password', [
'current_password' => 'invalid',
@ -146,7 +146,7 @@ class AccountControllerTest extends ClientApiIntegrationTestCase
*/
public function testErrorIsReturnedForInvalidRequestData()
{
$user = factory(User::class)->create();
$user = User::factory()->create();
$this->actingAs($user)->putJson('/api/client/account/password', [
'current_password' => 'password',
@ -170,7 +170,7 @@ class AccountControllerTest extends ClientApiIntegrationTestCase
public function testErrorIsReturnedIfPasswordIsNotConfirmed()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->actingAs($user)->putJson('/api/client/account/password', [
'current_password' => 'password',

View file

@ -24,9 +24,9 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
public function testApiKeysAreReturned()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = factory(ApiKey::class)->create([
$key = ApiKey::factory()->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
@ -59,13 +59,13 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
public function testApiKeyCanBeCreatedForAccount()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
// Small sub-test to ensure we're always comparing the number of keys to the
// specific logged in account, and not just the total number of keys stored in
// the database.
factory(ApiKey::class)->times(10)->create([
'user_id' => factory(User::class)->create()->id,
ApiKey::factory()->times(10)->create([
'user_id' => User::factory()->create()->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
@ -103,8 +103,8 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
public function testNoMoreThanFiveApiKeysCanBeCreatedForAnAccount()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
factory(ApiKey::class)->times(5)->create([
$user = User::factory()->create();
ApiKey::factory()->times(5)->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
@ -127,7 +127,7 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
public function testValidationErrorIsReturnedForBadRequests()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
$response = $this->actingAs($user)->postJson('/api/client/account/api-keys', [
'description' => '',
@ -154,9 +154,9 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
public function testApiKeyCanBeDeleted()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = factory(ApiKey::class)->create([
$key = ApiKey::factory()->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
@ -173,9 +173,9 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
public function testNonExistentApiKeyDeletionReturns404Error()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = factory(ApiKey::class)->create([
$key = ApiKey::factory()->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
@ -193,11 +193,11 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
public function testApiKeyBelongingToAnotherUserCannotBeDeleted()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
/** @var \Pterodactyl\Models\User $user2 */
$user2 = factory(User::class)->create();
$user2 = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = factory(ApiKey::class)->create([
$key = ApiKey::factory()->create([
'user_id' => $user2->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
]);
@ -215,9 +215,9 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
public function testApplicationApiKeyCannotBeDeleted()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
/** @var \Pterodactyl\Models\ApiKey $key */
$key = factory(ApiKey::class)->create([
$key = ApiKey::factory()->create([
'user_id' => $user->id,
'key_type' => ApiKey::TYPE_APPLICATION,
]);

View file

@ -2,19 +2,21 @@
namespace Pterodactyl\Tests\Integration\Api\Client;
use Carbon\Carbon;
use ReflectionClass;
use Carbon\CarbonImmutable;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Task;
use Pterodactyl\Models\User;
use Webmozart\Assert\Assert;
use Pterodactyl\Models\Backup;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Models\Database;
use Pterodactyl\Models\Location;
use Pterodactyl\Models\Schedule;
use Illuminate\Support\Collection;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\DatabaseHost;
use Pterodactyl\Tests\Integration\TestResponse;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Transformers\Api\Client\BaseClientTransformer;
@ -25,6 +27,9 @@ abstract class ClientApiIntegrationTestCase extends IntegrationTestCase
*/
protected function tearDown(): void
{
Database::query()->forceDelete();
DatabaseHost::query()->forceDelete();
Backup::query()->forceDelete();
Server::query()->forceDelete();
Node::query()->forceDelete();
Location::query()->forceDelete();
@ -34,22 +39,24 @@ abstract class ClientApiIntegrationTestCase extends IntegrationTestCase
}
/**
* Setup tests and ensure all of the times are always the same.
* Override the default createTestResponse from Illuminate so that we can
* just dump 500-level errors to the screen in the tests without having
* to keep re-assigning variables.
*
* @param \Illuminate\Http\Response $response
*
* @return \Illuminate\Testing\TestResponse
*/
public function setUp(): void
protected function createTestResponse($response)
{
parent::setUp();
Carbon::setTestNow(Carbon::now());
CarbonImmutable::setTestNow(Carbon::now());
return TestResponse::fromBaseResponse($response);
}
/**
* Returns a link to the specific resource using the client API.
*
* @param mixed $model
* @param mixed $model
* @param string|null $append
* @return string
*/
protected function link($model, $append = null): string
{
@ -79,17 +86,17 @@ abstract class ClientApiIntegrationTestCase extends IntegrationTestCase
* is assumed that the user is actually a subuser of the server.
*
* @param string[] $permissions
* @return array
*/
protected function generateTestAccount(array $permissions = []): array
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
if (empty($permissions)) {
return [$user, $this->createServerModel(['user_id' => $user->id])];
}
/** @var \Pterodactyl\Models\Server $server */
$server = $this->createServerModel();
Subuser::query()->create([
@ -105,7 +112,6 @@ abstract class ClientApiIntegrationTestCase extends IntegrationTestCase
* Asserts that the data passed through matches the output of the data from the transformer. This
* will remove the "relationships" key when performing the comparison.
*
* @param array $data
* @param \Pterodactyl\Models\Model|\Illuminate\Database\Eloquent\Model $model
*/
protected function assertJsonTransformedWith(array $data, $model)
@ -113,7 +119,7 @@ abstract class ClientApiIntegrationTestCase extends IntegrationTestCase
$reflect = new ReflectionClass($model);
$transformer = sprintf('\\Pterodactyl\\Transformers\\Api\\Client\\%sTransformer', $reflect->getShortName());
$transformer = new $transformer;
$transformer = new $transformer();
$this->assertInstanceOf(BaseClientTransformer::class, $transformer);
$this->assertSame(

View file

@ -5,8 +5,8 @@ namespace Pterodactyl\Tests\Integration\Api\Client;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Models\Permission;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\Permission;
class ClientControllerTest extends ClientApiIntegrationTestCase
{
@ -19,7 +19,7 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
public function testOnlyLoggedInUsersServersAreReturned()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(3)->create();
$users = User::factory()->times(3)->create();
/** @var \Pterodactyl\Models\Server[] $servers */
$servers = [
@ -46,7 +46,7 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
public function testServersAreFilteredUsingNameAndUuidInformation()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(2)->create();
$users = User::factory()->times(2)->create();
$users[0]->update(['root_admin' => true]);
/** @var \Pterodactyl\Models\Server[] $servers */
@ -106,8 +106,8 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
$server2 = $this->createServerModel(['user_id' => $user->id, 'node_id' => $server->node_id]);
$allocation = factory(Allocation::class)->create(['node_id' => $server->node_id, 'server_id' => $server->id, 'ip' => '192.168.1.1', 'port' => 25565]);
$allocation2 = factory(Allocation::class)->create(['node_id' => $server->node_id, 'server_id' => $server2->id, 'ip' => '192.168.1.1', 'port' => 25570]);
$allocation = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server->id, 'ip' => '192.168.1.1', 'port' => 25565]);
$allocation2 = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server2->id, 'ip' => '192.168.1.1', 'port' => 25570]);
$server->update(['allocation_id' => $allocation->id]);
$server2->update(['allocation_id' => $allocation2->id]);
@ -144,7 +144,7 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
public function testServersUserIsASubuserOfAreReturned()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(3)->create();
$users = User::factory()->times(3)->create();
$servers = [
$this->createServerModel(['user_id' => $users[0]->id]),
$this->createServerModel(['user_id' => $users[1]->id]),
@ -175,7 +175,7 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
public function testFilterOnlyOwnerServers()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(3)->create();
$users = User::factory()->times(3)->create();
$servers = [
$this->createServerModel(['user_id' => $users[0]->id]),
$this->createServerModel(['user_id' => $users[1]->id]),
@ -204,7 +204,7 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
public function testPermissionsAreReturned()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
$this->actingAs($user)
->getJson('/api/client/permissions')
@ -224,7 +224,7 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
public function testOnlyAdminLevelServersAreReturned()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(4)->create();
$users = User::factory()->times(4)->create();
$users[0]->update(['root_admin' => true]);
$servers = [
@ -259,7 +259,7 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
public function testAllServersAreReturnedToAdmin()
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(4)->create();
$users = User::factory()->times(4)->create();
$users[0]->update(['root_admin' => true]);
$servers = [
@ -292,7 +292,7 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
public function testNoServersAreReturnedIfAdminFilterIsPassedByRegularUser($type)
{
/** @var \Pterodactyl\Models\User[] $users */
$users = factory(User::class)->times(3)->create();
$users = User::factory()->times(3)->create();
$this->createServerModel(['user_id' => $users[0]->id]);
$this->createServerModel(['user_id' => $users[1]->id]);
@ -315,7 +315,7 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
$server->allocation->notes = 'Test notes';
$server->allocation->save();
factory(Allocation::class)->times(2)->create([
Allocation::factory()->times(2)->create([
'node_id' => $server->node_id,
'server_id' => $server->id,
]);

View file

@ -0,0 +1,60 @@
<?php
namespace Pterodactyl\Tests\Integration\Api\Client\Server\Allocation;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Tests\Integration\Api\Client\ClientApiIntegrationTestCase;
class AllocationAuthorizationTest extends ClientApiIntegrationTestCase
{
/**
* @dataProvider methodDataProvider
*/
public function testAccessToAServersAllocationsIsRestrictedProperly(string $method, string $endpoint)
{
// The API $user is the owner of $server1.
[$user, $server1] = $this->generateTestAccount();
// Will be a subuser of $server2.
$server2 = $this->createServerModel();
// And as no access to $server3.
$server3 = $this->createServerModel();
// Set the API $user as a subuser of server 2, but with no permissions
// to do anything with the allocations for that server.
Subuser::factory()->create(['server_id' => $server2->id, 'user_id' => $user->id]);
$allocation1 = Allocation::factory()->create(['server_id' => $server1->id, 'node_id' => $server1->node_id]);
$allocation2 = Allocation::factory()->create(['server_id' => $server2->id, 'node_id' => $server2->node_id]);
$allocation3 = Allocation::factory()->create(['server_id' => $server3->id, 'node_id' => $server3->node_id]);
// This is the only valid call for this test, accessing the allocation for the same
// server that the API user is the owner of.
$response = $this->actingAs($user)->json($method, $this->link($server1, '/network/allocations/' . $allocation1->id . $endpoint));
$this->assertTrue($response->status() <= 204 || $response->status() === 400 || $response->status() === 422);
// This request fails because the allocation is valid for that server but the user
// making the request is not authorized to perform that action.
$this->actingAs($user)->json($method, $this->link($server2, '/network/allocations/' . $allocation2->id . $endpoint))->assertForbidden();
// Both of these should report a 404 error due to the allocations being linked to
// servers that are not the same as the server in the request, or are assigned
// to a server for which the user making the request has no access to.
$this->actingAs($user)->json($method, $this->link($server1, '/network/allocations/' . $allocation2->id . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server1, '/network/allocations/' . $allocation3->id . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server2, '/network/allocations/' . $allocation3->id . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server3, '/network/allocations/' . $allocation3->id . $endpoint))->assertNotFound();
}
/**
* @return \string[][]
*/
public function methodDataProvider(): array
{
return [
['POST', ''],
['DELETE', ''],
['POST', '/primary'],
];
}
}

View file

@ -3,8 +3,8 @@
namespace Pterodactyl\Tests\Integration\Api\Client\Server\Allocation;
use Illuminate\Http\Response;
use Pterodactyl\Models\Permission;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\Permission;
use Pterodactyl\Tests\Integration\Api\Client\ClientApiIntegrationTestCase;
class CreateNewAllocationTest extends ClientApiIntegrationTestCase
@ -24,7 +24,6 @@ class CreateNewAllocationTest extends ClientApiIntegrationTestCase
/**
* Tests that a new allocation can be properly assigned to a server.
*
* @param array $permission
* @dataProvider permissionDataProvider
*/
public function testNewAllocationCanBeAssignedToServer(array $permission)
@ -33,7 +32,7 @@ class CreateNewAllocationTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount($permission);
$server->update(['allocation_limit' => 2]);
$response = $this->actingAs($user)->postJson($this->link($server, "/network/allocations"));
$response = $this->actingAs($user)->postJson($this->link($server, '/network/allocations'));
$response->assertJsonPath('object', Allocation::RESOURCE_NAME);
$matched = Allocation::query()->findOrFail($response->json('attributes.id'));
@ -52,7 +51,7 @@ class CreateNewAllocationTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount([Permission::ACTION_ALLOCATION_UPDATE]);
$server->update(['allocation_limit' => 2]);
$this->actingAs($user)->postJson($this->link($server, "/network/allocations"))->assertForbidden();
$this->actingAs($user)->postJson($this->link($server, '/network/allocations'))->assertForbidden();
}
/**
@ -66,7 +65,7 @@ class CreateNewAllocationTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
$server->update(['allocation_limit' => 2]);
$this->actingAs($user)->postJson($this->link($server, "/network/allocations"))
$this->actingAs($user)->postJson($this->link($server, '/network/allocations'))
->assertStatus(Response::HTTP_BAD_REQUEST)
->assertJsonPath('errors.0.code', 'AutoAllocationNotEnabledException')
->assertJsonPath('errors.0.detail', 'Server auto-allocation is not enabled for this instance.');
@ -81,7 +80,7 @@ class CreateNewAllocationTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
$server->update(['allocation_limit' => 1]);
$this->actingAs($user)->postJson($this->link($server, "/network/allocations"))
$this->actingAs($user)->postJson($this->link($server, '/network/allocations'))
->assertStatus(Response::HTTP_BAD_REQUEST)
->assertJsonPath('errors.0.code', 'DisplayException')
->assertJsonPath('errors.0.detail', 'Cannot assign additional allocations to this server: limit has been reached.');

View file

@ -3,8 +3,8 @@
namespace Pterodactyl\Tests\Integration\Api\Client\Server\Allocation;
use Illuminate\Http\Response;
use Pterodactyl\Models\Permission;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\Permission;
use Pterodactyl\Tests\Integration\Api\Client\ClientApiIntegrationTestCase;
class DeleteAllocationTest extends ClientApiIntegrationTestCase
@ -13,7 +13,6 @@ class DeleteAllocationTest extends ClientApiIntegrationTestCase
* Test that an allocation is deleted from the server and the notes are properly reset
* to an empty value on assignment.
*
* @param array $permission
* @dataProvider permissionDataProvider
*/
public function testAllocationCanBeDeletedFromServer(array $permission)
@ -22,7 +21,7 @@ class DeleteAllocationTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount($permission);
/** @var \Pterodactyl\Models\Allocation $allocation */
$allocation = factory(Allocation::class)->create([
$allocation = Allocation::factory()->create([
'server_id' => $server->id,
'node_id' => $server->node_id,
'notes' => 'hodor',
@ -42,7 +41,7 @@ class DeleteAllocationTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount([Permission::ACTION_ALLOCATION_CREATE]);
/** @var \Pterodactyl\Models\Allocation $allocation */
$allocation = factory(Allocation::class)->create([
$allocation = Allocation::factory()->create([
'server_id' => $server->id,
'node_id' => $server->node_id,
'notes' => 'hodor',

View file

@ -0,0 +1,69 @@
<?php
namespace Pterodactyl\Tests\Integration\Api\Client\Server\Backup;
use Mockery;
use Carbon\CarbonImmutable;
use Pterodactyl\Models\Backup;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Services\Backups\DeleteBackupService;
use Pterodactyl\Tests\Integration\Api\Client\ClientApiIntegrationTestCase;
class BackupAuthorizationTest extends ClientApiIntegrationTestCase
{
/**
* @dataProvider methodDataProvider
*/
public function testAccessToAServersBackupIsRestrictedProperly(string $method, string $endpoint)
{
// The API $user is the owner of $server1.
[$user, $server1] = $this->generateTestAccount();
// Will be a subuser of $server2.
$server2 = $this->createServerModel();
// And as no access to $server3.
$server3 = $this->createServerModel();
// Set the API $user as a subuser of server 2, but with no permissions
// to do anything with the backups for that server.
Subuser::factory()->create(['server_id' => $server2->id, 'user_id' => $user->id]);
$backup1 = Backup::factory()->create(['server_id' => $server1->id, 'completed_at' => CarbonImmutable::now()]);
$backup2 = Backup::factory()->create(['server_id' => $server2->id, 'completed_at' => CarbonImmutable::now()]);
$backup3 = Backup::factory()->create(['server_id' => $server3->id, 'completed_at' => CarbonImmutable::now()]);
$this->instance(DeleteBackupService::class, $mock = Mockery::mock(DeleteBackupService::class));
if ($method === 'DELETE') {
$mock->expects('handle')->andReturnUndefined();
}
// This is the only valid call for this test, accessing the backup for the same
// server that the API user is the owner of.
$this->actingAs($user)->json($method, $this->link($server1, '/backups/' . $backup1->uuid . $endpoint))
->assertStatus($method === 'DELETE' ? 204 : 200);
// This request fails because the backup is valid for that server but the user
// making the request is not authorized to perform that action.
$this->actingAs($user)->json($method, $this->link($server2, '/backups/' . $backup2->uuid . $endpoint))->assertForbidden();
// Both of these should report a 404 error due to the backup being linked to
// servers that are not the same as the server in the request, or are assigned
// to a server for which the user making the request has no access to.
$this->actingAs($user)->json($method, $this->link($server1, '/backups/' . $backup2->uuid . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server1, '/backups/' . $backup3->uuid . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server2, '/backups/' . $backup3->uuid . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server3, '/backups/' . $backup3->uuid . $endpoint))->assertNotFound();
}
/**
* @return \string[][]
*/
public function methodDataProvider(): array
{
return [
['GET', ''],
['GET', '/download'],
['DELETE', ''],
];
}
}

View file

@ -69,7 +69,7 @@ class CommandControllerTest extends ClientApiIntegrationTestCase
$this->repository->expects('setServer')->with(Mockery::on(function ($value) use ($server) {
return $value->uuid === $server->uuid;
}))->andReturnSelf();
$this->repository->expects('send')->with('say Test')->andReturn(new GuzzleResponse);
$this->repository->expects('send')->with('say Test')->andReturn(new GuzzleResponse());
$response = $this->actingAs($user)->postJson("/api/client/servers/{$server->uuid}/command", [
'command' => 'say Test',

View file

@ -0,0 +1,76 @@
<?php
namespace Pterodactyl\Tests\Integration\Api\Client\Server\Database;
use Mockery;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Models\Database;
use Pterodactyl\Models\DatabaseHost;
use Pterodactyl\Contracts\Extensions\HashidsInterface;
use Pterodactyl\Services\Databases\DatabasePasswordService;
use Pterodactyl\Services\Databases\DatabaseManagementService;
use Pterodactyl\Tests\Integration\Api\Client\ClientApiIntegrationTestCase;
class DatabaseAuthorizationTest extends ClientApiIntegrationTestCase
{
/**
* @dataProvider methodDataProvider
*/
public function testAccessToAServersDatabasesIsRestrictedProperly(string $method, string $endpoint)
{
// The API $user is the owner of $server1.
[$user, $server1] = $this->generateTestAccount();
// Will be a subuser of $server2.
$server2 = $this->createServerModel();
// And as no access to $server3.
$server3 = $this->createServerModel();
$host = DatabaseHost::factory()->create([]);
// Set the API $user as a subuser of server 2, but with no permissions
// to do anything with the databases for that server.
Subuser::factory()->create(['server_id' => $server2->id, 'user_id' => $user->id]);
$database1 = Database::factory()->create(['server_id' => $server1->id, 'database_host_id' => $host->id]);
$database2 = Database::factory()->create(['server_id' => $server2->id, 'database_host_id' => $host->id]);
$database3 = Database::factory()->create(['server_id' => $server3->id, 'database_host_id' => $host->id]);
$this->instance(DatabasePasswordService::class, $mock = Mockery::mock(DatabasePasswordService::class));
$this->instance(DatabaseManagementService::class, $mock2 = Mockery::mock(DatabaseManagementService::class));
if ($method === 'POST') {
$mock->expects('handle')->andReturnUndefined();
} else {
$mock2->expects('delete')->andReturnUndefined();
}
$hashids = $this->app->make(HashidsInterface::class);
// This is the only valid call for this test, accessing the database for the same
// server that the API user is the owner of.
$this->actingAs($user)->json($method, $this->link($server1, '/databases/' . $hashids->encode($database1->id) . $endpoint))
->assertStatus($method === 'DELETE' ? 204 : 200);
// This request fails because the database is valid for that server but the user
// making the request is not authorized to perform that action.
$this->actingAs($user)->json($method, $this->link($server2, '/databases/' . $hashids->encode($database2->id) . $endpoint))->assertForbidden();
// Both of these should report a 404 error due to the database being linked to
// servers that are not the same as the server in the request, or are assigned
// to a server for which the user making the request has no access to.
$this->actingAs($user)->json($method, $this->link($server1, '/databases/' . $hashids->encode($database2->id) . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server1, '/databases/' . $hashids->encode($database3->id) . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server2, '/databases/' . $hashids->encode($database3->id) . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server3, '/databases/' . $hashids->encode($database3->id) . $endpoint))->assertNotFound();
}
/**
* @return \string[][]
*/
public function methodDataProvider(): array
{
return [
['POST', '/rotate-password'],
['DELETE', ''],
];
}
}

View file

@ -32,7 +32,7 @@ class NetworkAllocationControllerTest extends ClientApiIntegrationTestCase
public function testServerAllocationsAreNotReturnedWithoutPermission()
{
[$user, $server] = $this->generateTestAccount();
$user2 = factory(User::class)->create();
$user2 = User::factory()->create();
$server->owner_id = $user2->id;
$server->save();
@ -49,7 +49,6 @@ class NetworkAllocationControllerTest extends ClientApiIntegrationTestCase
/**
* Tests that notes on an allocation can be set correctly.
*
* @param array $permissions
* @dataProvider updatePermissionsDataProvider
*/
public function testAllocationNotesCanBeUpdated(array $permissions)
@ -85,7 +84,7 @@ class NetworkAllocationControllerTest extends ClientApiIntegrationTestCase
public function testAllocationNotesCannotBeUpdatedByInvalidUsers()
{
[$user, $server] = $this->generateTestAccount();
$user2 = factory(User::class)->create();
$user2 = User::factory()->create();
$server->owner_id = $user2->id;
$server->save();
@ -98,14 +97,13 @@ class NetworkAllocationControllerTest extends ClientApiIntegrationTestCase
}
/**
* @param array $permissions
* @dataProvider updatePermissionsDataProvider
*/
public function testPrimaryAllocationCanBeModified(array $permissions)
{
[$user, $server] = $this->generateTestAccount($permissions);
$allocation = $server->allocation;
$allocation2 = factory(Allocation::class)->create(['node_id' => $server->node_id, 'server_id' => $server->id]);
$allocation2 = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server->id]);
$server->allocation_id = $allocation->id;
$server->save();
@ -121,7 +119,7 @@ class NetworkAllocationControllerTest extends ClientApiIntegrationTestCase
public function testPrimaryAllocationCannotBeModifiedByInvalidUser()
{
[$user, $server] = $this->generateTestAccount();
$user2 = factory(User::class)->create();
$user2 = User::factory()->create();
$server->owner_id = $user2->id;
$server->save();

View file

@ -15,7 +15,6 @@ class PowerControllerTest extends ClientApiIntegrationTestCase
* an error in response. This checks against the specific permission needed to send
* the command to the server.
*
* @param string $action
* @param string[] $permissions
* @dataProvider invalidPermissionDataProvider
*/
@ -47,8 +46,6 @@ class PowerControllerTest extends ClientApiIntegrationTestCase
/**
* Test that sending a valid power actions works.
*
* @param string $action
* @param string $permission
* @dataProvider validPowerActionDataProvider
*/
public function testActionCanBeSentToServer(string $action, string $permission)
@ -74,8 +71,6 @@ class PowerControllerTest extends ClientApiIntegrationTestCase
/**
* Returns invalid permission combinations for a given power action.
*
* @return array
*/
public function invalidPermissionDataProvider(): array
{
@ -88,9 +83,6 @@ class PowerControllerTest extends ClientApiIntegrationTestCase
];
}
/**
* @return array
*/
public function validPowerActionDataProvider(): array
{
return [

View file

@ -25,6 +25,7 @@ class CreateServerScheduleTest extends ClientApiIntegrationTestCase
'minute' => '0',
'hour' => '*/2',
'day_of_week' => '2',
'month' => '1',
'day_of_month' => '*',
]);
@ -39,6 +40,7 @@ class CreateServerScheduleTest extends ClientApiIntegrationTestCase
$this->assertSame('0', $schedule->cron_minute);
$this->assertSame('*/2', $schedule->cron_hour);
$this->assertSame('2', $schedule->cron_day_of_week);
$this->assertSame('1', $schedule->cron_month);
$this->assertSame('*', $schedule->cron_day_of_month);
$this->assertSame('Test Schedule', $schedule->name);
@ -69,6 +71,7 @@ class CreateServerScheduleTest extends ClientApiIntegrationTestCase
'minute' => '*',
'hour' => '*',
'day_of_month' => '*',
'month' => '*',
'day_of_week' => '*',
])
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
@ -87,9 +90,6 @@ class CreateServerScheduleTest extends ClientApiIntegrationTestCase
->assertForbidden();
}
/**
* @return array
*/
public function permissionsDataProvider(): array
{
return [[[]], [[Permission::ACTION_SCHEDULE_CREATE]]];

View file

@ -20,8 +20,8 @@ class DeleteServerScheduleTest extends ClientApiIntegrationTestCase
{
[$user, $server] = $this->generateTestAccount($permissions);
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$task = factory(Task::class)->create(['schedule_id' => $schedule->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$task = Task::factory()->create(['schedule_id' => $schedule->id]);
$this->actingAs($user)
->deleteJson("/api/client/servers/{$server->uuid}/schedules/{$schedule->id}")
@ -52,7 +52,7 @@ class DeleteServerScheduleTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
[, $server2] = $this->generateTestAccount(['user_id' => $user->id]);
$schedule = factory(Schedule::class)->create(['server_id' => $server2->id]);
$schedule = Schedule::factory()->create(['server_id' => $server2->id]);
$this->actingAs($user)
->deleteJson("/api/client/servers/{$server->uuid}/schedules/{$schedule->id}")
@ -69,7 +69,7 @@ class DeleteServerScheduleTest extends ClientApiIntegrationTestCase
{
[$user, $server] = $this->generateTestAccount([Permission::ACTION_SCHEDULE_UPDATE]);
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$this->actingAs($user)
->deleteJson("/api/client/servers/{$server->uuid}/schedules/{$schedule->id}")
@ -78,9 +78,6 @@ class DeleteServerScheduleTest extends ClientApiIntegrationTestCase
$this->assertDatabaseHas('schedules', ['id' => $schedule->id]);
}
/**
* @return array
*/
public function permissionsDataProvider(): array
{
return [[[]], [[Permission::ACTION_SCHEDULE_DELETE]]];

View file

@ -15,7 +15,6 @@ class ExecuteScheduleTest extends ClientApiIntegrationTestCase
/**
* Test that a schedule can be executed and is updated in the database correctly.
*
* @param array $permissions
* @dataProvider permissionsDataProvider
*/
public function testScheduleIsExecutedRightAway(array $permissions)
@ -25,7 +24,7 @@ class ExecuteScheduleTest extends ClientApiIntegrationTestCase
Bus::fake();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create([
$schedule = Schedule::factory()->create([
'server_id' => $server->id,
]);
@ -35,7 +34,7 @@ class ExecuteScheduleTest extends ClientApiIntegrationTestCase
$response->assertJsonPath('errors.0.detail', 'Cannot process schedule for task execution: no tasks are registered.');
/** @var \Pterodactyl\Models\Task $task */
$task = factory(Task::class)->create([
$task = Task::factory()->create([
'schedule_id' => $schedule->id,
'sequence_id' => 1,
'time_offset' => 2,
@ -60,12 +59,12 @@ class ExecuteScheduleTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create([
$schedule = Schedule::factory()->create([
'server_id' => $server->id,
'is_active' => false,
]);
$response = $this->actingAs($user)->postJson($this->link($schedule, "/execute"));
$response = $this->actingAs($user)->postJson($this->link($schedule, '/execute'));
$response->assertStatus(Response::HTTP_BAD_REQUEST);
$response->assertJsonPath('errors.0.code', 'BadRequestHttpException');
@ -80,14 +79,11 @@ class ExecuteScheduleTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount([Permission::ACTION_SCHEDULE_CREATE]);
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$this->actingAs($user)->postJson($this->link($schedule, '/execute'))->assertForbidden();
}
/**
* @return array
*/
public function permissionsDataProvider(): array
{
return [[[]], [[Permission::ACTION_SCHEDULE_UPDATE]]];

View file

@ -24,7 +24,7 @@ class GetServerSchedulesTest extends ClientApiIntegrationTestCase
* Test that schedules for a server are returned.
*
* @param array $permissions
* @param bool $individual
* @param bool $individual
* @dataProvider permissionsDataProvider
*/
public function testServerSchedulesAreReturned($permissions, $individual)
@ -32,9 +32,9 @@ class GetServerSchedulesTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount($permissions);
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
/** @var \Pterodactyl\Models\Task $task */
$task = factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 1, 'time_offset' => 0]);
$task = Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 1, 'time_offset' => 0]);
$response = $this->actingAs($user)
->getJson(
@ -45,7 +45,7 @@ class GetServerSchedulesTest extends ClientApiIntegrationTestCase
->assertOk();
$prefix = $individual ? '' : 'data.0.';
if (! $individual) {
if (!$individual) {
$response->assertJsonCount(1, 'data');
}
@ -66,7 +66,7 @@ class GetServerSchedulesTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
[, $server2] = $this->generateTestAccount(['user_id' => $user->id]);
$schedule = factory(Schedule::class)->create(['server_id' => $server2->id]);
$schedule = Schedule::factory()->create(['server_id' => $server2->id]);
$this->actingAs($user)
->getJson("/api/client/servers/{$server->uuid}/schedules/{$schedule->id}")
@ -84,16 +84,13 @@ class GetServerSchedulesTest extends ClientApiIntegrationTestCase
->getJson("/api/client/servers/{$server->uuid}/schedules")
->assertForbidden();
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$this->actingAs($user)
->getJson("/api/client/servers/{$server->uuid}/schedules/{$schedule->id}")
->assertForbidden();
}
/**
* @return array
*/
public function permissionsDataProvider(): array
{
return [

View file

@ -0,0 +1,70 @@
<?php
namespace Pterodactyl\Tests\Integration\Api\Client\Server\Schedule;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Models\Schedule;
use Pterodactyl\Tests\Integration\Api\Client\ClientApiIntegrationTestCase;
class ScheduleAuthorizationTest extends ClientApiIntegrationTestCase
{
/**
* Tests that a subuser with access to two servers cannot improperly access a resource
* on Server A when providing a URL that points to Server B. This prevents a regression
* in the code where controllers didn't properly validate that a resource was assigned
* to the server that was also present in the URL.
*
* The comments within the test code itself are better at explaining exactly what is
* being tested and protected against.
*
* @dataProvider methodDataProvider
*/
public function testAccessToAServersSchedulesIsRestrictedProperly(string $method, string $endpoint)
{
// The API $user is the owner of $server1.
[$user, $server1] = $this->generateTestAccount();
// Will be a subuser of $server2.
$server2 = $this->createServerModel();
// And as no access to $server3.
$server3 = $this->createServerModel();
// Set the API $user as a subuser of server 2, but with no permissions
// to do anything with the schedules for that server.
Subuser::factory()->create(['server_id' => $server2->id, 'user_id' => $user->id]);
$schedule1 = Schedule::factory()->create(['server_id' => $server1->id]);
$schedule2 = Schedule::factory()->create(['server_id' => $server2->id]);
$schedule3 = Schedule::factory()->create(['server_id' => $server3->id]);
// This is the only valid call for this test, accessing the schedule for the same
// server that the API user is the owner of.
$response = $this->actingAs($user)->json($method, $this->link($server1, '/schedules/' . $schedule1->id . $endpoint));
$this->assertTrue($response->status() <= 204 || $response->status() === 400 || $response->status() === 422);
// This request fails because the schedule is valid for that server but the user
// making the request is not authorized to perform that action.
$this->actingAs($user)->json($method, $this->link($server2, '/schedules/' . $schedule2->id . $endpoint))->assertForbidden();
// Both of these should report a 404 error due to the schedules being linked to
// servers that are not the same as the server in the request, or are assigned
// to a server for which the user making the request has no access to.
$this->actingAs($user)->json($method, $this->link($server1, '/schedules/' . $schedule2->id . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server1, '/schedules/' . $schedule3->id . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server2, '/schedules/' . $schedule3->id . $endpoint))->assertNotFound();
$this->actingAs($user)->json($method, $this->link($server3, '/schedules/' . $schedule3->id . $endpoint))->assertNotFound();
}
/**
* @return \string[][]
*/
public function methodDataProvider(): array
{
return [
['GET', ''],
['POST', ''],
['DELETE', ''],
['POST', '/execute'],
['POST', '/tasks'],
];
}
}

View file

@ -19,6 +19,7 @@ class UpdateServerScheduleTest extends ClientApiIntegrationTestCase
'minute' => '5',
'hour' => '*',
'day_of_week' => '*',
'month' => '*',
'day_of_month' => '*',
'is_active' => false,
];
@ -34,8 +35,8 @@ class UpdateServerScheduleTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount($permissions);
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$expected = Utilities::getScheduleNextRunDate('5', '*', '*', '*');
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$expected = Utilities::getScheduleNextRunDate('5', '*', '*', '*', '*');
$response = $this->actingAs($user)
->postJson("/api/client/servers/{$server->uuid}/schedules/{$schedule->id}", $this->updateData);
@ -59,7 +60,7 @@ class UpdateServerScheduleTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
[, $server2] = $this->generateTestAccount(['user_id' => $user->id]);
$schedule = factory(Schedule::class)->create(['server_id' => $server2->id]);
$schedule = Schedule::factory()->create(['server_id' => $server2->id]);
$this->actingAs($user)
->postJson("/api/client/servers/{$server->uuid}/schedules/{$schedule->id}")
@ -74,7 +75,7 @@ class UpdateServerScheduleTest extends ClientApiIntegrationTestCase
{
[$user, $server] = $this->generateTestAccount([Permission::ACTION_SCHEDULE_CREATE]);
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$this->actingAs($user)
->postJson("/api/client/servers/{$server->uuid}/schedules/{$schedule->id}")
@ -92,7 +93,7 @@ class UpdateServerScheduleTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create([
$schedule = Schedule::factory()->create([
'server_id' => $server->id,
'is_active' => true,
'is_processing' => true,
@ -111,9 +112,6 @@ class UpdateServerScheduleTest extends ClientApiIntegrationTestCase
$this->assertFalse($schedule->is_processing);
}
/**
* @return array
*/
public function permissionsDataProvider(): array
{
return [[[]], [[Permission::ACTION_SCHEDULE_UPDATE]]];

View file

@ -21,7 +21,7 @@ class CreateServerScheduleTaskTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount($permissions);
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$this->assertEmpty($schedule->tasks);
$response = $this->actingAs($user)->postJson($this->link($schedule, '/tasks'), [
@ -51,7 +51,7 @@ class CreateServerScheduleTaskTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$response = $this->actingAs($user)->postJson($this->link($schedule, '/tasks'))->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
@ -96,7 +96,7 @@ class CreateServerScheduleTaskTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$this->actingAs($user)->postJson($this->link($schedule, '/tasks'), [
'action' => 'backup',
@ -121,8 +121,8 @@ class CreateServerScheduleTaskTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
factory(Task::class)->times(2)->create(['schedule_id' => $schedule->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
Task::factory()->times(2)->create(['schedule_id' => $schedule->id]);
$this->actingAs($user)->postJson($this->link($schedule, '/tasks'), [
'action' => 'command',
@ -144,7 +144,7 @@ class CreateServerScheduleTaskTest extends ClientApiIntegrationTestCase
[, $server2] = $this->generateTestAccount(['user_id' => $user->id]);
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server2->id]);
$schedule = Schedule::factory()->create(['server_id' => $server2->id]);
$this->actingAs($user)
->postJson("/api/client/servers/{$server->uuid}/schedules/{$schedule->id}/tasks")
@ -160,16 +160,13 @@ class CreateServerScheduleTaskTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount([Permission::ACTION_SCHEDULE_CREATE]);
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$this->actingAs($user)
->postJson($this->link($schedule, '/tasks'))
->assertForbidden();
}
/**
* @return array
*/
public function permissionsDataProvider(): array
{
return [[[]], [[Permission::ACTION_SCHEDULE_UPDATE]]];

View file

@ -19,8 +19,8 @@ class DeleteScheduleTaskTest extends ClientApiIntegrationTestCase
$server2 = $this->createServerModel();
[$user] = $this->generateTestAccount();
$schedule = factory(Schedule::class)->create(['server_id' => $server2->id]);
$task = factory(Task::class)->create(['schedule_id' => $schedule->id]);
$schedule = Schedule::factory()->create(['server_id' => $server2->id]);
$task = Task::factory()->create(['schedule_id' => $schedule->id]);
$this->actingAs($user)->deleteJson($this->link($task))->assertNotFound();
}
@ -33,9 +33,9 @@ class DeleteScheduleTaskTest extends ClientApiIntegrationTestCase
{
[$user, $server] = $this->generateTestAccount();
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule2 = factory(Schedule::class)->create(['server_id' => $server->id]);
$task = factory(Task::class)->create(['schedule_id' => $schedule->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$schedule2 = Schedule::factory()->create(['server_id' => $server->id]);
$task = Task::factory()->create(['schedule_id' => $schedule->id]);
$this->actingAs($user)->deleteJson("/api/client/servers/{$server->uuid}/schedules/{$schedule2->id}/tasks/{$task->id}")->assertNotFound();
}
@ -47,12 +47,12 @@ class DeleteScheduleTaskTest extends ClientApiIntegrationTestCase
{
[$user, $server] = $this->generateTestAccount([Permission::ACTION_SCHEDULE_CREATE]);
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$task = factory(Task::class)->create(['schedule_id' => $schedule->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$task = Task::factory()->create(['schedule_id' => $schedule->id]);
$this->actingAs($user)->deleteJson($this->link($task))->assertForbidden();
$user2 = factory(User::class)->create();
$user2 = User::factory()->create();
$this->actingAs($user2)->deleteJson($this->link($task))->assertNotFound();
}
@ -65,12 +65,12 @@ class DeleteScheduleTaskTest extends ClientApiIntegrationTestCase
{
[$user, $server] = $this->generateTestAccount();
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$tasks = [
factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 1]),
factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 2]),
factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 3]),
factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 4]),
Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 1]),
Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 2]),
Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 3]),
Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 4]),
];
$response = $this->actingAs($user)->deleteJson($this->link($tasks[1]));

View file

@ -110,17 +110,11 @@ class SettingsControllerTest extends ClientApiIntegrationTestCase
$this->assertTrue($server->isInstalled());
}
/**
* @return array
*/
public function renamePermissionsDataProvider(): array
{
return [[[]], [[Permission::ACTION_SETTINGS_RENAME]]];
}
/**
* @return array
*/
public function reinstallPermissionsDataProvider(): array
{
return [[[]], [[Permission::ACTION_SETTINGS_REINSTALL]]];

View file

@ -34,7 +34,7 @@ class GetStartupAndVariablesTest extends ClientApiIntegrationTestCase
])->save();
$server = $server->refresh();
$response = $this->actingAs($user)->getJson($this->link($server) . "/startup");
$response = $this->actingAs($user)->getJson($this->link($server) . '/startup');
$response->assertOk();
$response->assertJsonPath('meta.startup_command', 'java bungeecord.jar --version [hidden]');
@ -53,10 +53,10 @@ class GetStartupAndVariablesTest extends ClientApiIntegrationTestCase
public function testStartupDataIsNotReturnedWithoutPermission()
{
[$user, $server] = $this->generateTestAccount([Permission::ACTION_WEBSOCKET_CONNECT]);
$this->actingAs($user)->getJson($this->link($server) . "/startup")->assertForbidden();
$this->actingAs($user)->getJson($this->link($server) . '/startup')->assertForbidden();
$user2 = factory(User::class)->create();
$this->actingAs($user2)->getJson($this->link($server) . "/startup")->assertNotFound();
$user2 = User::factory()->create();
$this->actingAs($user2)->getJson($this->link($server) . '/startup')->assertNotFound();
}
/**

View file

@ -49,7 +49,6 @@ class UpdateStartupVariableTest extends ClientApiIntegrationTestCase
* Test that variables that are either not user_viewable, or not user_editable, cannot be
* updated via this endpoint.
*
* @param array $permissions
* @dataProvider permissionsDataProvider
*/
public function testStartupVariableCannotBeUpdatedIfNotUserViewableOrEditable(array $permissions)
@ -145,10 +144,10 @@ class UpdateStartupVariableTest extends ClientApiIntegrationTestCase
public function testStartupVariableCannotBeUpdatedIfNotUserViewable()
{
[$user, $server] = $this->generateTestAccount([Permission::ACTION_WEBSOCKET_CONNECT]);
$this->actingAs($user)->putJson($this->link($server) . "/startup/variable")->assertForbidden();
$this->actingAs($user)->putJson($this->link($server) . '/startup/variable')->assertForbidden();
$user2 = factory(User::class)->create();
$this->actingAs($user2)->putJson($this->link($server) . "/startup/variable")->assertNotFound();
$user2 = User::factory()->create();
$this->actingAs($user2)->putJson($this->link($server) . '/startup/variable')->assertNotFound();
}
/**

View file

@ -24,7 +24,7 @@ class CreateServerSubuserTest extends ClientApiIntegrationTestCase
{
[$user, $server] = $this->generateTestAccount($permissions);
$response = $this->actingAs($user)->postJson($this->link($server) . "/users", [
$response = $this->actingAs($user)->postJson($this->link($server) . '/users', [
'email' => $email = $this->faker->email,
'permissions' => [
Permission::ACTION_USER_CREATE,
@ -61,7 +61,7 @@ class CreateServerSubuserTest extends ClientApiIntegrationTestCase
Permission::ACTION_CONTROL_CONSOLE,
]);
$response = $this->actingAs($user)->postJson($this->link($server) . "/users", [
$response = $this->actingAs($user)->postJson($this->link($server) . '/users', [
'email' => $email = $this->faker->email,
'permissions' => [
Permission::ACTION_USER_CREATE,
@ -83,7 +83,7 @@ class CreateServerSubuserTest extends ClientApiIntegrationTestCase
$email = str_repeat(Str::random(20), 9) . '1@gmail.com'; // 191 is the hard limit for the column in MySQL.
$response = $this->actingAs($user)->postJson($this->link($server) . "/users", [
$response = $this->actingAs($user)->postJson($this->link($server) . '/users', [
'email' => $email,
'permissions' => [
Permission::ACTION_USER_CREATE,
@ -92,7 +92,7 @@ class CreateServerSubuserTest extends ClientApiIntegrationTestCase
$response->assertOk();
$response = $this->actingAs($user)->postJson($this->link($server) . "/users", [
$response = $this->actingAs($user)->postJson($this->link($server) . '/users', [
'email' => $email . '.au',
'permissions' => [
Permission::ACTION_USER_CREATE,
@ -113,9 +113,9 @@ class CreateServerSubuserTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
/** @var \Pterodactyl\Models\User $existing */
$existing = factory(User::class)->create(['email' => $this->faker->email]);
$existing = User::factory()->create(['email' => $this->faker->email]);
$response = $this->actingAs($user)->postJson($this->link($server) . "/users", [
$response = $this->actingAs($user)->postJson($this->link($server) . '/users', [
'email' => $existing->email,
'permissions' => [
Permission::ACTION_USER_CREATE,
@ -135,7 +135,7 @@ class CreateServerSubuserTest extends ClientApiIntegrationTestCase
{
[$user, $server] = $this->generateTestAccount();
$response = $this->actingAs($user)->postJson($this->link($server) . "/users", [
$response = $this->actingAs($user)->postJson($this->link($server) . '/users', [
'email' => $email = $this->faker->email,
'permissions' => [
Permission::ACTION_USER_CREATE,
@ -144,7 +144,7 @@ class CreateServerSubuserTest extends ClientApiIntegrationTestCase
$response->assertOk();
$response = $this->actingAs($user)->postJson($this->link($server) . "/users", [
$response = $this->actingAs($user)->postJson($this->link($server) . '/users', [
'email' => $email,
'permissions' => [
Permission::ACTION_USER_CREATE,
@ -156,9 +156,6 @@ class CreateServerSubuserTest extends ClientApiIntegrationTestCase
$response->assertJsonPath('errors.0.detail', 'A user with that email address is already assigned as a subuser for this server.');
}
/**
* @return array
*/
public function permissionsDataProvider(): array
{
return [[[]], [[Permission::ACTION_USER_CREATE]]];

View file

@ -30,13 +30,13 @@ class DeleteSubuserTest extends ClientApiIntegrationTestCase
[$user, $server] = $this->generateTestAccount();
/** @var \Pterodactyl\Models\User $differentUser */
$differentUser = factory(User::class)->create();
$differentUser = User::factory()->create();
// Generate a UUID that lines up with a user in the database if it were to be cast to an int.
$uuid = $differentUser->id . str_repeat('a', strlen((string)$differentUser->id)) . substr(Uuid::uuid4()->toString(), 8);
$uuid = $differentUser->id . str_repeat('a', strlen((string) $differentUser->id)) . substr(Uuid::uuid4()->toString(), 8);
/** @var \Pterodactyl\Models\User $subuser */
$subuser = factory(User::class)->create(['uuid' => $uuid]);
$subuser = User::factory()->create(['uuid' => $uuid]);
Subuser::query()->forceCreate([
'user_id' => $subuser->id,
@ -52,7 +52,7 @@ class DeleteSubuserTest extends ClientApiIntegrationTestCase
// anything in the database.
$uuid = '18180000' . substr(Uuid::uuid4()->toString(), 8);
/** @var \Pterodactyl\Models\User $subuser */
$subuser = factory(User::class)->create(['uuid' => $uuid]);
$subuser = User::factory()->create(['uuid' => $uuid]);
Subuser::query()->forceCreate([
'user_id' => $subuser->id,

View file

@ -0,0 +1,60 @@
<?php
namespace Pterodactyl\Tests\Integration\Api\Client\Server\Subuser;
use Mockery;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Repositories\Wings\DaemonServerRepository;
use Pterodactyl\Tests\Integration\Api\Client\ClientApiIntegrationTestCase;
class SubuserAuthorizationTest extends ClientApiIntegrationTestCase
{
/**
* Test that mismatched subusers are not accessible to a server.
*
* @dataProvider methodDataProvider
*/
public function testUserCannotAccessResourceBelongingToOtherServers(string $method)
{
// Generic subuser, the specific resource we're trying to access.
/** @var \Pterodactyl\Models\User $internal */
$internal = User::factory()->create();
// The API $user is the owner of $server1.
[$user, $server1] = $this->generateTestAccount();
// Will be a subuser of $server2.
$server2 = $this->createServerModel();
// And as no access to $server3.
$server3 = $this->createServerModel();
// Set the API $user as a subuser of server 2, but with no permissions
// to do anything with the subusers for that server.
Subuser::factory()->create(['server_id' => $server2->id, 'user_id' => $user->id]);
Subuser::factory()->create(['server_id' => $server1->id, 'user_id' => $internal->id]);
Subuser::factory()->create(['server_id' => $server2->id, 'user_id' => $internal->id]);
Subuser::factory()->create(['server_id' => $server3->id, 'user_id' => $internal->id]);
$this->instance(DaemonServerRepository::class, $mock = Mockery::mock(DaemonServerRepository::class));
if ($method === 'DELETE') {
$mock->expects('setServer->revokeUserJTI')->with($internal->id)->andReturnUndefined();
}
// This route is acceptable since they're accessing a subuser on their own server.
$this->actingAs($user)->json($method, $this->link($server1, '/users/' . $internal->uuid))->assertStatus($method === 'POST' ? 422 : ($method === 'DELETE' ? 204 : 200));
// This route can be revealed since the subuser belongs to the correct server, but
// errors out with a 403 since $user does not have the right permissions for this.
$this->actingAs($user)->json($method, $this->link($server2, '/users/' . $internal->uuid))->assertForbidden();
$this->actingAs($user)->json($method, $this->link($server3, '/users/' . $internal->uuid))->assertNotFound();
}
/**
* @return \string[][]
*/
public function methodDataProvider(): array
{
return [['GET'], ['POST'], ['DELETE']];
}
}

View file

@ -2,12 +2,13 @@
namespace Pterodactyl\Tests\Integration\Api\Client\Server;
use Carbon\Carbon;
use Lcobucci\JWT\Parser;
use Carbon\CarbonImmutable;
use Illuminate\Http\Response;
use Lcobucci\JWT\Configuration;
use Pterodactyl\Models\Permission;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Pterodactyl\Tests\Integration\Api\Client\ClientApiIntegrationTestCase;
class WebsocketControllerTest extends ClientApiIntegrationTestCase
@ -32,8 +33,6 @@ class WebsocketControllerTest extends ClientApiIntegrationTestCase
*/
public function testJwtAndWebsocketUrlAreReturnedForServerOwner()
{
CarbonImmutable::setTestNow(Carbon::now());
/** @var \Pterodactyl\Models\User $user */
/** @var \Pterodactyl\Models\Server $server */
[$user, $server] = $this->generateTestAccount();
@ -51,22 +50,33 @@ class WebsocketControllerTest extends ClientApiIntegrationTestCase
$this->assertStringStartsWith('wss://', $connection, 'Failed asserting that websocket connection address has expected "wss://" prefix.');
$this->assertStringEndsWith("/api/servers/{$server->uuid}/ws", $connection, 'Failed asserting that websocket connection address uses expected Wings endpoint.');
$token = (new Parser)->parse($response->json('data.token'));
$config = Configuration::forSymmetricSigner(new Sha256(), $key = InMemory::plainText($server->node->getDecryptedKey()));
$config->setValidationConstraints(new SignedWith(new Sha256(), $key));
/** @var \Lcobucci\JWT\Token\Plain $token */
$token = $config->parser()->parse($response->json('data.token'));
$this->assertTrue(
$token->verify(new Sha256, $server->node->getDecryptedKey()),
$config->validator()->validate($token, ...$config->validationConstraints()),
'Failed to validate that the JWT data returned was signed using the Node\'s secret key.'
);
// The way we generate times for the JWT will truncate the microseconds from the
// time, but CarbonImmutable::now() will include them, thus causing test failures.
//
// This little chunk of logic just strips those out by generating a new CarbonImmutable
// instance from the current timestamp, which is how the JWT works. We also need to
// switch to UTC here for consistency.
$expect = CarbonImmutable::createFromTimestamp(CarbonImmutable::now()->getTimestamp())->timezone('UTC');
// Check that the claims are generated correctly.
$this->assertSame(config('app.url'), $token->getClaim('iss'));
$this->assertSame($server->node->getConnectionAddress(), $token->getClaim('aud'));
$this->assertSame(CarbonImmutable::now()->getTimestamp(), $token->getClaim('iat'));
$this->assertSame(CarbonImmutable::now()->subMinutes(5)->getTimestamp(), $token->getClaim('nbf'));
$this->assertSame(CarbonImmutable::now()->addMinutes(10)->getTimestamp(), $token->getClaim('exp'));
$this->assertSame($user->id, $token->getClaim('user_id'));
$this->assertSame($server->uuid, $token->getClaim('server_uuid'));
$this->assertSame(['*'], $token->getClaim('permissions'));
$this->assertTrue($token->hasBeenIssuedBy(config('app.url')));
$this->assertTrue($token->isPermittedFor($server->node->getConnectionAddress()));
$this->assertEquals($expect, $token->claims()->get('iat'));
$this->assertEquals($expect->subMinutes(5), $token->claims()->get('nbf'));
$this->assertEquals($expect->addMinutes(10), $token->claims()->get('exp'));
$this->assertSame($user->id, $token->claims()->get('user_id'));
$this->assertSame($server->uuid, $token->claims()->get('server_uuid'));
$this->assertSame(['*'], $token->claims()->get('permissions'));
}
/**
@ -85,14 +95,17 @@ class WebsocketControllerTest extends ClientApiIntegrationTestCase
$response->assertOk();
$response->assertJsonStructure(['data' => ['token', 'socket']]);
$token = (new Parser)->parse($response->json('data.token'));
$config = Configuration::forSymmetricSigner(new Sha256(), $key = InMemory::plainText($server->node->getDecryptedKey()));
$config->setValidationConstraints(new SignedWith(new Sha256(), $key));
/** @var \Lcobucci\JWT\Token\Plain $token */
$token = $config->parser()->parse($response->json('data.token'));
$this->assertTrue(
$token->verify(new Sha256, $server->node->getDecryptedKey()),
$config->validator()->validate($token, ...$config->validationConstraints()),
'Failed to validate that the JWT data returned was signed using the Node\'s secret key.'
);
// Check that the claims are generated correctly.
$this->assertSame($permissions, $token->getClaim('permissions'));
$this->assertSame($permissions, $token->claims()->get('permissions'));
}
}

View file

@ -18,7 +18,7 @@ class TwoFactorControllerTest extends ClientApiIntegrationTestCase
public function testTwoFactorImageDataIsReturned()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create(['use_totp' => false]);
$user = User::factory()->create(['use_totp' => false]);
$this->assertFalse($user->use_totp);
$this->assertEmpty($user->totp_secret);
@ -42,7 +42,7 @@ class TwoFactorControllerTest extends ClientApiIntegrationTestCase
public function testErrorIsReturnedWhenTwoFactorIsAlreadyEnabled()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create(['use_totp' => true]);
$user = User::factory()->create(['use_totp' => true]);
$response = $this->actingAs($user)->getJson('/api/client/account/two-factor');
@ -57,7 +57,7 @@ class TwoFactorControllerTest extends ClientApiIntegrationTestCase
public function testValidationErrorIsReturnedIfInvalidDataIsPassedToEnabled2FA()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create(['use_totp' => false]);
$user = User::factory()->create(['use_totp' => false]);
$response = $this->actingAs($user)->postJson('/api/client/account/two-factor', [
'code' => '',
@ -74,7 +74,7 @@ class TwoFactorControllerTest extends ClientApiIntegrationTestCase
public function testTwoFactorCanBeEnabledOnAccount()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create(['use_totp' => false]);
$user = User::factory()->create(['use_totp' => false]);
// Make the initial call to get the account setup for 2FA.
$this->actingAs($user)->getJson('/api/client/account/two-factor')->assertOk();
@ -111,9 +111,7 @@ class TwoFactorControllerTest extends ClientApiIntegrationTestCase
}
}
throw new ExpectationFailedException(
sprintf('Failed asserting that token [%s] exists as a hashed value in recovery_tokens table.', $raw)
);
throw new ExpectationFailedException(sprintf('Failed asserting that token [%s] exists as a hashed value in recovery_tokens table.', $raw));
}
}
@ -126,7 +124,7 @@ class TwoFactorControllerTest extends ClientApiIntegrationTestCase
Carbon::setTestNow(Carbon::now());
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create(['use_totp' => true]);
$user = User::factory()->create(['use_totp' => true]);
$response = $this->actingAs($user)->deleteJson('/api/client/account/two-factor', [
'password' => 'invalid',
@ -157,7 +155,7 @@ class TwoFactorControllerTest extends ClientApiIntegrationTestCase
Carbon::setTestNow(Carbon::now());
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create(['use_totp' => false]);
$user = User::factory()->create(['use_totp' => false]);
$response = $this->actingAs($user)->deleteJson('/api/client/account/two-factor', [
'password' => 'password',

View file

@ -7,8 +7,8 @@ use Illuminate\Http\Request;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Subuser;
use Illuminate\Pagination\LengthAwarePaginator;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Http\Controllers\Admin\UserController;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
class UserControllerTest extends IntegrationTestCase
{
@ -23,8 +23,8 @@ class UserControllerTest extends IntegrationTestCase
{
$unique = Str::random(16);
$users = [
factory(User::class)->create(['username' => $unique . '_1']),
factory(User::class)->create(['username' => $unique . '_2']),
User::factory()->create(['username' => $unique . '_1']),
User::factory()->create(['username' => $unique . '_2']),
];
$servers = [
@ -51,9 +51,9 @@ class UserControllerTest extends IntegrationTestCase
$response = $data['users']->items();
$this->assertCount(2, $response);
$this->assertInstanceOf(User::class, $response[0]);
$this->assertSame(3, (int)$response[0]->servers_count);
$this->assertSame(0, (int)$response[0]->subuser_of_count);
$this->assertSame(1, (int)$response[1]->servers_count);
$this->assertSame(2, (int)$response[1]->subuser_of_count);
$this->assertSame(3, (int) $response[0]->servers_count);
$this->assertSame(0, (int) $response[0]->subuser_of_count);
$this->assertSame(1, (int) $response[1]->servers_count);
$this->assertSame(2, (int) $response[1]->subuser_of_count);
}
}

View file

@ -2,10 +2,10 @@
namespace Pterodactyl\Tests\Integration;
use Tests\TestCase;
use Cake\Chronos\Chronos;
use Carbon\CarbonImmutable;
use Pterodactyl\Tests\TestCase;
use Illuminate\Database\Eloquent\Model;
use Tests\Traits\Integration\CreatesTestModels;
use Pterodactyl\Tests\Traits\Integration\CreatesTestModels;
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
abstract class IntegrationTestCase extends TestCase
@ -36,13 +36,10 @@ abstract class IntegrationTestCase extends TestCase
/**
* Return an ISO-8601 formatted timestamp to use in the API response.
*
* @param string $timestamp
* @return string
*/
protected function formatTimestamp(string $timestamp): string
{
return Chronos::createFromFormat(Chronos::DEFAULT_TO_STRING_FORMAT, $timestamp)
return CarbonImmutable::createFromFormat(CarbonImmutable::DEFAULT_TO_STRING_FORMAT, $timestamp)
->setTimezone(BaseTransformer::RESPONSE_TIMEZONE)
->toIso8601String();
}

View file

@ -32,7 +32,7 @@ class FindAssignableAllocationServiceTest extends IntegrationTestCase
{
$server = $this->createServerModel();
$created = factory(Allocation::class)->create([
$created = Allocation::factory()->create([
'node_id' => $server->node_id,
'ip' => $server->allocation->ip,
]);
@ -74,7 +74,7 @@ class FindAssignableAllocationServiceTest extends IntegrationTestCase
config()->set('pterodactyl.client_features.allocations.range_start', 5000);
config()->set('pterodactyl.client_features.allocations.range_end', 5001);
factory(Allocation::class)->create([
Allocation::factory()->create([
'server_id' => $server2->id,
'node_id' => $server->node_id,
'ip' => $server->allocation->ip,
@ -92,8 +92,8 @@ class FindAssignableAllocationServiceTest extends IntegrationTestCase
config()->set('pterodactyl.client_features.allocations.range_start', 5000);
config()->set('pterodactyl.client_features.allocations.range_end', 5005);
for ($i = 5000; $i <= 5005; $i++) {
factory(Allocation::class)->create([
for ($i = 5000; $i <= 5005; ++$i) {
Allocation::factory()->create([
'ip' => $server->allocation->ip,
'port' => $i,
'node_id' => $server->node_id,
@ -115,7 +115,7 @@ class FindAssignableAllocationServiceTest extends IntegrationTestCase
{
$server = $this->createServerModel();
factory(Allocation::class)->times(5)->create(['node_id' => $server->node_id]);
Allocation::factory()->times(5)->create(['node_id' => $server->node_id]);
$this->expectException(NoAutoAllocationSpaceAvailableException::class);
$this->expectExceptionMessage('Cannot assign additional allocation: no more space available on node.');

View file

@ -3,7 +3,6 @@
namespace Pterodactyl\Tests\Integration\Services\Databases;
use Mockery;
use Exception;
use BadMethodCallException;
use InvalidArgumentException;
use Pterodactyl\Models\Database;
@ -63,9 +62,9 @@ class DatabaseManagementServiceTest extends IntegrationTestCase
public function testDatabaseCannotBeCreatedIfServerHasReachedLimit()
{
$server = $this->createServerModel(['database_limit' => 2]);
$host = factory(DatabaseHost::class)->create(['node_id' => $server->node_id]);
$host = DatabaseHost::factory()->create(['node_id' => $server->node_id]);
factory(Database::class)->times(2)->create(['server_id' => $server->id, 'database_host_id' => $host->id]);
Database::factory()->times(2)->create(['server_id' => $server->id, 'database_host_id' => $host->id]);
$this->expectException(TooManyDatabasesException::class);
@ -96,9 +95,9 @@ class DatabaseManagementServiceTest extends IntegrationTestCase
$server = $this->createServerModel();
$name = DatabaseManagementService::generateUniqueDatabaseName('soemthing', $server->id);
$host = factory(DatabaseHost::class)->create(['node_id' => $server->node_id]);
$host2 = factory(DatabaseHost::class)->create(['node_id' => $server->node_id]);
factory(Database::class)->create([
$host = DatabaseHost::factory()->create(['node_id' => $server->node_id]);
$host2 = DatabaseHost::factory()->create(['node_id' => $server->node_id]);
Database::factory()->create([
'database' => $name,
'database_host_id' => $host->id,
'server_id' => $server->id,
@ -125,7 +124,7 @@ class DatabaseManagementServiceTest extends IntegrationTestCase
$server = $this->createServerModel();
$name = DatabaseManagementService::generateUniqueDatabaseName('soemthing', $server->id);
$host = factory(DatabaseHost::class)->create(['node_id' => $server->node_id]);
$host = DatabaseHost::factory()->create(['node_id' => $server->node_id]);
$this->repository->expects('createDatabase')->with($name);
@ -167,7 +166,7 @@ class DatabaseManagementServiceTest extends IntegrationTestCase
$this->assertInstanceOf(Database::class, $response);
$this->assertSame($response->server_id, $server->id);
$this->assertRegExp('/^(u[\d]+_)(\w){10}$/', $username);
$this->assertMatchesRegularExpression('/^(u[\d]+_)(\w){10}$/', $username);
$this->assertSame($username, $secondUsername);
$this->assertSame(24, strlen($password));
@ -183,11 +182,11 @@ class DatabaseManagementServiceTest extends IntegrationTestCase
$server = $this->createServerModel();
$name = DatabaseManagementService::generateUniqueDatabaseName('soemthing', $server->id);
$host = factory(DatabaseHost::class)->create(['node_id' => $server->node_id]);
$host = DatabaseHost::factory()->create(['node_id' => $server->node_id]);
$this->repository->expects('createDatabase')->with($name)->andThrows(new BadMethodCallException);
$this->repository->expects('createDatabase')->with($name)->andThrows(new BadMethodCallException());
$this->repository->expects('dropDatabase')->with($name);
$this->repository->expects('dropUser')->withAnyArgs()->andThrows(new InvalidArgumentException);
$this->repository->expects('dropUser')->withAnyArgs()->andThrows(new InvalidArgumentException());
$this->expectException(BadMethodCallException::class);
@ -200,9 +199,6 @@ class DatabaseManagementServiceTest extends IntegrationTestCase
$this->assertDatabaseMissing('databases', ['server_id' => $server->id]);
}
/**
* @return array
*/
public function invalidDataDataProvider(): array
{
return [

View file

@ -7,7 +7,6 @@ use Pterodactyl\Models\Node;
use InvalidArgumentException;
use Pterodactyl\Models\Database;
use Pterodactyl\Models\DatabaseHost;
use Symfony\Component\VarDumper\Cloner\Data;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Services\Databases\DatabaseManagementService;
use Pterodactyl\Services\Databases\DeployServerDatabaseService;
@ -53,7 +52,7 @@ class DeployServerDatabaseServiceTest extends IntegrationTestCase
$server = $this->createServerModel();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessageMatches('/^Expected a non-empty value\. Got: /',);
$this->expectExceptionMessageMatches('/^Expected a non-empty value\. Got: /', );
$this->getService()->handle($server, $data);
}
@ -65,8 +64,8 @@ class DeployServerDatabaseServiceTest extends IntegrationTestCase
{
$server = $this->createServerModel();
$node = factory(Node::class)->create(['location_id' => $server->location->id]);
factory(DatabaseHost::class)->create(['node_id' => $node->id]);
$node = Node::factory()->create(['location_id' => $server->location->id]);
DatabaseHost::factory()->create(['node_id' => $node->id]);
config()->set('pterodactyl.client_features.databases.allow_random', false);
@ -100,15 +99,15 @@ class DeployServerDatabaseServiceTest extends IntegrationTestCase
{
$server = $this->createServerModel();
$node = factory(Node::class)->create(['location_id' => $server->location->id]);
factory(DatabaseHost::class)->create(['node_id' => $node->id]);
$host = factory(DatabaseHost::class)->create(['node_id' => $server->node_id]);
$node = Node::factory()->create(['location_id' => $server->location->id]);
DatabaseHost::factory()->create(['node_id' => $node->id]);
$host = DatabaseHost::factory()->create(['node_id' => $server->node_id]);
$this->managementService->expects('create')->with($server, [
'database_host_id' => $host->id,
'database' => "s{$server->id}_something",
'remote' => '%',
])->andReturns(new Database);
])->andReturns(new Database());
$response = $this->getService()->handle($server, [
'database' => 'something',
@ -127,14 +126,14 @@ class DeployServerDatabaseServiceTest extends IntegrationTestCase
{
$server = $this->createServerModel();
$node = factory(Node::class)->create(['location_id' => $server->location->id]);
$host = factory(DatabaseHost::class)->create(['node_id' => $node->id]);
$node = Node::factory()->create(['location_id' => $server->location->id]);
$host = DatabaseHost::factory()->create(['node_id' => $node->id]);
$this->managementService->expects('create')->with($server, [
'database_host_id' => $host->id,
'database' => "s{$server->id}_something",
'remote' => '%',
])->andReturns(new Database);
])->andReturns(new Database());
$response = $this->getService()->handle($server, [
'database' => 'something',
@ -144,9 +143,6 @@ class DeployServerDatabaseServiceTest extends IntegrationTestCase
$this->assertInstanceOf(Database::class, $response);
}
/**
* @return array
*/
public function invalidDataProvider(): array
{
return [

View file

@ -6,8 +6,8 @@ use Exception;
use Pterodactyl\Models\Node;
use InvalidArgumentException;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Location;
use Pterodactyl\Models\Database;
use Pterodactyl\Models\Location;
use Illuminate\Support\Collection;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Services\Deployment\FindViableNodesService;
@ -71,24 +71,24 @@ class FindViableNodesServiceTest extends IntegrationTestCase
public function testExpectedNodeIsReturnedForLocation()
{
/** @var \Pterodactyl\Models\Location[] $locations */
$locations = factory(Location::class)->times(2)->create();
$locations = Location::factory()->times(2)->create();
/** @var \Pterodactyl\Models\Node[] $nodes */
$nodes = [
// This node should never be returned once we've completed the initial test which
// runs without a location filter.
factory(Node::class)->create([
Node::factory()->create([
'location_id' => $locations[0]->id,
'memory' => 2048,
'disk' => 1024 * 100,
]),
factory(Node::class)->create([
Node::factory()->create([
'location_id' => $locations[1]->id,
'memory' => 1024,
'disk' => 10240,
'disk_overallocate' => 10,
]),
factory(Node::class)->create([
Node::factory()->create([
'location_id' => $locations[1]->id,
'memory' => 1024 * 4,
'memory_overallocate' => 50,
@ -112,7 +112,7 @@ class FindViableNodesServiceTest extends IntegrationTestCase
// Helper, I am lazy.
$base = function () use ($locations) {
return $this->getService()->setLocations([ $locations[1]->id ])->setDisk(512);
return $this->getService()->setLocations([$locations[1]->id])->setDisk(512);
};
// Expect that we can create this server on either node since the disk and memory

View file

@ -23,7 +23,7 @@ class ProcessScheduleServiceTest extends IntegrationTestCase
public function testScheduleWithNoTasksReturnsException()
{
$server = $this->createServerModel();
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
$this->expectException(DisplayException::class);
$this->expectExceptionMessage('Cannot process schedule for task execution: no tasks are registered.');
@ -39,13 +39,13 @@ class ProcessScheduleServiceTest extends IntegrationTestCase
$server = $this->createServerModel();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create([
$schedule = Schedule::factory()->create([
'server_id' => $server->id,
'cron_minute' => 'hodor', // this will break the getNextRunDate() function.
]);
/** @var \Pterodactyl\Models\Task $task */
$task = factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 1]);
$task = Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 1]);
$this->expectException(InvalidArgumentException::class);
@ -68,10 +68,10 @@ class ProcessScheduleServiceTest extends IntegrationTestCase
$server = $this->createServerModel();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
/** @var \Pterodactyl\Models\Task $task */
$task = factory(Task::class)->create(['schedule_id' => $schedule->id, 'time_offset' => 10, 'sequence_id' => 1]);
$task = Task::factory()->create(['schedule_id' => $schedule->id, 'time_offset' => 10, 'sequence_id' => 1]);
$this->getService()->handle($schedule, $now);
@ -100,16 +100,16 @@ class ProcessScheduleServiceTest extends IntegrationTestCase
$server = $this->createServerModel();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id]);
$schedule = Schedule::factory()->create(['server_id' => $server->id]);
/** @var \Pterodactyl\Models\Task $task */
$task2 = factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 4]);
$task = factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 2]);
$task3 = factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 3]);
$task2 = Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 4]);
$task = Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 2]);
$task3 = Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 3]);
$this->getService()->handle($schedule);
Bus::assertDispatched(RunTaskJob::class, function (RunTaskJob $job) use ($task) {
Bus::assertDispatched(RunTaskJob::class, function (RunTaskJob $job) use ($task) {
return $task->id === $job->task->id;
});
@ -131,9 +131,9 @@ class ProcessScheduleServiceTest extends IntegrationTestCase
$server = $this->createServerModel();
/** @var \Pterodactyl\Models\Schedule $schedule */
$schedule = factory(Schedule::class)->create(['server_id' => $server->id, 'last_run_at' => null]);
$schedule = Schedule::factory()->create(['server_id' => $server->id, 'last_run_at' => null]);
/** @var \Pterodactyl\Models\Task $task */
$task = factory(Task::class)->create(['schedule_id' => $schedule->id, 'sequence_id' => 1]);
$task = Task::factory()->create(['schedule_id' => $schedule->id, 'sequence_id' => 1]);
$dispatcher->expects('dispatchNow')->andThrows(new Exception('Test thrown exception'));
@ -151,9 +151,6 @@ class ProcessScheduleServiceTest extends IntegrationTestCase
$this->assertDatabaseHas('tasks', ['id' => $task->id, 'is_queued' => false]);
}
/**
* @return array
*/
public function dispatchNowDataProvider(): array
{
return [[true], [false]];

View file

@ -36,7 +36,7 @@ class BuildModificationServiceTest extends IntegrationTestCase
$server2 = $this->createServerModel();
/** @var \Pterodactyl\Models\Allocation[] $allocations */
$allocations = factory(Allocation::class)->times(4)->create(['node_id' => $server->node_id, 'notes' => 'Random notes']);
$allocations = Allocation::factory()->times(4)->create(['node_id' => $server->node_id, 'notes' => 'Random notes']);
$initialAllocationId = $server->allocation_id;
$allocations[0]->update(['server_id' => $server->id, 'notes' => 'Test notes']);
@ -83,7 +83,7 @@ class BuildModificationServiceTest extends IntegrationTestCase
{
$server = $this->createServerModel();
/** @var \Pterodactyl\Models\Allocation[] $allocations */
$allocations = factory(Allocation::class)->times(4)->create(['node_id' => $server->node_id]);
$allocations = Allocation::factory()->times(4)->create(['node_id' => $server->node_id]);
$allocations[0]->update(['server_id' => $server->id]);
@ -155,8 +155,8 @@ class BuildModificationServiceTest extends IntegrationTestCase
public function testNoExceptionIsThrownIfOnlyRemovingAllocation()
{
$server = $this->createServerModel();
/** @var \Pterodactyl\Models\Allocation[] $allocations */
$allocation = factory(Allocation::class)->create(['node_id' => $server->node_id, 'server_id' => $server->id]);
/** @var \Pterodactyl\Models\Allocation $allocation */
$allocation = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server->id]);
$this->daemonServerRepository->expects('setServer->update')->andReturnUndefined();
@ -178,8 +178,8 @@ class BuildModificationServiceTest extends IntegrationTestCase
public function testAllocationInBothAddAndRemoveIsAdded()
{
$server = $this->createServerModel();
/** @var \Pterodactyl\Models\Allocation[] $allocations */
$allocation = factory(Allocation::class)->create(['node_id' => $server->node_id]);
/** @var \Pterodactyl\Models\Allocation $allocation */
$allocation = Allocation::factory()->create(['node_id' => $server->node_id]);
$this->daemonServerRepository->expects('setServer->update')->andReturnUndefined();
@ -197,9 +197,10 @@ class BuildModificationServiceTest extends IntegrationTestCase
public function testUsingSameAllocationIdMultipleTimesDoesNotError()
{
$server = $this->createServerModel();
/** @var \Pterodactyl\Models\Allocation[] $allocations */
$allocation = factory(Allocation::class)->create(['node_id' => $server->node_id, 'server_id' => $server->id]);
$allocation2 = factory(Allocation::class)->create(['node_id' => $server->node_id]);
/** @var \Pterodactyl\Models\Allocation $allocation */
$allocation = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server->id]);
/** @var \Pterodactyl\Models\Allocation $allocation2 */
$allocation2 = Allocation::factory()->create(['node_id' => $server->node_id]);
$this->daemonServerRepository->expects('setServer->update')->andReturnUndefined();
@ -219,8 +220,8 @@ class BuildModificationServiceTest extends IntegrationTestCase
public function testThatUpdatesAreRolledBackIfExceptionIsEncountered()
{
$server = $this->createServerModel();
/** @var \Pterodactyl\Models\Allocation[] $allocations */
$allocation = factory(Allocation::class)->create(['node_id' => $server->node_id]);
/** @var \Pterodactyl\Models\Allocation $allocation */
$allocation = Allocation::factory()->create(['node_id' => $server->node_id]);
$this->daemonServerRepository->expects('setServer->update')->andThrows(new DisplayException('Test'));

View file

@ -4,16 +4,16 @@ namespace Pterodactyl\Tests\Integration\Services\Servers;
use Mockery;
use Pterodactyl\Models\Egg;
use GuzzleHttp\Psr7\Request;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\User;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Location;
use Pterodactyl\Models\Allocation;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Validation\ValidationException;
use GuzzleHttp\Exception\BadResponseException;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Models\Objects\DeploymentObject;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Services\Servers\ServerCreationService;
@ -48,15 +48,18 @@ class ServerCreationServiceTest extends IntegrationTestCase
public function testServerIsCreatedWithDeploymentObject()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
/** @var \Pterodactyl\Models\Location $location */
$location = Location::factory()->create();
/** @var \Pterodactyl\Models\Node $node */
$node = factory(Node::class)->create([
'location_id' => factory(Location::class)->create()->id,
$node = Node::factory()->create([
'location_id' => $location->id,
]);
/** @var \Pterodactyl\Models\Allocation[]|\Illuminate\Database\Eloquent\Collection $allocations */
$allocations = factory(Allocation::class)->times(5)->create([
$allocations = Allocation::factory()->times(5)->create([
'node_id' => $node->id,
]);
@ -156,15 +159,18 @@ class ServerCreationServiceTest extends IntegrationTestCase
public function testErrorEncounteredByWingsCausesServerToBeDeleted()
{
/** @var \Pterodactyl\Models\User $user */
$user = factory(User::class)->create();
$user = User::factory()->create();
/** @var \Pterodactyl\Models\Location $location */
$location = Location::factory()->create();
/** @var \Pterodactyl\Models\Node $node */
$node = factory(Node::class)->create([
'location_id' => factory(Location::class)->create()->id,
$node = Node::factory()->create([
'location_id' => $location->id,
]);
/** @var \Pterodactyl\Models\Allocation $allocation */
$allocation = factory(Allocation::class)->create([
$allocation = Allocation::factory()->create([
'node_id' => $node->id,
]);

View file

@ -6,6 +6,7 @@ use Mockery;
use Exception;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Database;
use Pterodactyl\Models\DatabaseHost;
use GuzzleHttp\Exception\BadResponseException;
@ -65,7 +66,7 @@ class ServerDeletionServiceTest extends IntegrationTestCase
$this->expectException(DaemonConnectionException::class);
$this->daemonServerRepository->expects('setServer->delete')->withNoArgs()->andThrows(
new DaemonConnectionException(new BadResponseException('Bad request', new Request('GET', '/test')))
new DaemonConnectionException(new BadResponseException('Bad request', new Request('GET', '/test'), new Response()))
);
$this->getService()->handle($server);
@ -113,17 +114,17 @@ class ServerDeletionServiceTest extends IntegrationTestCase
public function testExceptionWhileDeletingStopsProcess()
{
$server = $this->createServerModel();
$host = factory(DatabaseHost::class)->create();
$host = DatabaseHost::factory()->create();
/** @var \Pterodactyl\Models\Database $db */
$db = factory(Database::class)->create(['database_host_id' => $host->id, 'server_id' => $server->id]);
$db = Database::factory()->create(['database_host_id' => $host->id, 'server_id' => $server->id]);
$server->refresh();
$this->daemonServerRepository->expects('setServer->delete')->withNoArgs()->andReturnUndefined();
$this->databaseManagementService->expects('delete')->with(Mockery::on(function ($value) use ($db) {
return $value instanceof Database && $value->id === $db->id;
}))->andThrows(new Exception);
}))->andThrows(new Exception());
$this->expectException(Exception::class);
$this->getService()->handle($server);
@ -138,17 +139,17 @@ class ServerDeletionServiceTest extends IntegrationTestCase
public function testExceptionWhileDeletingDatabasesDoesNotAbortIfForceDeleted()
{
$server = $this->createServerModel();
$host = factory(DatabaseHost::class)->create();
$host = DatabaseHost::factory()->create();
/** @var \Pterodactyl\Models\Database $db */
$db = factory(Database::class)->create(['database_host_id' => $host->id, 'server_id' => $server->id]);
$db = Database::factory()->create(['database_host_id' => $host->id, 'server_id' => $server->id]);
$server->refresh();
$this->daemonServerRepository->expects('setServer->delete')->withNoArgs()->andReturnUndefined();
$this->databaseManagementService->expects('delete')->with(Mockery::on(function ($value) use ($db) {
return $value instanceof Database && $value->id === $db->id;
}))->andThrows(new Exception);
}))->andThrows(new Exception());
$this->getService()->withForce(true)->handle($server);

View file

@ -3,10 +3,9 @@
namespace Pterodactyl\Tests\Integration\Services\Servers;
use Exception;
use Ramsey\Uuid\Uuid;
use Pterodactyl\Models\Egg;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Nest;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\ServerVariable;
use Illuminate\Validation\ValidationException;

View file

@ -92,7 +92,6 @@ class VariableValidatorServiceTest extends IntegrationTestCase
$this->assertArrayHasKey('environment.BUNGEE_VERSION', $exception->errors());
}
$response = $this->getService()->setUserLevel(User::USER_LEVEL_ADMIN)->handle($egg->id, [
'BUNGEE_VERSION' => '123',
'SERVER_JARFILE' => 'server.jar',

View file

@ -0,0 +1,38 @@
<?php
namespace Pterodactyl\Tests\Integration;
use Illuminate\Testing\Assert as PHPUnit;
use Pterodactyl\Exceptions\DisplayException;
use Illuminate\Validation\ValidationException;
use Illuminate\Testing\TestResponse as IlluminateTestResponse;
class TestResponse extends IlluminateTestResponse
{
/**
* Overrides the default assert status logic to dump out the error to the
* test output if it is caused by a 500 level error and we were not specifically
* look for that status response.
*
* @param int $status
*
* @return \Pterodactyl\Tests\Integration\TestResponse
*/
public function assertStatus($status)
{
$actual = $this->getStatusCode();
// Dump the response to the screen before making the assertion which is going
// to fail so that debugging isn't such a nightmare.
if ($actual !== $status && $status !== 500) {
$this->dump();
if (!is_null($this->exception) && !$this->exception instanceof DisplayException && !$this->exception instanceof ValidationException) {
dump($this->exception);
}
}
PHPUnit::assertSame($actual, $status, "Expected status code {$status} but received {$actual}.");
return $this;
}
}

View file

@ -1,8 +1,9 @@
<?php
namespace Tests;
namespace Pterodactyl\Tests;
use Cake\Chronos\Chronos;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
@ -16,9 +17,12 @@ abstract class TestCase extends BaseTestCase
{
parent::setUp();
Carbon::setTestNow(Carbon::now());
CarbonImmutable::setTestNow(Carbon::now());
// Why, you ask? If we don't force this to false it is possible for certain exceptions
// to show their error message properly in the integration test output, but not actually
// be setup correctly to display thier message in production.
// be setup correctly to display their message in production.
//
// If we expect a message in a test, and it isn't showing up (rather, showing the generic
// "an error occurred" message), we can probably assume that the exception isn't one that
@ -35,7 +39,8 @@ abstract class TestCase extends BaseTestCase
{
parent::tearDown();
Chronos::setTestNow();
Carbon::setTestNow();
CarbonImmutable::setTestNow();
}
/**

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Traits\Http;
namespace Pterodactyl\Tests\Traits\Http;
use Illuminate\Http\Response;
use Illuminate\Testing\TestResponse;
@ -9,8 +9,6 @@ trait IntegrationJsonRequestAssertions
{
/**
* Make assertions about a 404 response on the API.
*
* @param \Illuminate\Testing\TestResponse $response
*/
public function assertNotFoundJson(TestResponse $response)
{
@ -30,8 +28,6 @@ trait IntegrationJsonRequestAssertions
/**
* Make assertions about a 403 error returned by the API.
*
* @param \Illuminate\Testing\TestResponse $response
*/
public function assertAccessDeniedJson(TestResponse $response)
{

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Traits\Http;
namespace Pterodactyl\Tests\Traits\Http;
use Closure;
use Illuminate\Http\Request;

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Traits\Http;
namespace Pterodactyl\Tests\Traits\Http;
use Mockery as m;
use Illuminate\Http\Request;
@ -22,8 +22,6 @@ trait RequestMockHelpers
/**
* Set the class to mock for requests.
*
* @param string $class
*/
public function setRequestMockClass(string $class)
{
@ -34,8 +32,6 @@ trait RequestMockHelpers
/**
* Configure the user model that the request mock should return with.
*
* @param \Pterodactyl\Models\User|null $user
*/
public function setRequestUserModel(User $user = null)
{
@ -44,13 +40,10 @@ trait RequestMockHelpers
/**
* Generates a new request user model and also returns the generated model.
*
* @param array $args
* @return \Pterodactyl\Models\User
*/
public function generateRequestUserModel(array $args = []): User
{
$user = factory(User::class)->make($args);
$user = User::factory()->make($args);
$this->setRequestUserModel($user);
return $user;
@ -59,8 +52,7 @@ trait RequestMockHelpers
/**
* Set a request attribute on the mock object.
*
* @param string $attribute
* @param mixed $value
* @param mixed $value
*/
public function setRequestAttribute(string $attribute, $value)
{
@ -69,8 +61,6 @@ trait RequestMockHelpers
/**
* Set the request route name.
*
* @param string $name
*/
public function setRequestRouteName(string $name)
{
@ -83,7 +73,7 @@ trait RequestMockHelpers
protected function buildRequestMock()
{
$this->request = m::mock($this->requestMockClass);
if (! $this->request instanceof Request) {
if (!$this->request instanceof Request) {
throw new InvalidArgumentException('Request mock class must be an instance of ' . Request::class . ' when mocked.');
}
@ -94,13 +84,11 @@ trait RequestMockHelpers
* Sets the mocked request user. If a user model is not provided, a factory model
* will be created and returned.
*
* @param \Pterodactyl\Models\User|null $user
* @return \Pterodactyl\Models\User
* @deprecated
*/
protected function setRequestUser(User $user = null): User
{
$user = $user instanceof User ? $user : factory(User::class)->make();
$user = $user instanceof User ? $user : User::factory()->make();
$this->request->shouldReceive('user')->withNoArgs()->andReturn($user);
return $user;

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Traits\Integration;
namespace Pterodactyl\Tests\Traits\Integration;
use Ramsey\Uuid\Uuid;
use Pterodactyl\Models\Egg;
@ -10,7 +10,6 @@ use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Location;
use Pterodactyl\Models\Allocation;
use Illuminate\Database\Eloquent\Factory as EloquentFactory;
trait CreatesTestModels
{
@ -21,69 +20,69 @@ trait CreatesTestModels
*
* The returned server model will have all of the relationships loaded onto it.
*
* @param array $attributes
* @return \Pterodactyl\Models\Server
*/
public function createServerModel(array $attributes = []): Server
public function createServerModel(array $attributes = [])
{
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory = $this->app->make(EloquentFactory::class);
if (isset($attributes['user_id'])) {
$attributes['owner_id'] = $attributes['user_id'];
}
if (! isset($attributes['owner_id'])) {
$user = $factory->of(User::class)->create();
if (!isset($attributes['owner_id'])) {
/** @var \Pterodactyl\Models\User $user */
$user = User::factory()->create();
$attributes['owner_id'] = $user->id;
}
if (! isset($attributes['node_id'])) {
if (! isset($attributes['location_id'])) {
$location = $factory->of(Location::class)->create();
if (!isset($attributes['node_id'])) {
if (!isset($attributes['location_id'])) {
/** @var \Pterodactyl\Models\Location $location */
$location = Location::factory()->create();
$attributes['location_id'] = $location->id;
}
$node = $factory->of(Node::class)->create(['location_id' => $attributes['location_id']]);
/** @var \Pterodactyl\Models\Node $node */
$node = Node::factory()->create(['location_id' => $attributes['location_id']]);
$attributes['node_id'] = $node->id;
}
if (! isset($attributes['allocation_id'])) {
$allocation = $factory->of(Allocation::class)->create(['node_id' => $attributes['node_id']]);
if (!isset($attributes['allocation_id'])) {
/** @var \Pterodactyl\Models\Allocation $allocation */
$allocation = Allocation::factory()->create(['node_id' => $attributes['node_id']]);
$attributes['allocation_id'] = $allocation->id;
}
if (! isset($attributes['nest_id'])) {
if (!isset($attributes['nest_id'])) {
/** @var \Pterodactyl\Models\Nest $nest */
$nest = Nest::with('eggs')->first();
$attributes['nest_id'] = $nest->id;
if (! isset($attributes['egg_id'])) {
if (!isset($attributes['egg_id'])) {
$attributes['egg_id'] = $nest->getRelation('eggs')->first()->id;
}
}
if (! isset($attributes['egg_id'])) {
if (!isset($attributes['egg_id'])) {
/** @var \Pterodactyl\Models\Egg $egg */
$egg = Egg::where('nest_id', $attributes['nest_id'])->first();
$attributes['egg_id'] = $egg->id;
}
unset($attributes['user_id'], $attributes['location_id']);
$server = $factory->of(Server::class)->create($attributes);
/** @var \Pterodactyl\Models\Server $server */
$server = Server::factory()->create($attributes);
Allocation::query()->where('id', $server->allocation_id)->update(['server_id' => $server->id]);
return Server::with([
return $server->fresh([
'location', 'user', 'node', 'allocation', 'nest', 'egg',
])->findOrFail($server->id);
]);
}
/**
* Clones a given egg allowing us to make modifications that don't affect other
* tests that rely on the egg existing in the correct state.
*
* @param \Pterodactyl\Models\Egg $egg
* @return \Pterodactyl\Models\Egg
*/
protected function cloneEggAndVariables(Egg $egg): Egg
{

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Traits;
namespace Pterodactyl\Tests\Traits;
use PDO;
use Mockery;
@ -41,7 +41,7 @@ trait MocksPdoConnection
*/
protected function tearDownPdoMock()
{
if (! self::$initialResolver) {
if (!self::$initialResolver) {
return;
}

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Traits;
namespace Pterodactyl\Tests\Traits;
use Mockery;
use Mockery\MockInterface;
@ -22,8 +22,7 @@ trait MocksRequestException
* Configure the exception mock to work with the Panel's default exception
* handler actions.
*
* @param string $abstract
* @param null $response
* @param null $response
*/
protected function configureExceptionMock(string $abstract = RequestException::class, $response = null)
{
@ -32,9 +31,6 @@ trait MocksRequestException
/**
* Return a mocked instance of the request exception.
*
* @param string $abstract
* @return \Mockery\MockInterface
*/
protected function getExceptionMock(string $abstract = RequestException::class): MockInterface
{

View file

@ -7,7 +7,7 @@
* https://opensource.org/licenses/MIT
*/
namespace Tests\Traits;
namespace Pterodactyl\Tests\Traits;
use Mockery as m;
use Ramsey\Uuid\Uuid;
@ -37,8 +37,6 @@ trait MocksUuids
/**
* Returns the known UUID for tests to use.
*
* @return string
*/
public function getKnownUuid(): string
{

View file

@ -1,15 +1,8 @@
<?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\Helpers;
namespace Pterodactyl\Tests\Unit\Helpers;
use Tests\TestCase;
use Pterodactyl\Tests\TestCase;
class IsDigitTest extends TestCase
{

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Unit\Http\Middleware;
namespace Pterodactyl\Tests\Unit\Http\Middleware;
use Pterodactyl\Models\User;
use Pterodactyl\Http\Middleware\AdminAuthenticate;
@ -13,7 +13,7 @@ class AdminAuthenticateTest extends MiddlewareTestCase
*/
public function testAdminsAreAuthenticated()
{
$user = factory(User::class)->make(['root_admin' => 1]);
$user = User::factory()->make(['root_admin' => 1]);
$this->request->shouldReceive('user')->withNoArgs()->twice()->andReturn($user);
@ -39,7 +39,7 @@ class AdminAuthenticateTest extends MiddlewareTestCase
{
$this->expectException(AccessDeniedHttpException::class);
$user = factory(User::class)->make(['root_admin' => 0]);
$user = User::factory()->make(['root_admin' => 0]);
$this->request->shouldReceive('user')->withNoArgs()->twice()->andReturn($user);
@ -48,8 +48,6 @@ class AdminAuthenticateTest extends MiddlewareTestCase
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\AdminAuthenticate
*/
private function getMiddleware(): AdminAuthenticate
{

View file

@ -1,8 +1,8 @@
<?php
namespace Tests\Unit\Http\Middleware\Api\Application;
namespace Pterodactyl\Tests\Unit\Http\Middleware\Api\Application;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Pterodactyl\Http\Middleware\Api\Application\AuthenticateApplicationUser;
@ -44,11 +44,9 @@ class AuthenticateUserTest extends MiddlewareTestCase
/**
* Return an instance of the middleware for testing.
*
* @return \Pterodactyl\Http\Middleware\Api\Application\AuthenticateApplicationUser
*/
private function getMiddleware(): AuthenticateApplicationUser
{
return new AuthenticateApplicationUser;
return new AuthenticateApplicationUser();
}
}

View file

@ -1,10 +1,10 @@
<?php
namespace Tests\Unit\Http\Middleware\Api;
namespace Pterodactyl\Tests\Unit\Http\Middleware\Api;
use Pterodactyl\Models\ApiKey;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Http\Middleware\Api\AuthenticateIPAccess;
use Pterodactyl\Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class AuthenticateIPAccessTest extends MiddlewareTestCase
@ -14,7 +14,7 @@ class AuthenticateIPAccessTest extends MiddlewareTestCase
*/
public function testWithNoIPRestrictions()
{
$model = factory(ApiKey::class)->make(['allowed_ips' => []]);
$model = ApiKey::factory()->make(['allowed_ips' => []]);
$this->setRequestAttribute('api_key', $model);
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
@ -26,7 +26,7 @@ class AuthenticateIPAccessTest extends MiddlewareTestCase
*/
public function testWithValidIP()
{
$model = factory(ApiKey::class)->make(['allowed_ips' => ['127.0.0.1']]);
$model = ApiKey::factory()->make(['allowed_ips' => ['127.0.0.1']]);
$this->setRequestAttribute('api_key', $model);
$this->request->shouldReceive('ip')->withNoArgs()->once()->andReturn('127.0.0.1');
@ -39,7 +39,7 @@ class AuthenticateIPAccessTest extends MiddlewareTestCase
*/
public function testValidIPAgainstCIDRRange()
{
$model = factory(ApiKey::class)->make(['allowed_ips' => ['192.168.1.1/28']]);
$model = ApiKey::factory()->make(['allowed_ips' => ['192.168.1.1/28']]);
$this->setRequestAttribute('api_key', $model);
$this->request->shouldReceive('ip')->withNoArgs()->once()->andReturn('192.168.1.15');
@ -55,7 +55,7 @@ class AuthenticateIPAccessTest extends MiddlewareTestCase
{
$this->expectException(AccessDeniedHttpException::class);
$model = factory(ApiKey::class)->make(['allowed_ips' => ['127.0.0.1']]);
$model = ApiKey::factory()->make(['allowed_ips' => ['127.0.0.1']]);
$this->setRequestAttribute('api_key', $model);
$this->request->shouldReceive('ip')->withNoArgs()->twice()->andReturn('127.0.0.2');
@ -65,8 +65,6 @@ class AuthenticateIPAccessTest extends MiddlewareTestCase
/**
* Return an instance of the middleware to be used when testing.
*
* @return \Pterodactyl\Http\Middleware\Api\AuthenticateIPAccess
*/
private function getMiddleware(): AuthenticateIPAccess
{

View file

@ -1,17 +1,17 @@
<?php
namespace Tests\Unit\Http\Middleware\Api;
namespace Pterodactyl\Tests\Unit\Http\Middleware\Api;
use Mockery as m;
use Cake\Chronos\Chronos;
use Carbon\CarbonImmutable;
use Pterodactyl\Models\User;
use Pterodactyl\Models\ApiKey;
use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\Encryption\Encrypter;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Http\Middleware\Api\AuthenticateKey;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@ -38,7 +38,6 @@ class AuthenticateKeyTest extends MiddlewareTestCase
public function setUp(): void
{
parent::setUp();
Chronos::setTestNow(Chronos::now());
$this->auth = m::mock(AuthManager::class);
$this->encrypter = m::mock(Encrypter::class);
@ -69,7 +68,7 @@ class AuthenticateKeyTest extends MiddlewareTestCase
$this->expectException(AccessDeniedHttpException::class);
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn('abcd1234');
$this->repository->shouldReceive('findFirstWhere')->andThrow(new RecordNotFoundException);
$this->repository->shouldReceive('findFirstWhere')->andThrow(new RecordNotFoundException());
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_APPLICATION);
}
@ -79,7 +78,7 @@ class AuthenticateKeyTest extends MiddlewareTestCase
*/
public function testValidToken()
{
$model = factory(ApiKey::class)->make();
$model = ApiKey::factory()->make();
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'decrypted');
$this->repository->shouldReceive('findFirstWhere')->with([
@ -90,7 +89,7 @@ class AuthenticateKeyTest extends MiddlewareTestCase
$this->auth->shouldReceive('guard->loginUsingId')->with($model->user_id)->once()->andReturnNull();
$this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, [
'last_used_at' => Chronos::now(),
'last_used_at' => CarbonImmutable::now(),
])->once()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_APPLICATION);
@ -102,7 +101,7 @@ class AuthenticateKeyTest extends MiddlewareTestCase
*/
public function testValidTokenWithUserKey()
{
$model = factory(ApiKey::class)->make();
$model = ApiKey::factory()->make();
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'decrypted');
$this->repository->shouldReceive('findFirstWhere')->with([
@ -113,7 +112,7 @@ class AuthenticateKeyTest extends MiddlewareTestCase
$this->auth->shouldReceive('guard->loginUsingId')->with($model->user_id)->once()->andReturnNull();
$this->repository->shouldReceive('withoutFreshModel->update')->with($model->id, [
'last_used_at' => Chronos::now(),
'last_used_at' => CarbonImmutable::now(),
])->once()->andReturnNull();
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions(), ApiKey::TYPE_ACCOUNT);
@ -126,7 +125,7 @@ class AuthenticateKeyTest extends MiddlewareTestCase
*/
public function testAccessWithoutToken()
{
$user = factory(User::class)->make(['id' => 123]);
$user = User::factory()->make(['id' => 123]);
$this->request->shouldReceive('user')->andReturn($user);
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturnNull();
@ -147,7 +146,7 @@ class AuthenticateKeyTest extends MiddlewareTestCase
{
$this->expectException(AccessDeniedHttpException::class);
$model = factory(ApiKey::class)->make();
$model = ApiKey::factory()->make();
$this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'asdf');
$this->repository->shouldReceive('findFirstWhere')->with([
@ -161,8 +160,6 @@ class AuthenticateKeyTest extends MiddlewareTestCase
/**
* Return an instance of the middleware with mocked dependencies for testing.
*
* @return \Pterodactyl\Http\Middleware\Api\AuthenticateKey
*/
private function getMiddleware(): AuthenticateKey
{

View file

@ -1,15 +1,15 @@
<?php
namespace Tests\Unit\Http\Middleware\Api\Daemon;
namespace Pterodactyl\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\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Http\Middleware\Api\Daemon\DaemonAuthenticate;
use Pterodactyl\Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@ -70,7 +70,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
* Test that passing in an invalid node daemon secret will result in a bad request
* exception being returned.
*
* @param string $token
* @dataProvider badTokenDataProvider
*/
public function testResponseShouldFailIfTokenFormatIsIncorrect(string $token)
@ -92,7 +91,7 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
$this->expectException(AccessDeniedHttpException::class);
/** @var \Pterodactyl\Models\Node $model */
$model = factory(Node::class)->make();
$model = Node::factory()->make();
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn($model->daemon_token_id . '.random_string_123');
@ -125,7 +124,7 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
public function testSuccessfulMiddlewareProcess()
{
/** @var \Pterodactyl\Models\Node $model */
$model = factory(Node::class)->make();
$model = Node::factory()->make();
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn($model->daemon_token_id . '.' . decrypt($model->daemon_token));
@ -159,8 +158,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\Api\Daemon\DaemonAuthenticate
*/
private function getMiddleware(): DaemonAuthenticate
{

View file

@ -1,11 +1,11 @@
<?php
namespace Tests\Unit\Http\Middleware\Api;
namespace Pterodactyl\Tests\Unit\Http\Middleware\Api;
use Mockery as m;
use Illuminate\Contracts\Config\Repository;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Http\Middleware\Api\SetSessionDriver;
use Pterodactyl\Tests\Unit\Http\Middleware\MiddlewareTestCase;
class SetSessionDriverTest extends MiddlewareTestCase
{
@ -36,8 +36,6 @@ class SetSessionDriverTest extends MiddlewareTestCase
/**
* Return an instance of the middleware with mocked dependencies for testing.
*
* @return \Pterodactyl\Http\Middleware\Api\SetSessionDriver
*/
private function getMiddleware(): SetSessionDriver
{

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Unit\Http\Middleware;
namespace Pterodactyl\Tests\Unit\Http\Middleware;
use Illuminate\Auth\AuthenticationException;
use Pterodactyl\Http\Middleware\Authenticate;
@ -31,8 +31,6 @@ class AuthenticateTest extends MiddlewareTestCase
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\Authenticate
*/
private function getMiddleware(): Authenticate
{

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Unit\Http\Middleware;
namespace Pterodactyl\Tests\Unit\Http\Middleware;
use Mockery as m;
use Pterodactyl\Models\User;
@ -40,7 +40,7 @@ class LanguageMiddlewareTest extends MiddlewareTestCase
*/
public function testLanguageIsSetWithAuthenticatedUser()
{
$user = factory(User::class)->make(['language' => 'de']);
$user = User::factory()->make(['language' => 'de']);
$this->request->shouldReceive('user')->withNoArgs()->andReturn($user);
$this->appMock->shouldReceive('setLocale')->with('de')->once()->andReturnNull();
@ -50,8 +50,6 @@ class LanguageMiddlewareTest extends MiddlewareTestCase
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\LanguageMiddleware
*/
private function getMiddleware(): LanguageMiddleware
{

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Unit\Http\Middleware;
namespace Pterodactyl\Tests\Unit\Http\Middleware;
use Mockery as m;
use Pterodactyl\Models\Node;
@ -31,8 +31,8 @@ class MaintenanceMiddlewareTest extends MiddlewareTestCase
*/
public function testHandle()
{
$server = factory(Server::class)->make();
$node = factory(Node::class)->make(['maintenance' => 0]);
$server = Server::factory()->make();
$node = Node::factory()->make(['maintenance' => 0]);
$server->setRelation('node', $node);
$this->setRequestAttribute('server', $server);
@ -45,8 +45,8 @@ class MaintenanceMiddlewareTest extends MiddlewareTestCase
*/
public function testHandleInMaintenanceMode()
{
$server = factory(Server::class)->make();
$node = factory(Node::class)->make(['maintenance_mode' => 1]);
$server = Server::factory()->make();
$node = Node::factory()->make(['maintenance_mode' => 1]);
$server->setRelation('node', $node);
$this->setRequestAttribute('server', $server);
@ -54,15 +54,12 @@ class MaintenanceMiddlewareTest extends MiddlewareTestCase
$this->response->shouldReceive('view')
->once()
->with('errors.maintenance')
->andReturn(new Response);
->andReturn(new Response());
$response = $this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertInstanceOf(Response::class, $response);
}
/**
* @return \Pterodactyl\Http\Middleware\MaintenanceMiddleware
*/
private function getMiddleware(): MaintenanceMiddleware
{
return new MaintenanceMiddleware($this->response);

View file

@ -1,15 +1,17 @@
<?php
namespace Tests\Unit\Http\Middleware;
namespace Pterodactyl\Tests\Unit\Http\Middleware;
use Tests\TestCase;
use Tests\Traits\Http\RequestMockHelpers;
use Tests\Traits\Http\MocksMiddlewareClosure;
use Tests\Assertions\MiddlewareAttributeAssertionsTrait;
use Pterodactyl\Tests\TestCase;
use Pterodactyl\Tests\Traits\Http\RequestMockHelpers;
use Pterodactyl\Tests\Traits\Http\MocksMiddlewareClosure;
use Pterodactyl\Tests\Assertions\MiddlewareAttributeAssertionsTrait;
abstract class MiddlewareTestCase extends TestCase
{
use MiddlewareAttributeAssertionsTrait, MocksMiddlewareClosure, RequestMockHelpers;
use MiddlewareAttributeAssertionsTrait;
use MocksMiddlewareClosure;
use RequestMockHelpers;
/**
* Setup tests with a mocked request object and normal attributes.

View file

@ -1,6 +1,6 @@
<?php
namespace Tests\Unit\Http\Middleware;
namespace Pterodactyl\Tests\Unit\Http\Middleware;
use Mockery as m;
use Illuminate\Auth\AuthManager;
@ -50,8 +50,6 @@ class RedirectIfAuthenticatedTest extends MiddlewareTestCase
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\RedirectIfAuthenticated
*/
private function getMiddleware(): RedirectIfAuthenticated
{

View file

@ -1,13 +1,13 @@
<?php
namespace Tests\Unit\Http\Middleware\Server;
namespace Pterodactyl\Tests\Unit\Http\Middleware\Server;
use Mockery as m;
use Pterodactyl\Models\Server;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\Routing\ResponseFactory;
use Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Http\Middleware\Server\AccessingValidServer;
use Pterodactyl\Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@ -49,7 +49,7 @@ class AccessingValidServerTest extends MiddlewareTestCase
$this->expectException(AccessDeniedHttpException::class);
$this->expectExceptionMessage('Server is suspended and cannot be accessed.');
$model = factory(Server::class)->make(['status' => Server::STATUS_SUSPENDED]);
$model = Server::factory()->make(['suspended' => 1]);
$this->request->shouldReceive('route->parameter')->with('server')->once()->andReturn('123456');
$this->request->shouldReceive('expectsJson')->withNoArgs()->once()->andReturn(true);
@ -67,7 +67,7 @@ class AccessingValidServerTest extends MiddlewareTestCase
$this->expectException(ConflictHttpException::class);
$this->expectExceptionMessage('Server is still completing the installation process.');
$model = factory(Server::class)->make(['status' => Server::STATUS_INSTALLING]);
$model = Server::factory()->make(['installed' => 0]);
$this->request->shouldReceive('route->parameter')->with('server')->once()->andReturn('123456');
$this->request->shouldReceive('expectsJson')->withNoArgs()->once()->andReturn(true);
@ -101,7 +101,7 @@ class AccessingValidServerTest extends MiddlewareTestCase
*/
public function testValidServerProcess()
{
$model = factory(Server::class)->make();
$model = Server::factory()->make();
$this->request->shouldReceive('route->parameter')->with('server')->once()->andReturn('123456');
$this->request->shouldReceive('expectsJson')->withNoArgs()->once()->andReturn(false);
@ -117,8 +117,6 @@ class AccessingValidServerTest extends MiddlewareTestCase
/**
* Provide test data that checks that the correct view is returned for each model type.
*
* @return array
*/
public function viewDataProvider(): array
{
@ -126,16 +124,14 @@ class AccessingValidServerTest extends MiddlewareTestCase
$this->refreshApplication();
return [
[factory(Server::class)->make(['status' => Server::STATUS_SUSPENDED]), 'errors.suspended', 403],
[factory(Server::class)->make(['status' => Server::STATUS_INSTALLING]), 'errors.installing', 409],
[factory(Server::class)->make(['status' => Server::STATUS_INSTALL_FAILED]), 'errors.installing', 409],
[Server::factory()->make(['suspended' => 1]), 'errors.suspended', 403],
[Server::factory()->make(['installed' => 0]), 'errors.installing', 409],
[Server::factory()->make(['installed' => 2]), 'errors.installing', 409],
];
}
/**
* Return an instance of the middleware using mocked dependencies.
*
* @return \Pterodactyl\Http\Middleware\Server\AccessingValidServer
*/
private function getMiddleware(): AccessingValidServer
{

View file

@ -1,9 +1,9 @@
<?php
namespace Tests\Unit\Rules;
namespace Pterodactyl\Tests\Unit\Rules;
use Tests\TestCase;
use Pterodactyl\Rules\Username;
use Pterodactyl\Tests\TestCase;
class UsernameTest extends TestCase
{
@ -12,7 +12,7 @@ class UsernameTest extends TestCase
*/
public function testRuleIsStringable()
{
$this->assertSame('p_username', (string) new Username);
$this->assertSame('p_username', (string) new Username());
}
/**
@ -22,7 +22,7 @@ class UsernameTest extends TestCase
*/
public function testValidUsernames(string $username)
{
$this->assertTrue((new Username)->passes('test', $username), 'Assert username is valid.');
$this->assertTrue((new Username())->passes('test', $username), 'Assert username is valid.');
}
/**
@ -32,12 +32,11 @@ class UsernameTest extends TestCase
*/
public function testInvalidUsernames(string $username)
{
$this->assertFalse((new Username)->passes('test', $username), 'Assert username is not valid.');
$this->assertFalse((new Username())->passes('test', $username), 'Assert username is not valid.');
}
/**
* Provide valid usernames.
* @return array
*/
public function validUsernameDataProvider(): array
{
@ -54,8 +53,6 @@ class UsernameTest extends TestCase
/**
* Provide invalid usernames.
*
* @return array
*/
public function invalidUsernameDataProvider(): array
{

View file

@ -1,9 +1,9 @@
<?php
namespace Tests\Unit\Services\Acl\Api;
namespace Pterodactyl\Tests\Unit\Services\Acl\Api;
use Tests\TestCase;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Tests\TestCase;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class AdminAclTest extends TestCase
@ -23,15 +23,13 @@ class AdminAclTest extends TestCase
*/
public function testCheck()
{
$model = factory(ApiKey::class)->make(['r_servers' => AdminAcl::READ | AdminAcl::WRITE]);
$model = ApiKey::factory()->make(['r_servers' => AdminAcl::READ | AdminAcl::WRITE]);
$this->assertTrue(AdminAcl::check($model, AdminAcl::RESOURCE_SERVERS, AdminAcl::WRITE));
}
/**
* Provide valid and invalid permissions combos for testing.
*
* @return array
*/
public function permissionsDataProvider(): array
{

View file

@ -1,11 +1,11 @@
<?php
namespace Tests\Unit\Services\Api;
namespace Pterodactyl\Tests\Unit\Services\Api;
use Mockery as m;
use Tests\TestCase;
use phpmock\phpunit\PHPMock;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Tests\TestCase;
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Services\Api\KeyCreationService;
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
@ -40,7 +40,7 @@ class KeyCreationServiceTest extends TestCase
*/
public function testKeyIsCreated()
{
$model = factory(ApiKey::class)->make();
$model = ApiKey::factory()->make();
$this->getFunctionMock('\\Pterodactyl\\Services\\Api', 'str_random')
->expects($this->exactly(2))->willReturnCallback(function ($length) {
@ -68,7 +68,7 @@ class KeyCreationServiceTest extends TestCase
*/
public function testIdentifierAndTokenAreOnlySetByFunction()
{
$model = factory(ApiKey::class)->make();
$model = ApiKey::factory()->make();
$this->getFunctionMock('\\Pterodactyl\\Services\\Api', 'str_random')
->expects($this->exactly(2))->willReturnCallback(function ($length) {
@ -95,7 +95,7 @@ class KeyCreationServiceTest extends TestCase
*/
public function testPermissionsAreRetrievedForApplicationKeys()
{
$model = factory(ApiKey::class)->make();
$model = ApiKey::factory()->make();
$this->getFunctionMock('\\Pterodactyl\\Services\\Api', 'str_random')
->expects($this->exactly(2))->willReturnCallback(function ($length) {
@ -125,7 +125,7 @@ class KeyCreationServiceTest extends TestCase
*/
public function testPermissionsAreNotRetrievedForNonApplicationKeys($keyType)
{
$model = factory(ApiKey::class)->make();
$model = ApiKey::factory()->make();
$this->getFunctionMock('\\Pterodactyl\\Services\\Api', 'str_random')
->expects($this->exactly(2))->willReturnCallback(function ($length) {
@ -149,8 +149,6 @@ class KeyCreationServiceTest extends TestCase
/**
* Provide key types that are not an application specific key.
*
* @return array
*/
public function keyTypeDataProvider(): array
{
@ -161,8 +159,6 @@ class KeyCreationServiceTest extends TestCase
/**
* Return an instance of the service with mocked dependencies for testing.
*
* @return \Pterodactyl\Services\Api\KeyCreationService
*/
private function getService(): KeyCreationService
{