Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions src/Process/HostProcessFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@

final class HostProcessFactory implements ProcessFactory
{
/**
* Inherited env vars that are kept, everything else is unset so we don't leak secrets to the process
*/
private const ALLOWED_ENV = ['PATH', 'HOME', 'COMPOSER_HOME'];

private ExecutableFinder $executableFinder;

public function __construct(?ExecutableFinder $executableFinder = null)
Expand All @@ -28,19 +33,27 @@ public function create(ProcessInput $processInput): Process
return new Process(
[$executablePath, ...$processInput->getArgs()],
$processInput->getWorkingDirectory(),
$this->getDefaultEnv() + $processInput->getEnv(),
array_merge($this->getDefaultEnv(), $processInput->getEnv()),
$processInput->getInput(),
10,
);
}

/**
* @return array<false>
* Symfony Process inherits the parent env, so we unset every inherited var by setting it to false.
* We read from getenv() rather than $_ENV, as $_ENV is empty when variables_order does not include E.
*
* @return array<string, false>
*/
private function getDefaultEnv(): array
{
$env = array_map(fn() => false, $_ENV);
$env + array_map(fn() => false, $_SERVER);
$env = [];

foreach (array_keys(getenv() + $_ENV) as $name) {
if (!in_array($name, self::ALLOWED_ENV, true)) {
$env[(string) $name] = false;
}
}

return $env;
}
Expand Down
18 changes: 17 additions & 1 deletion test/Process/HostProcessFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,23 @@ public function testCreateWithEnv(): void
$input = new ProcessInput('composer', ['one', 'two'], __DIR__, ['SOME_VAR' => 'value']);

$process = $factory->create($input);
static::assertSame(['SOME_VAR' => 'value'], $process->getEnv());
static::assertSame('value', $process->getEnv()['SOME_VAR']);
}

public function testInheritedEnvIsRemovedExceptAllowed(): void
{
putenv('PHPSCHOOL_SECRET=secret');

try {
$process = (new HostProcessFactory())->create(
new ProcessInput('php', ['-r', 'echo json_encode([getenv("PHPSCHOOL_SECRET"), getenv("PATH") !== false]);'], __DIR__, []),
);
$process->mustRun();

static::assertSame('[false,true]', $process->getOutput());
} finally {
putenv('PHPSCHOOL_SECRET');
}
}

public function testWithInput(): void
Expand Down
Loading