1
1
mirror of https://github.com/pterodactyl/panel.git synced 2024-11-26 02:52:30 +01:00

Implement Panel changes to support internal SFTP subsystem on Daemon (#703)

This commit is contained in:
Dane Everitt 2017-10-25 00:35:25 -04:00 committed by GitHub
parent 57db949a9c
commit 058e490ec4
23 changed files with 484 additions and 247 deletions

View File

@ -0,0 +1,85 @@
<?php
namespace Pterodactyl\Http\Controllers\API\Remote;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Auth\AuthenticationException;
use Pterodactyl\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Services\Sftp\AuthenticateUsingPasswordService;
use Pterodactyl\Http\Requests\API\Remote\SftpAuthenticationFormRequest;
class SftpController extends Controller
{
use ThrottlesLogins;
/**
* @var \Pterodactyl\Services\Sftp\AuthenticateUsingPasswordService
*/
private $authenticationService;
/**
* SftpController constructor.
*
* @param \Pterodactyl\Services\Sftp\AuthenticateUsingPasswordService $authenticationService
*/
public function __construct(AuthenticateUsingPasswordService $authenticationService)
{
$this->authenticationService = $authenticationService;
}
/**
* Authenticate a set of credentials and return the associated server details
* for a SFTP connection on the daemon.
*
* @param \Pterodactyl\Http\Requests\API\Remote\SftpAuthenticationFormRequest $request
* @return \Illuminate\Http\JsonResponse
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/
public function index(SftpAuthenticationFormRequest $request): JsonResponse
{
$connection = explode('.', $request->input('username'));
$this->incrementLoginAttempts($request);
if ($this->hasTooManyLoginAttempts($request)) {
return response()->json([
'error' => 'Logins throttled.',
], 429);
}
try {
$data = $this->authenticationService->handle(
array_get($connection, 0),
$request->input('password'),
object_get($request->attributes->get('node'), 'id', 0),
array_get($connection, 1)
);
$this->clearLoginAttempts($request);
} catch (AuthenticationException $exception) {
return response()->json([
'error' => 'Invalid credentials.',
], 403);
} catch (RecordNotFoundException $exception) {
return response()->json([
'error' => 'Invalid server.',
], 404);
}
return response()->json($data);
}
/**
* Get the throttle key for the given request.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function throttleKey(Request $request)
{
return strtolower(array_get(explode('.', $request->input('username')), 0) . '|' . $request->ip());
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace Pterodactyl\Http\Controllers\Server\Settings;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Traits\Controllers\JavascriptInjection;
class SftpController extends Controller
{
use JavascriptInjection;
/**
* Render the server SFTP settings page.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\View
*/
public function index(Request $request): View
{
$this->setRequest($request)->injectJavascript();
return view('server.settings.sftp');
}
}

View File

@ -75,7 +75,7 @@ class DaemonAuthenticate
throw new HttpException(403);
}
$request->attributes->set('node.model', $node);
$request->attributes->set('node', $node);
return $next($request);
}

View File

@ -0,0 +1,44 @@
<?php
namespace Pterodactyl\Http\Requests\API\Remote;
use Pterodactyl\Http\Requests\Request;
class SftpAuthenticationFormRequest extends Request
{
/**
* Authenticate the request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Rules to apply to the request.
*
* @return array
*/
public function rules()
{
return [
'username' => 'required|string',
'password' => 'required|string',
];
}
/**
* Return only the fields that we are interested in from the request.
* This will include empty fields as a null value.
*
* @return array
*/
public function normalize()
{
return $this->only(
array_keys($this->rules())
);
}
}

View File

