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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

## 2.9.4 - Upcoming

* Fixed the compiled runtime to use a private default cache directory, preventing local code execution.

## 2.9.3 - 2026-11-16

* Fixed merge() to error on scalar and null arguments instead of triggering PHP errors.
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ $runtime('foo.bar', ['foo' => ['bar' => 'baz']]);
// > 'baz'
```

The cache directory holds PHP files that are executed when loaded, so it must
not be writable by untrusted users. When no directory is provided, a private
per-user directory inside the system temp directory is used, except on
Windows, where the system temp directory itself is used.

##### Environment Variables

You can utilize the CompilerRuntime in `JmesPath\search()` by setting the
Expand Down
2 changes: 1 addition & 1 deletion bin/perf.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ function runCase($given, $expression, $name)
$runtime = \JmesPath\Env::createRuntime();
// Delete compiled scripts if not caching.
if ($runtime instanceof \JmesPath\CompilerRuntime) {
array_map('unlink', glob(sys_get_temp_dir() . '/jmespath_*.php'));
array_map('unlink', glob($runtime->getCacheDir() . '/jmespath_*.php'));
}
}
}
Expand Down
66 changes: 65 additions & 1 deletion src/CompilerRuntime.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class CompilerRuntime
private $compiler;
private $cacheDir;
private $interpreter;
private $tempDir;

/**
* @param string|null $dir Directory used to store compiled PHP files.
Expand All @@ -30,7 +31,11 @@ public function __construct($dir = null, ?Parser $parser = null)
{
$this->parser = $parser ?: new Parser();
$this->compiler = new TreeCompiler();
$dir = $dir ?: sys_get_temp_dir();

if (!$dir) {
$dir = self::defaultCacheDir();
$this->tempDir = realpath(sys_get_temp_dir());
}

if (!is_dir($dir) && !mkdir($dir, 0755, true)) {
throw new \RuntimeException("Unable to create cache directory: $dir");
Expand All @@ -57,6 +62,11 @@ public function __invoke($expression, $data)
$functionName = self::functionName($expression);

if (!function_exists($functionName)) {
if ($this->tempDir) {
// A long-lived process can outlive the directory it checked.
$this->cacheDir = self::defaultCacheDir($this->tempDir);
}

$filename = "{$this->cacheDir}/{$functionName}.php";
if (!file_exists($filename)) {
$this->compile($filename, $expression, $functionName);
Expand All @@ -78,12 +88,66 @@ public static function functionName($expression)
);
}

/**
* @internal Shared with Env so the default location cannot drift.
*/
public static function defaultCacheDir($temp = null)
{
$dir = $temp ?: sys_get_temp_dir();

if (PHP_OS_FAMILY === 'Windows') {
return $dir;
}

$uid = self::effectiveUserId();
$dir = rtrim($dir, '/') . "/jmespath-{$uid}";

clearstatcache(true, $dir);

if (!is_dir($dir)) {
@mkdir($dir, 0700, true);
}

// A single lstat() so the type, owner and mode describe the same file.
$stat = @lstat($dir);

if (!$stat
|| ($stat['mode'] & 0170000) !== 0040000
|| $stat['uid'] !== $uid
|| ($stat['mode'] & 0077) !== 0
) {
throw new \RuntimeException(
"Unable to use private cache directory: {$dir}"
);
}

return $dir;
}

/** @internal */
public function getCacheDir()
{
return $this->cacheDir;
}

private static function effectiveUserId()
{
if (function_exists('posix_geteuid')) {
return posix_geteuid();
}

$file = tmpfile();

if (!$file) {
throw new \RuntimeException('Unable to determine the current user');
}

$uid = fstat($file)['uid'];
fclose($file);

return $uid;
}

private function compile($filename, $expression, $functionName)
{
$code = $this->compiler->visit(
Expand Down
8 changes: 6 additions & 2 deletions src/Env.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public static function createRuntime()

/**
* Delete all previously compiled JMESPath files from the JP_COMPILE_DIR
* directory or sys_get_temp_dir().
* directory or the default cache directory.
*
* @return int Returns the number of deleted files.
*/
Expand All @@ -59,7 +59,11 @@ public static function cleanCompileDir()
$total = 0;
$compileDir = self::getEnvVariable(self::COMPILE_DIR);
if ($compileDir === 'on' || !$compileDir) {
$compileDir = sys_get_temp_dir();
try {
$compileDir = CompilerRuntime::defaultCacheDir();
} catch (\RuntimeException $e) {
return $total;
}
}

foreach (glob("{$compileDir}/jmespath_*.php") as $file) {
Expand Down
139 changes: 139 additions & 0 deletions tests/CompilerRuntimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,128 @@ public function testFunctionNameUsesVersionedSalt(): void
);
}

/**
* @requires function posix_geteuid
*/
public function testDefaultCacheDirIsPrivateToCurrentUser(): void
{
$temp = $this->createTempDir();
$dir = $temp . '/jmespath-' . posix_geteuid();

try {
$this->assertSame($dir, $this->runInTempDir($temp, 'echo (new JmesPath\CompilerRuntime())->getCacheDir();'));
$this->assertSame(posix_geteuid(), fileowner($dir));
$this->assertSame(0700, fileperms($dir) & 0777);
} finally {
$this->removeTempDir($dir);
$this->removeTempDir($temp);
}
}

/**
* @requires function posix_geteuid
*/
public function testDefaultCacheDirIgnoresFilesInSystemTempDir(): void
{
$temp = $this->createTempDir();
$name = CompilerRuntime::functionName('foo');
file_put_contents($temp . '/' . $name . '.php', "<?php function {$name}() { return 'planted'; }");

try {
$this->assertSame('123', $this->runInTempDir($temp, 'echo (new JmesPath\CompilerRuntime())("foo", ["foo" => 123]);'));
} finally {
$this->removeTempDir($temp . '/jmespath-' . posix_geteuid());
$this->removeTempDir($temp);
}
}

/**
* @requires function posix_geteuid
*/
public function testRejectsDefaultCacheDirAccessibleByOthers(): void
{
$temp = $this->createTempDir();
$dir = $temp . '/jmespath-' . posix_geteuid();
mkdir($dir);
chmod($dir, 0755);

try {
$this->assertSame(
"Unable to use private cache directory: {$dir}",
$this->runInTempDir($temp, 'new JmesPath\CompilerRuntime();')
);
} finally {
$this->removeTempDir($dir);
$this->removeTempDir($temp);
}
}

/**
* @requires function posix_geteuid
*/
public function testRejectsSymlinkedDefaultCacheDir(): void
{
$temp = $this->createTempDir();
$dir = $temp . '/jmespath-' . posix_geteuid();
$target = $this->createTempDir();
chmod($target, 0700);
symlink($target, $dir);

try {
$this->assertSame(
"Unable to use private cache directory: {$dir}",
$this->runInTempDir($temp, 'new JmesPath\CompilerRuntime();')
);
} finally {
unlink($dir);
$this->removeTempDir($target);
$this->removeTempDir($temp);
}
}

/**
* @requires function posix_geteuid
*/
public function testChecksDefaultCacheDirAgainBeforeLoading(): void
{
$temp = $this->createTempDir();
$dir = $temp . '/jmespath-' . posix_geteuid();

try {
$this->runInTempDir($temp, '(new JmesPath\CompilerRuntime())("foo", []);');
$this->assertSame(
"Unable to use private cache directory: {$dir}",
$this->runInTempDir(
$temp,
'$runtime = new JmesPath\CompilerRuntime(); chmod($runtime->getCacheDir(), 0755); $runtime("foo", []);'
)
);
} finally {
$this->removeTempDir($dir);
$this->removeTempDir($temp);
}
}

/**
* @requires function posix_geteuid
*/
public function testKeepsDefaultCacheDirWhenWorkingDirectoryChanges(): void
{
$temp = $this->createTempDir();
$dir = $temp . '/jmespath-' . posix_geteuid();
$code = sprintf(
'chdir(%s); $runtime = new JmesPath\CompilerRuntime(); chdir("/"); $runtime("foo", []); echo $runtime->getCacheDir();',
var_export($temp, true)
);

try {
$this->assertSame($dir, $this->runInTempDir('.', $code));
} finally {
$this->removeTempDir($dir);
$this->removeTempDir($temp);
}
}

public function testRuntimesUseJmesPathTruthinessForEmptyObjects(): void
{
$dir = $this->createTempDir();
Expand Down Expand Up @@ -192,6 +314,23 @@ public function testStillCompilesValidFunctions(): void
}
}

private function runInTempDir($temp, $code)
{
$command = sprintf(
'%s -d sys_temp_dir=%s -r %s 2>&1',
escapeshellarg(PHP_BINARY),
escapeshellarg($temp),
escapeshellarg(sprintf(
'require %s; try { %s } catch (RuntimeException $e) { echo $e->getMessage(); }',
var_export(__DIR__ . '/../vendor/autoload.php', true),
$code
))
);
exec($command, $output);

return implode("\n", $output);
}

private function createTempDir()
{
$dir = sys_get_temp_dir() . '/jmespath-compiler-' . bin2hex(random_bytes(12));
Expand Down
7 changes: 2 additions & 5 deletions tests/ComplianceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,8 @@ class ComplianceTest extends TestCase

public static function setUpBeforeClass(): void
{
self::$path = sys_get_temp_dir() . '/jmespath-compliance-compiled';
if (!is_dir(self::$path)) {
mkdir(self::$path, 0777, true);
}
array_map('unlink', glob(self::$path . '/jmespath_*.php') ?: []);
self::$path = sys_get_temp_dir() . '/jmespath-compliance-' . bin2hex(random_bytes(12));
mkdir(self::$path);
}

public static function tearDownAfterClass(): void
Expand Down
8 changes: 4 additions & 4 deletions tests/EnvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ public function testSearchesWithFunction(): void

public function testCleansCompileDir(): void
{
$dir = sys_get_temp_dir();
$runtime = new CompilerRuntime($dir);
$runtime = new CompilerRuntime();
$dir = $runtime->getCacheDir();
$runtime('@ | @ | @[0][0][0]', []);
$this->assertNotEmpty(glob($dir . '/jmespath_*.php'));
$this->assertGreaterThan(0, Env::cleanCompileDir());
Expand All @@ -37,8 +37,8 @@ public function testCleansCompileDirWhenCompileEnvIsOn(): void
$_SERVER[Env::COMPILE_DIR] = 'on';

$expr = 'env' . bin2hex(random_bytes(12));
$filename = sys_get_temp_dir() . '/' . CompilerRuntime::functionName($expr) . '.php';
$runtime = new CompilerRuntime(sys_get_temp_dir());
$runtime = new CompilerRuntime();
$filename = $runtime->getCacheDir() . '/' . CompilerRuntime::functionName($expr) . '.php';

try {
$this->assertSame(1, $runtime($expr, [$expr => 1]));
Expand Down