Additional coverage to ensure values are wrapped as expected; ref #3287

This commit is contained in:
Dane Everitt 2021-04-24 16:39:56 -07:00
parent 38a5f2dbbf
commit 6ef60633d3
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
2 changed files with 58 additions and 15 deletions

View file

@ -1,11 +1,4 @@
<?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\Traits\Commands;
@ -13,6 +6,20 @@ use Pterodactyl\Exceptions\PterodactylException;
trait EnvironmentWriterTrait
{
/**
* Escapes an environment value by looking for any characters that could
* reasonablly cause environment parsing issues. Those values are then wrapped
* in quotes before being returned.
*/
public function escapeEnvironmentValue(string $value): string
{
if (!preg_match('/^\"(.*)\"$/', $value) && preg_match('/([^\w.\-+\/])+/', $value)) {
return sprintf('"%s"', addslashes($value));
}
return $value;
}
/**
* Update the .env file for the application using the passed in values.
*
@ -28,14 +35,7 @@ trait EnvironmentWriterTrait
$saveContents = file_get_contents($path);
collect($values)->each(function ($value, $key) use (&$saveContents) {
$key = strtoupper($key);
// If the key value is not sorrounded by quotation marks, and contains anything that could reasonably
// cause environment parsing issues, wrap it in quotes before writing it. This also adds slashes to the
// value to ensure quotes within it don't cause us issues.
if (!preg_match('/^\"(.*)\"$/', $value) && preg_match('/([^\w.\-+\/])+/', $value)) {
$value = sprintf('"%s"', addslashes($value));
}
$saveValue = sprintf('%s=%s', $key, $value);
$saveValue = sprintf('%s=%s', $key, $this->escapeEnvironmentValue($value));
if (preg_match_all('/^' . $key . '=(.*)$/m', $saveContents) < 1) {
$saveContents = $saveContents . PHP_EOL . $saveValue;

View file

@ -0,0 +1,43 @@
<?php
namespace Pterodactyl\Tests\Unit\Helpers;
use Pterodactyl\Tests\TestCase;
use Pterodactyl\Traits\Commands\EnvironmentWriterTrait;
class EnvironmentWriterTraitTest extends TestCase
{
/**
* @dataProvider variableDataProvider
*/
public function testVariableIsEscapedProperly($input, $expected)
{
$output = (new FooClass())->escapeEnvironmentValue($input);
$this->assertSame($expected, $output);
}
public function variableDataProvider(): array
{
return [
['foo', 'foo'],
['abc123', 'abc123'],
['val"ue', '"val\"ue"'],
['my test value', '"my test value"'],
['mysql_p@assword', '"mysql_p@assword"'],
['mysql_p#assword', '"mysql_p#assword"'],
['mysql p@$$word', '"mysql p@$$word"'],
['mysql p%word', '"mysql p%word"'],
['mysql p#word', '"mysql p#word"'],
['abc_@#test', '"abc_@#test"'],
['test 123 $$$', '"test 123 $$$"'],
['#password%', '"#password%"'],
['$pass ', '"$pass "'],
];
}
}
class FooClass
{
use EnvironmentWriterTrait;
}