@ -144,13 +144,23 @@ class Node extends Model implements CleansAttributes, ValidableContract
],
],
'docker' => [
'container' => [
'user' => null,
],
'network' => [
'name' => 'pterodactyl_nw',
],
'socket' => '/var/run/docker.sock',
'autoupdate_images' => true,
],
'sftp' => [
'path' => $this->daemonBase,
'ip' => '0.0.0.0',
'port' => $this->daemonSFTP,
'container' => 'ptdl-sftp',
'keypair' => [
'bits' => 2048,
'e' => 65537,
],
],
'logger' => [
'path' => 'logs/',

View File

@ -29,19 +29,12 @@ class Server extends Model implements CleansAttributes, ValidableContract
*/
protected $table = 'servers';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['sftp_password'];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
protected $dates = [self::CREATED_AT, self::UPDATED_AT, 'deleted_at'];
/**
* Always eager load these relationships on the model.
@ -55,7 +48,7 @@ class Server extends Model implements CleansAttributes, ValidableContract
*
* @var array
*/
protected $guarded = ['id', 'installed', 'created_at', 'updated_at', 'deleted_at'];
protected $guarded = ['id', 'installed', self::CREATED_AT, self::UPDATED_AT, 'deleted_at'];
/**
* @var array
@ -73,8 +66,6 @@ class Server extends Model implements CleansAttributes, ValidableContract
'node_id' => 'required',
'allocation_id' => 'required',
'pack_id' => 'sometimes',
'auto_deploy' => 'sometimes',
'custom_id' => 'sometimes',
'skip_scripts' => 'sometimes',
];
@ -95,10 +86,7 @@ class Server extends Model implements CleansAttributes, ValidableContract
'nest_id' => 'exists:nests,id',
'egg_id' => 'exists:eggs,id',
'pack_id' => 'nullable|numeric|min:0',
'custom_container' => 'nullable|string',
'startup' => 'nullable|string',
'auto_deploy' => 'accepted',
'custom_id' => 'numeric|unique:servers,id',
'skip_scripts' => 'boolean',
];
@ -132,7 +120,6 @@ class Server extends Model implements CleansAttributes, ValidableContract
*/
protected $searchableColumns = [
'name' => 10,
'username' => 10,
'uuidShort' => 9,
'uuid' => 8,
'pack.name' => 7,

View File

@ -63,11 +63,6 @@ class ServerCreationService
*/
protected $userRepository;
/**
* @var \Pterodactyl\Services\Servers\UsernameGenerationService
*/
protected $usernameService;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService
*/
@ -84,7 +79,6 @@ class ServerCreationService
* @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $repository
* @param \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface $serverVariableRepository
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $userRepository
* @param \Pterodactyl\Services\Servers\UsernameGenerationService $usernameService
* @param \Pterodactyl\Services\Servers\VariableValidatorService $validatorService
*/
public function __construct(
@ -96,7 +90,6 @@ class ServerCreationService
ServerRepositoryInterface $repository,
ServerVariableRepositoryInterface $serverVariableRepository,
UserRepositoryInterface $userRepository,
UsernameGenerationService $usernameService,
VariableValidatorService $validatorService
) {
$this->allocationRepository = $allocationRepository;
@ -107,7 +100,6 @@ class ServerCreationService
$this->repository = $repository;
$this->serverVariableRepository = $serverVariableRepository;
$this->userRepository = $userRepository;
$this->usernameService = $usernameService;
$this->validatorService = $validatorService;
}
@ -151,8 +143,6 @@ class ServerCreationService
'startup' => $data['startup'],
'daemonSecret' => str_random(NodeCreationService::DAEMON_SECRET_LENGTH),
'image' => $data['docker_image'],
'username' => $this->usernameService->generate($data['name'], $uniqueShort),
'sftp_password' => null,
]);
// Process allocations and assign them to the server in the database.

View File

