Skip to content
Open
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
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* Add a way to mark a `Twig\Markup` instance as safe for some escaping strategies only
* Make `Environment::getExtension()` return the runtime of an extension class registered with `AttributeExtension`
* Make `Environment::getRuntime()` fall back to the registered extension of the same class
* Speed up checking allowed methods and properties in `SecurityPolicy`

# 3.30.0 (2026-09-25)

Expand Down
50 changes: 33 additions & 17 deletions src/Sandbox/SecurityPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ final class SecurityPolicy implements SecurityPolicyInterface
private $allowedFunctions;
private array $allowedTests;
private bool $strict = false;
/** @var array<class-string, array<string|int, true>> */
private array $allowedMethodCache = [];
/** @var array<class-string, array<string|int, true>> */
private array $allowedPropertyCache = [];

public function __construct(array $allowedTags = [], array $allowedFilters = [], array $allowedMethods = [], array $allowedProperties = [], array $allowedFunctions = [], array $allowedTests = [])
{
Expand All @@ -52,6 +56,7 @@ public function setAllowedFilters(array $filters): void
public function setAllowedMethods(array $methods): void
{
$this->allowedMethods = [];
$this->allowedMethodCache = [];
foreach ($methods as $class => $m) {
$this->allowedMethods[$class] = array_map('strtolower', \is_array($m) ? $m : [$m]);
}
Expand All @@ -60,6 +65,7 @@ public function setAllowedMethods(array $methods): void
public function setAllowedProperties(array $properties): void
{
$this->allowedProperties = $properties;
$this->allowedPropertyCache = [];
}

public function setAllowedFunctions(array $functions): void
Expand Down Expand Up @@ -146,39 +152,49 @@ public function checkSecurity($tags, $filters, $functions, array $tests = []): v

public function checkMethodAllowed($obj, $method): void
{
$method = strtolower($method);
$objClass = $obj::class;
if (isset($this->allowedMethodCache[$objClass][$method])) {
return;
}

$lcMethod = strtolower($method);

if ($obj instanceof Template || ($obj instanceof Markup && 'withcontent' !== $lcMethod)) {
$this->allowedMethodCache[$objClass][$method] = true;

if ($obj instanceof Template || ($obj instanceof Markup && 'withcontent' !== $method)) {
return;
}

$allowed = false;
foreach ($this->allowedMethods as $class => $methods) {
if ($obj instanceof $class && \in_array($method, $methods, true)) {
$allowed = true;
break;
if ($obj instanceof $class && \in_array($lcMethod, $methods, true)) {
$this->allowedMethodCache[$objClass][$method] = true;

return;
}
}

if (!$allowed) {
$class = $obj::class;
throw new SecurityNotAllowedMethodError(\sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, $class), $class, $method);
}
throw new SecurityNotAllowedMethodError(\sprintf('Calling "%s" method on a "%s" object is not allowed.', $lcMethod, $objClass), $objClass, $lcMethod);
}

public function checkPropertyAllowed($obj, $property): void
{
$allowed = false;
// an ArrayAccess key can be anything, and only a string or an integer can be a cache key
$cacheable = \is_string($property) || \is_int($property);
$objClass = $obj::class;
if ($cacheable && isset($this->allowedPropertyCache[$objClass][$property])) {
return;
}

foreach ($this->allowedProperties as $class => $properties) {
if ($obj instanceof $class && \in_array($property, \is_array($properties) ? $properties : [$properties], true)) {
$allowed = true;
break;
if ($cacheable) {
$this->allowedPropertyCache[$objClass][$property] = true;
}

return;
}
}

if (!$allowed) {
$class = $obj::class;
throw new SecurityNotAllowedPropertyError(\sprintf('Calling "%s" property on a "%s" object is not allowed.', $property, $class), $class, $property);
}
throw new SecurityNotAllowedPropertyError(\sprintf('Calling "%s" property on a "%s" object is not allowed.', $property, $objClass), $objClass, $property);
}
}
176 changes: 176 additions & 0 deletions tests/Sandbox/SecurityPolicyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
<?php

/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Twig\Tests\Sandbox;

use PHPUnit\Framework\TestCase;
use Twig\Markup;
use Twig\Sandbox\SecurityNotAllowedMethodError;
use Twig\Sandbox\SecurityNotAllowedPropertyError;
use Twig\Sandbox\SecurityPolicy;

class SecurityPolicyTest extends TestCase
{
public function testMethodNamesAreCaseInsensitive(): void
{
$policy = new SecurityPolicy([], [], [SecurityPolicyTestObject::class => ['getFoo']]);
$object = new SecurityPolicyTestObject();

$policy->checkMethodAllowed($object, 'getFoo');
$policy->checkMethodAllowed($object, 'GETFOO');
$policy->checkMethodAllowed($object, 'getfoo');

$this->expectException(SecurityNotAllowedMethodError::class);
$this->expectExceptionMessage('Calling "getbar" method on a "'.SecurityPolicyTestObject::class.'" object is not allowed.');
$policy->checkMethodAllowed($object, 'getBar');
}

public function testAnAllowedMethodStaysAllowedAndADeniedOneStaysDenied(): void
{
$policy = new SecurityPolicy([], [], [SecurityPolicyTestObject::class => ['getFoo']]);
$object = new SecurityPolicyTestObject();

$policy->checkMethodAllowed($object, 'getFoo');
$policy->checkMethodAllowed($object, 'getFoo');

for ($i = 0; $i < 2; ++$i) {
try {
$policy->checkMethodAllowed($object, 'getBar');
$this->fail('A denied method must be denied on every call.');
} catch (SecurityNotAllowedMethodError $e) {
$this->assertSame(SecurityPolicyTestObject::class, $e->getClassName());
$this->assertSame('getbar', $e->getMethodName());
}
}
}

public function testMethodsAllowedOnAClassAreAllowedOnItsSubclassesOnly(): void
{
$policy = new SecurityPolicy([], [], [SecurityPolicyTestObject::class => ['getFoo']]);

$policy->checkMethodAllowed(new SecurityPolicyTestChildObject(), 'getFoo');

$this->expectException(SecurityNotAllowedMethodError::class);
$policy->checkMethodAllowed(new SecurityPolicyTestSiblingObject(), 'getFoo');
}

public function testSetAllowedMethodsRevokesWhatWasAllowedBefore(): void
{
$policy = new SecurityPolicy([], [], [SecurityPolicyTestObject::class => ['getFoo']]);
$object = new SecurityPolicyTestObject();

$policy->checkMethodAllowed($object, 'getFoo');

$policy->setAllowedMethods([SecurityPolicyTestObject::class => ['getBar']]);
$policy->checkMethodAllowed($object, 'getBar');

$this->expectException(SecurityNotAllowedMethodError::class);
$policy->checkMethodAllowed($object, 'getFoo');
}

public function testTemplateAndMarkupMethodsAreAllowedExceptWithContent(): void
{
$policy = new SecurityPolicy();
$markup = new Markup('content', 'UTF-8');

$policy->checkMethodAllowed($markup, '__toString');
$policy->checkMethodAllowed($markup, '__toString');

$this->expectException(SecurityNotAllowedMethodError::class);
$policy->checkMethodAllowed($markup, 'withContent');
}

public function testAnAllowedPropertyStaysAllowedAndADeniedOneStaysDenied(): void
{
$policy = new SecurityPolicy([], [], [], [SecurityPolicyTestObject::class => ['foo']]);
$object = new SecurityPolicyTestObject();

$policy->checkPropertyAllowed($object, 'foo');
$policy->checkPropertyAllowed($object, 'foo');

for ($i = 0; $i < 2; ++$i) {
try {
$policy->checkPropertyAllowed($object, 'bar');
$this->fail('A denied property must be denied on every call.');
} catch (SecurityNotAllowedPropertyError $e) {
$this->assertSame(SecurityPolicyTestObject::class, $e->getClassName());
$this->assertSame('bar', $e->getPropertyName());
}
}
}

public function testPropertyNamesAreCaseSensitive(): void
{
$policy = new SecurityPolicy([], [], [], [SecurityPolicyTestObject::class => ['foo']]);
$object = new SecurityPolicyTestObject();

$policy->checkPropertyAllowed($object, 'foo');

$this->expectException(SecurityNotAllowedPropertyError::class);
$policy->checkPropertyAllowed($object, 'FOO');
}

public function testSetAllowedPropertiesRevokesWhatWasAllowedBefore(): void
{
$policy = new SecurityPolicy([], [], [], [SecurityPolicyTestObject::class => ['foo']]);
$object = new SecurityPolicyTestObject();

$policy->checkPropertyAllowed($object, 'foo');

$policy->setAllowedProperties([SecurityPolicyTestObject::class => ['bar']]);
$policy->checkPropertyAllowed($object, 'bar');

$this->expectException(SecurityNotAllowedPropertyError::class);
$policy->checkPropertyAllowed($object, 'foo');
}

public function testPropertyKeysThatAreNeitherStringsNorIntegersAreSupported(): void
{
$key = new Markup('foo', 'UTF-8');
$policy = new SecurityPolicy([], [], [], [SecurityPolicyTestObject::class => [0, $key]]);
$object = new SecurityPolicyTestObject();

$policy->checkPropertyAllowed($object, 0);
$policy->checkPropertyAllowed($object, 0);
$policy->checkPropertyAllowed($object, $key);
$policy->checkPropertyAllowed($object, $key);

$this->expectException(SecurityNotAllowedPropertyError::class);
$policy->checkPropertyAllowed($object, new Markup('bar', 'UTF-8'));
}
}

class SecurityPolicyTestObject
{
public $foo = 'foo';

public function getFoo()
{
return 'foo';
}

public function getBar()
{
return 'bar';
}
}

class SecurityPolicyTestChildObject extends SecurityPolicyTestObject
{
}

class SecurityPolicyTestSiblingObject
{
public function getFoo()
{
return 'foo';
}
}
Loading