Skip to content

Commit

Permalink
bug #3348 Fixes #3351 (Bozhidar Hristov)
Browse files Browse the repository at this point in the history
This PR was submitted for the 3.x branch but it was squashed and merged into the 1.x branch instead.

Discussion
----------

Fixes #3351

Sandbox mode is not disabled if syntax error occurs inside {% sandbox %} tag

Fixes #3351

Commits
-------

04658c9 Fixes #3351
  • Loading branch information
fabpot committed Jul 9, 2020
2 parents 2ecc15a + 04658c9 commit cb06013
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
7 changes: 7 additions & 0 deletions src/Node/SandboxNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,19 @@ public function compile(Compiler $compiler)
->write("\$this->sandbox->enableSandbox();\n")
->outdent()
->write("}\n")
->write("try {\n")
->indent()
->subcompile($this->getNode('body'))
->outdent()
->write("} finally {\n")
->indent()
->write("if (!\$alreadySandboxed) {\n")
->indent()
->write("\$this->sandbox->disableSandbox();\n")
->outdent()
->write("}\n")
->outdent()
->write("}\n")
;
}
}
Expand Down
15 changes: 15 additions & 0 deletions tests/Extension/SandboxTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
*/

use Twig\Environment;
use Twig\Error\SyntaxError;
use Twig\Extension\SandboxExtension;
use Twig\Loader\ArrayLoader;
use Twig\Sandbox\SecurityError;
Expand Down Expand Up @@ -44,6 +45,8 @@ protected function setUp(): void
'1_child' => "{% extends \"1_layout\" %}\n{% block content %}\n{{ \"a\"|json_encode }}\n{% endblock %}",
'1_include' => '{{ include("1_basic1", sandboxed=true) }}',
'1_range_operator' => '{{ (1..2)[0] }}',
'1_syntax_error_wrapper' => '{% sandbox %}{% include "1_syntax_error" %}{% endsandbox %}',
'1_syntax_error' => '{% syntax error }}'
];
}

Expand Down Expand Up @@ -75,6 +78,18 @@ public function testSandboxUnallowedMethodAccessor()
}
}

public function testIfSandBoxIsDisabledAfterSyntaxError()
{
$twig = $this->getEnvironment(false, [], self::$templates);
try {
$twig->load('1_syntax_error_wrapper')->render(self::$params);
} catch (SyntaxError $e) {
/** @var SandboxExtension $sandbox */
$sandbox = $twig->getExtension(SandboxExtension::class);
$this->assertFalse($sandbox->isSandboxed());
}
}

public function testSandboxUnallowedFilter()
{
$twig = $this->getEnvironment(true, [], self::$templates);
Expand Down
9 changes: 6 additions & 3 deletions tests/Node/SandboxTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,12 @@ public function getTests()
if (!\$alreadySandboxed = \$this->sandbox->isSandboxed()) {
\$this->sandbox->enableSandbox();
}
echo "foo";
if (!\$alreadySandboxed) {
\$this->sandbox->disableSandbox();
try {
echo "foo";
} finally {
if (!\$alreadySandboxed) {
\$this->sandbox->disableSandbox();
}
}
EOF
];
Expand Down

0 comments on commit cb06013

Please sign in to comment.