From 171a1d47a67f234c1ded1a2274194af188b7fe16 Mon Sep 17 00:00:00 2001 From: Carson Full Date: Mon, 5 Dec 2016 16:08:06 -0600 Subject: [PATCH] Fix sandbox being left enabled if an exception is thrown while rendering with include function --- lib/Twig/Extension/Core.php | 12 ++++++++++++ test/Twig/Tests/Extension/SandboxTest.php | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/lib/Twig/Extension/Core.php b/lib/Twig/Extension/Core.php index 69fa57b413..508b0c8848 100644 --- a/lib/Twig/Extension/Core.php +++ b/lib/Twig/Extension/Core.php @@ -1406,6 +1406,18 @@ function twig_include(Twig_Environment $env, $context, $template, $variables = a throw $e; } + } catch (Throwable $e) { + if ($isSandboxed && !$alreadySandboxed) { + $sandbox->disableSandbox(); + } + + throw $e; + } catch (Exception $e) { + if ($isSandboxed && !$alreadySandboxed) { + $sandbox->disableSandbox(); + } + + throw $e; } if ($isSandboxed && !$alreadySandboxed) { diff --git a/test/Twig/Tests/Extension/SandboxTest.php b/test/Twig/Tests/Extension/SandboxTest.php index 792cb33211..7456cd84af 100644 --- a/test/Twig/Tests/Extension/SandboxTest.php +++ b/test/Twig/Tests/Extension/SandboxTest.php @@ -34,6 +34,7 @@ protected function setUp() '1_basic' => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}', '1_layout' => '{% block content %}{% endblock %}', '1_child' => "{% extends \"1_layout\" %}\n{% block content %}\n{{ \"a\"|json_encode }}\n{% endblock %}", + '1_include' => '{{ include("1_basic1", sandboxed=true) }}', ); } @@ -240,6 +241,23 @@ public function testMacrosInASandbox() $this->assertEquals('

username

', $twig->loadTemplate('index')->render(array())); } + public function testSandboxDisabledAfterIncludeFunctionError() + { + $twig = $this->getEnvironment(false, array(), self::$templates); + + $e = null; + try { + $twig->loadTemplate('1_include')->render(self::$params); + } catch (Throwable $e) { + } catch (Exception $e) { + } + if ($e === null) { + $this->fail('An exception should be thrown for this test to be valid.'); + } + + $this->assertFalse($twig->getExtension('Twig_Extension_Sandbox')->isSandboxed(), 'Sandboxed include() function call should not leave Sandbox enabled when an error occurs.'); + } + protected function getEnvironment($sandboxed, $options, $templates, $tags = array(), $filters = array(), $methods = array(), $properties = array(), $functions = array()) { $loader = new Twig_Loader_Array($templates);