Skip to content

Commit

Permalink
bug #2282 Fix sandbox being left enabled if an exception is thrown wh…
Browse files Browse the repository at this point in the history
…ile rendering (CarsonF)

This PR was merged into the 1.x branch.

Discussion
----------

Fix sandbox being left enabled if an exception is thrown while rendering

What's happening for me:
- An exception is thrown while rendering inside the sandbox
- Render exception response
- WebProfiler toolbar tries to include a file
- Sandbox is still enabled, so a SecurityException is thrown (which hides the real error)

Commits
-------

171a1d4 Fix sandbox being left enabled if an exception is thrown while rendering with include function
  • Loading branch information
fabpot committed Dec 13, 2016
2 parents 52af84c + 171a1d4 commit 43a3dbf
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/Twig/Extension/Core.php
Expand Up @@ -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) {
Expand Down
18 changes: 18 additions & 0 deletions test/Twig/Tests/Extension/SandboxTest.php
Expand Up @@ -35,6 +35,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) }}',
);
}

Expand Down Expand Up @@ -241,6 +242,23 @@ public function testMacrosInASandbox()
$this->assertEquals('<p>username</p>', $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);
Expand Down

0 comments on commit 43a3dbf

Please sign in to comment.