@ -1,40 +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 Pterodactyl\Services\Servers;
class UsernameGenerationService
{
/**
* Generate a unique username to be used for SFTP connections and identification
* of the server docker container on the host system.
*
* @param string $name
* @param null $identifier
* @return string
*/
public function generate($name, $identifier = null)
{
if (is_null($identifier) || ! ctype_alnum($identifier)) {
$unique = str_random(8);
} else {
if (strlen($identifier) < 8) {
$unique = $identifier . str_random((8 - strlen($identifier)));
} else {
$unique = substr($identifier, 0, 8);
}
}
// Filter the Server Name
$name = trim(preg_replace('/[^A-Za-z0-9]+/', '', $name), '_');
$name = (strlen($name) < 1) ? str_random(6) : $name;
return strtolower(substr($name, 0, 6) . '_' . $unique);
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace Pterodactyl\Services\Sftp;
use Illuminate\Auth\AuthenticationException;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
class AuthenticateUsingPasswordService
{
/**
* @var \Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService
*/
private $keyProviderService;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
private $repository;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
*/
private $userRepository;
/**
* AuthenticateUsingPasswordService constructor.
*
* @param \Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService $keyProviderService
* @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $repository
* @param \Pterodactyl\Contracts\Repository\UserRepositoryInterface $userRepository
*/
public function __construct(
DaemonKeyProviderService $keyProviderService,
ServerRepositoryInterface $repository,
UserRepositoryInterface $userRepository
) {
$this->keyProviderService = $keyProviderService;
$this->repository = $repository;
$this->userRepository = $userRepository;
}
/**
* Attempt to authenticate a provded username and password and determine if they
* have permission to access a given server. This function does not account for
* subusers currently. Only administrators and server owners can login to access
* their files at this time.
*
* Server must exist on the node that the API call is being made from in order for a
* valid response to be provided.
*
* @param string $username
* @param string $password
* @param string|null $server
* @param int $node
* @return array
*
* @throws \Illuminate\Auth\AuthenticationException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function handle(string $username, string $password, int $node, string $server = null): array
{
if (is_null($server)) {
throw new RecordNotFoundException;
}
try {
$user = $this->userRepository->withColumns(['id', 'root_admin', 'password'])->findFirstWhere([['username', '=', $username]]);
if (! password_verify($password, $user->password)) {
throw new AuthenticationException;
}
} catch (RecordNotFoundException $exception) {
throw new AuthenticationException;
}
$server = $this->repository->withColumns(['id', 'node_id', 'owner_id', 'uuid'])->getByUuid($server);
if ($server->node_id !== $node || (! $user->root_admin && $server->owner_id !== $user->id)) {
throw new RecordNotFoundException;
}
return [
'server' => $server->uuid,
'token' => $this->keyProviderService->handle($server->id, $user->id),
];
}
}

View File

@ -50,7 +50,6 @@ trait JavascriptInjection
'uuid' => $server->uuid,
'uuidShort' => $server->uuidShort,
'daemonSecret' => $token,
'username' => $server->username,
],
'node' => [
'fqdn' => $server->node->fqdn,

View File

@ -30,8 +30,6 @@ $factory->define(Pterodactyl\Models\Server::class, function (Faker\Generator $fa
'cpu' => 0,
'oom_disabled' => 0,
'pack_id' => null,
'username' => $faker->userName,
'sftp_password' => null,
'installed' => 1,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class RemoveLegacySFTPInformation extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::table('servers', function (Blueprint $table) {
$table->dropUnique(['username']);
$table->dropColumn('username');
$table->dropColumn('sftp_password');
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::table('servers', function (Blueprint $table) {
$table->string('username')->nullable()->after('image')->unique();
$table->text('sftp_password')->after('image');
});
}
}

View File

@ -301,7 +301,7 @@ return [
'change_pass' => 'Change SFTP Password',
'details' => 'SFTP Details',
'conn_addr' => 'Connection Address',
'warning' => 'Ensure that your client is set to use SFTP and not FTP or FTPS for connections, there is a difference between the protocols.',
'warning' => 'The SFTP password is your account password. Ensure that your client is set to use SFTP and not FTP or FTPS for connections, there is a difference between the protocols.',
],
'database' => [
'header' => 'Databases',

View File

@ -42,7 +42,6 @@
<th>ID</th>
<th>Server Name</th>
<th>Owner</th>
<th>Username</th>
<th>Node</th>
<th>Connection</th>
<th></th>
@ -52,7 +51,6 @@
<td><code>{{ $server->uuidShort }}</code></td>
<td><a href="{{ route('admin.servers.view', $server->id) }}">{{ $server->name }}</a></td>
<td><a href="{{ route('admin.users.view', $server->user->id) }}">{{ $server->user->username }}</a></td>
<td>{{ $server->username }}</td>
<td><a href="{{ route('admin.nodes.view', $server->node->id) }}">{{ $server->node->name }}</a></td>
<td>
<code>{{ $server->allocation->alias }}:{{ $server->allocation->port }}</code>

View File

@ -55,14 +55,6 @@
<td>Docker Container ID</td>
<td data-attr="container-id"><i class="fa fa-fw fa-refresh fa-spin"></i></td>
</tr>
<tr>
<td>Docker User ID</td>
<td data-attr="container-user"><i class="fa fa-fw fa-refresh fa-spin"></i></td>
</tr>
<tr>
<td>Docker Container Name</td>
<td>{{ $server->username }}</td>
</tr>
<tr>
<td>Service</td>
<td>

View File

@ -16,7 +16,7 @@
<div id="terminal" style="width:100%;max-height: none !important;"></div>
<div id="terminal_input" class="form-group no-margin">
<div class="input-group">
<div class="input-group-addon terminal_input--prompt">{{ $server->username }}:~$</div>
<div class="input-group-addon terminal_input--prompt">container:~/$</div>
<input type="text" class="form-control terminal_input--input">
</div>
</div>

View File

@ -30,7 +30,7 @@
<div id="terminal" style="width:100%;"></div>
<div id="terminal_input" class="form-group no-margin">
<div class="input-group">
<div class="input-group-addon terminal_input--prompt">{{ $server->username }}:~$</div>
<div class="input-group-addon terminal_input--prompt">container:~/$</div>
<input type="text" class="form-control terminal_input--input">
</div>
</div>

View File

@ -21,37 +21,7 @@
@section('content')
<div class="row">
<div class="col-sm-6">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">@lang('server.config.sftp.change_pass')</h3>
</div>
@can('reset-sftp', $server)
<form action="{{ route('server.settings.sftp', $server->uuidShort) }}" method="post">
<div class="box-body">
<div class="form-group">
<label for="sftp_pass" class="control-label">@lang('base.account.new_password')</label>
<div>
<input type="password" class="form-control" name="sftp_pass" />
<p class="text-muted"><small>@lang('auth.password_requirements')</small></p>
</div>
</div>
</div>
<div class="box-footer">
{!! csrf_field() !!}
<input type="submit" class="btn btn-primary btn-sm" value="@lang('base.account.update_pass')" />
</div>
</form>
@else
<div class="box-body">
<div class="callout callout-warning callout-nomargin">
<p>@lang('auth.not_authorized')</p>
</div>
</div>
@endcan
</div>
</div>
<div class="col-sm-6">
<div class="col-xs-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">@lang('server.config.sftp.details')</h3>
@ -66,20 +36,12 @@
<div class="form-group">
<label for="password" class="control-label">@lang('strings.username')</label>
<div>
<input type="text" class="form-control" readonly value="{{ $server->username }}" />
<input type="text" class="form-control" readonly value="{{ auth()->user()->username }}.{{ $server->uuidShort }}" />
</div>
</div>
@can('view-sftp-password', $server)
<div class="form-group">
<label for="password" class="control-label">@lang('base.account.current_password')</label>
<div>
<input type="text" class="form-control" readonly @if(! is_null($server->sftp_password))value="{{ Crypt::decrypt($server->sftp_password) }}"@endif />
</div>
</div>
@endcan
</div>
<div class="box-footer">
<p class="small text-muted">@lang('server.config.sftp.warning')</p>
<p class="small text-muted no-margin-bottom">@lang('server.config.sftp.warning')</p>
</div>
</div>
</div>

View File

@ -12,3 +12,7 @@ Route::group(['prefix' => '/eggs'], function () {
Route::get('/', 'EggRetrievalController@index')->name('api.remote.eggs');
Route::get('/{uuid}', 'EggRetrievalController@download')->name('api.remote.eggs.download');
});
Route::group(['prefix' => '/sftp'], function () {
Route::post('/', 'SftpController@index')->name('api.remote.sftp');
});

View File

@ -21,10 +21,9 @@ Route::group(['prefix' => 'settings'], function () {
Route::get('/allocation', 'Settings\AllocationController@index')->name('server.settings.allocation');
Route::patch('/allocation', 'Settings\AllocationController@update');
Route::get('/sftp', 'ServerController@getSFTP')->name('server.settings.sftp');
Route::get('/startup', 'ServerController@getStartup')->name('server.settings.startup');
Route::get('/sftp', 'Settings\SftpController@index')->name('server.settings.sftp');
Route::post('/sftp', 'ServerController@postSettingsSFTP');
Route::get('/startup', 'ServerController@getStartup')->name('server.settings.startup');
Route::post('/startup', 'ServerController@postSettingsStartup');
});

View File

@ -18,7 +18,6 @@ use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Exceptions\PterodactylException;
use Pterodactyl\Services\Servers\ServerCreationService;
use Pterodactyl\Services\Servers\VariableValidatorService;
use Pterodactyl\Services\Servers\UsernameGenerationService;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
@ -109,11 +108,6 @@ class ServerCreationServiceTest extends TestCase
*/
protected $userRepository;
/**
* @var \Pterodactyl\Services\Servers\UsernameGenerationService|\Mockery\Mock
*/
protected $usernameService;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService|\Mockery\Mock
*/
@ -135,7 +129,6 @@ class ServerCreationServiceTest extends TestCase
$this->repository = m::mock(ServerRepositoryInterface::class);
$this->serverVariableRepository = m::mock(ServerVariableRepositoryInterface::class);
$this->userRepository = m::mock(UserRepositoryInterface::class);
$this->usernameService = m::mock(UsernameGenerationService::class);
$this->validatorService = m::mock(VariableValidatorService::class);
$this->getFunctionMock('\\Pterodactyl\\Services\\Servers', 'str_random')
@ -150,7 +143,6 @@ class ServerCreationServiceTest extends TestCase
$this->repository,
$this->serverVariableRepository,
$this->userRepository,
$this->usernameService,
$this->validatorService
);
}
@ -165,8 +157,6 @@ class ServerCreationServiceTest extends TestCase
->shouldReceive('validate')->with($this->data['egg_id'])->once()->andReturnSelf();
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->usernameService->shouldReceive('generate')->with($this->data['name'], 'random_string')
->once()->andReturn('user_name');
$this->repository->shouldReceive('create')->with(m::subset([
'uuid' => $this->getKnownUuid(),
@ -211,7 +201,6 @@ class ServerCreationServiceTest extends TestCase
{
$this->validatorService->shouldReceive('isAdmin->setFields->validate->getResults')->once()->andReturn([]);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->usernameService->shouldReceive('generate')->once()->andReturn('user_name');
$this->repository->shouldReceive('create')->once()->andReturn((object) [
'node_id' => 1,
'id' => 1,

View File

@ -1,109 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Tests\Unit\Services\Servers;
use Tests\TestCase;
use phpmock\phpunit\PHPMock;
use Pterodactyl\Services\Servers\UsernameGenerationService;
class UsernameGenerationServiceTest extends TestCase
{
use PHPMock;
/**
* @var UsernameGenerationService
*/
protected $service;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->service = new UsernameGenerationService();
$this->getFunctionMock('\\Pterodactyl\\Services\\Servers', 'str_random')
->expects($this->any())->willReturnCallback(function ($count) {
return str_pad('', $count, '0');
});
}
/**
* Test that a valid username is returned and is the correct length.
*/
public function testShouldReturnAValidUsernameWithASelfGeneratedIdentifier()
{
$response = $this->service->generate('testname');
$this->assertEquals('testna_00000000', $response);
}
/**
* Test that a name and identifier provided returns the expected username.
*/
public function testShouldReturnAValidUsernameWithAnIdentifierProvided()
{
$response = $this->service->generate('testname', 'identifier');
$this->assertEquals('testna_identifi', $response);
}
/**
* Test that the identifier is extended to 8 characters if it is shorter.
*/
public function testShouldExtendIdentifierToBe8CharactersIfItIsShorter()
{
$response = $this->service->generate('testname', 'xyz');
$this->assertEquals('testna_xyz00000', $response);
}
/**
* Test that special characters are removed from the username.
*/
public function testShouldStripSpecialCharactersFromName()
{
$response = $this->service->generate('te!st_n$ame', 'identifier');
$this->assertEquals('testna_identifi', $response);
}
/**
* Test that an empty name is replaced with 6 random characters.
*/
public function testEmptyNamesShouldBeReplacedWithRandomCharacters()
{
$response = $this->service->generate('');
$this->assertEquals('000000_00000000', $response);
}
/**
* Test that a name consisting entirely of special characters is handled.
*/
public function testNameOfOnlySpecialCharactersIsHandledProperly()
{
$response = $this->service->generate('$%#*#(@#(#*$&#(#!#@');
$this->assertEquals('000000_00000000', $response);
}
/**
* Test that passing a name shorter than 6 characters returns the entire name.
*/
public function testNameShorterThan6CharactersShouldBeRenderedEntirely()
{
$response = $this->service->generate('test', 'identifier');
$this->assertEquals('test_identifi', $response);
}
}

View File

@ -0,0 +1,181 @@
<?php
namespace Tests\Unit\Services\Sftp;
use Mockery as m;
use Tests\TestCase;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Services\Sftp\AuthenticateUsingPasswordService;
class AuthenticateUsingPasswordServiceTest extends TestCase
{
/**
* @var \Pterodactyl\Services\DaemonKeys\DaemonKeyProviderService|\Mockery\Mock
*/
private $keyProviderService;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface|\Mockery\Mock
*/
private $repository;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface|\Mockery\Mock
*/
private $userRepository;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->keyProviderService = m::mock(DaemonKeyProviderService::class);
$this->repository = m::mock(ServerRepositoryInterface::class);
$this->userRepository = m::mock(UserRepositoryInterface::class);
}
/**
* Test that an account can be authenticated.
*/
public function testNonAdminAccountIsAuthenticated()
{
$user = factory(User::class)->make(['root_admin' => 0]);
$server = factory(Server::class)->make(['node_id' => 1, 'owner_id' => $user->id]);
$this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf();
$this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user);
$this->repository->shouldReceive('withColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf();
$this->repository->shouldReceive('getByUuid')->with($server->uuidShort)->once()->andReturn($server);
$this->keyProviderService->shouldReceive('handle')->with($server->id, $user->id)->once()->andReturn('server_token');
$response = $this->getService()->handle($user->username, 'password', 1, $server->uuidShort);
$this->assertNotEmpty($response);
$this->assertArrayHasKey('server', $response);
$this->assertArrayHasKey('token', $response);
$this->assertSame($server->uuid, $response['server']);
$this->assertSame('server_token', $response['token']);
}
/**
* Test that an administrative user can access servers that they are not
* set as the owner of.
*/
public function testAdminAccountIsAuthenticated()
{
$user = factory(User::class)->make(['root_admin' => 1]);
$server = factory(Server::class)->make(['node_id' => 1, 'owner_id' => $user->id + 1]);
$this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf();
$this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user);
$this->repository->shouldReceive('withColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf();
$this->repository->shouldReceive('getByUuid')->with($server->uuidShort)->once()->andReturn($server);
$this->keyProviderService->shouldReceive('handle')->with($server->id, $user->id)->once()->andReturn('server_token');
$response = $this->getService()->handle($user->username, 'password', 1, $server->uuidShort);
$this->assertNotEmpty($response);
$this->assertArrayHasKey('server', $response);
$this->assertArrayHasKey('token', $response);
$this->assertSame($server->uuid, $response['server']);
$this->assertSame('server_token', $response['token']);
}
/**
* Test exception gets thrown if no server is passed into the function.
*
* @expectedException \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function testExceptionIsThrownIfNoServerIsProvided()
{
$this->getService()->handle('username', 'password', 1);
}
/**
* Test that an exception is thrown if the user account exists but the wrong
* credentials are passed.
*
* @expectedException \Illuminate\Auth\AuthenticationException
*/
public function testExceptionIsThrownIfUserDetailsAreIncorrect()
{
$user = factory(User::class)->make();
$this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf();
$this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user);
$this->getService()->handle($user->username, 'wrongpassword', 1, '1234');
}
/**
* Test that an exception is thrown if no user account is found.
*
* @expectedException \Illuminate\Auth\AuthenticationException
*/
public function testExceptionIsThrownIfNoUserAccountIsFound()
{
$this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf();
$this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', 'something']])->once()->andThrow(new RecordNotFoundException);
$this->getService()->handle('something', 'password', 1, '1234');
}
/**
* Test that an exception is thrown if the user is not the owner of the server
* and is not an administrator.
*
* @expectedException \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function testExceptionIsThrownIfUserDoesNotOwnServer()
{
$user = factory(User::class)->make(['root_admin' => 0]);
$server = factory(Server::class)->make(['node_id' => 1, 'owner_id' => $user->id + 1]);
$this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf();
$this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user);
$this->repository->shouldReceive('withColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf();
$this->repository->shouldReceive('getByUuid')->with($server->uuidShort)->once()->andReturn($server);
$this->getService()->handle($user->username, 'password', 1, $server->uuidShort);
}
/**
* Test that an exception is thrown if the requested server does not belong to
* the node that the request is made from.
*
* @expectedException \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function testExceptionIsThrownIfServerDoesNotExistOnCurrentNode()
{
$user = factory(User::class)->make(['root_admin' => 0]);
$server = factory(Server::class)->make(['node_id' => 2, 'owner_id' => $user->id]);
$this->userRepository->shouldReceive('withColumns')->with(['id', 'root_admin', 'password'])->once()->andReturnSelf();
$this->userRepository->shouldReceive('findFirstWhere')->with([['username', '=', $user->username]])->once()->andReturn($user);
$this->repository->shouldReceive('withColumns')->with(['id', 'node_id', 'owner_id', 'uuid'])->once()->andReturnSelf();
$this->repository->shouldReceive('getByUuid')->with($server->uuidShort)->once()->andReturn($server);
$this->getService()->handle($user->username, 'password', 1, $server->uuidShort);
}
/**
* Return an instance of the service with mocked dependencies.
*
* @return \Pterodactyl\Services\Sftp\AuthenticateUsingPasswordService
*/
private function getService(): AuthenticateUsingPasswordService
{
return new AuthenticateUsingPasswordService($this->keyProviderService, $this->repository, $this->userRepository);
}
}