Twig: Twig cache bug, potentially harmful

According to documentation:

Twig_Loader_Filesystem support absolute and relative paths. Using relative paths is preferred as it makes the cache keys independent of the project root directory (for instance, it allows warming the cache from a build server where the directory might be different from the one used on production servers)

This implies that absolute paths should create different cache files. But right now absolute paths do not work as intended. They share same cached files, this can be harmful in production environment.

Twig version: v1.33.2 composer require twig/twig

<?php
require_once (__DIR__."/vendor/autoload.php");
$path = getcwd()."/tpl";
echo "path=$path\n";
$twig_loader = new Twig_Loader_Filesystem($path);
$twig = new Twig_Environment($twig_loader, array(
						'cache' => '/tmp/twig-cache',
						'auto_reload' => true,
						));

echo $twig->render('page.html.twig');
?>

Just create two versions of this file in different folders and create different tpl/page.html.twig files. Once cache created, both php will output same cached result. Opcode disabled.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 20 (14 by maintainers)

Most upvoted comments

@alpha-and-omega the Twig_Environment gets cache names as input, and and has a cache folder. If you have several environments with different configurations, you must either ensure that they don’t share the same cache folder, or ensure that they will never reuse the same template name. Sharing the same cache folder for 2 environments with different configuration is opening the door to cache corruption (as the cache will be written by the other environment too). Instead of using /tmp/twig-cache as cache folder, create a different cache folder for each project.

This ticket is about the other case: if you don’t care about the second argument and want to use absolute paths, then you can still get cache conflicts.

I think the issue here is that you are trying to use 2 different environments sharing the same cache folder. The only way to make this work would be to ensure that they will never use the same template cache key when using the same template name (as the template name will resolve to a different file). Solving this use case requires using the template absolute path again as cache key, which forbids doing the warmup on a different machine and copying the cache. I don’t think it is worth it IMO. Just use separate cache folders if you have several environments with different configurations