Skip to content

[TwigBridge][TwigBundle] Add rate_limit() Twig function #61439

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 7.4
Choose a base branch
from
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
4 changes: 4 additions & 0 deletions src/Symfony/Bridge/Twig/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
CHANGELOG
=========

7.4
---
* Add `rate_limit()` Twig function

7.3
---

Expand Down
28 changes: 28 additions & 0 deletions src/Symfony/Bridge/Twig/Extension/RateLimiterExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Extension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
* @author Santiago San Martin <sanmartindev@gmail.com>
*/
final class RateLimiterExtension extends AbstractExtension
{
public function getFunctions(): array
{
return [
new TwigFunction('rate_limit', [RateLimiterRuntime::class, 'rateLimit']),
];
}
}
62 changes: 62 additions & 0 deletions src/Symfony/Bridge/Twig/Extension/RateLimiterRuntime.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Extension;

use Psr\Container\ContainerInterface;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\RateLimiter\RateLimiterFactoryInterface;

/**
* @author Santiago San Martin <sanmartindev@gmail.com>
*/
final class RateLimiterRuntime
{
public function __construct(
private readonly ContainerInterface $rateLimiterLocator,
private readonly RequestStack $requestStack,
private ?ExpressionLanguage $expressionLanguage = null,
) {
}

public function rateLimit(string $rateLimiterName, string|Expression|null $key = null, int $tokens = 1): bool
{
if (!class_exists(RateLimiterFactory::class)) {
throw new \LogicException('The "rate_limit()" function requires symfony/rate-limiter. Try running "composer require symfony/rate-limiter".');
}

$rateLimiterFactory = $this->rateLimiterLocator->get('limiter.'.$rateLimiterName);
if (!$rateLimiterFactory instanceof RateLimiterFactory && !$rateLimiterFactory instanceof RateLimiterFactoryInterface) {
$className = interface_exists(RateLimiterFactoryInterface::class) ? RateLimiterFactoryInterface::class : RateLimiterFactory::class;
throw new \LogicException(\sprintf('The service "%s" is not an instance of "%s".', $rateLimiterName, $className));
}

$limiter = $rateLimiterFactory->create($this->generateKey($key));

return $limiter->consume($tokens)->isAccepted();
}

private function generateKey(string|Expression|null $key): ?string
{
if (!$key instanceof Expression) {
return $key;
}

$this->expressionLanguage ??= new ExpressionLanguage();

return (string) $this->expressionLanguage->evaluate($key, [
'request' => $this->requestStack->getMainRequest(),
]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{% set limit = rate_limit('anonymous_api', 'custom_key', 50) %}
{% if limit %}
custom_key: allowed
{% else %}
custom_key: denied
{% endif %}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{% set limit = rate_limit('anonymous_api', 'exceed_key') %}
{% if limit %}
exceeded_limit: allowed
{% else %}
exceeded_limit: denied
{% endif %}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{% set limit = rate_limit('anonymous_api', expression('request.getClientIp()')) %}
{% if limit %}
expression_key: allowed
{% else %}
expression_key: denied
{% endif %}
174 changes: 174 additions & 0 deletions src/Symfony/Bridge/Twig/Tests/Extension/RateLimiterExtensionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Tests\Extension;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresMethod;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Bridge\Twig\Extension\ExpressionExtension;
use Symfony\Bridge\Twig\Extension\RateLimiterExtension;
use Symfony\Bridge\Twig\Extension\RateLimiterRuntime;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\RateLimiter\LimiterInterface;
use Symfony\Component\RateLimiter\RateLimit;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\RateLimiter\RateLimiterFactoryInterface;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
use Twig\RuntimeLoader\RuntimeLoaderInterface;

#[RequiresMethod(RateLimiterFactory::class, '__construct')]
class RateLimiterExtensionTest extends TestCase
{
#[DataProvider('provideRateLimitTemplatesUsingExpression')]
public function testRateLimiterWithExpression(
string $templateFile,
bool $isAccepted,
int|string $expectedConsume,
Expression $expression,
string $expectedOutput,
): void {
$request = Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '127.0.0.1']);
$requestStack = new RequestStack();
$requestStack->push($request);
$expectedKey = (new ExpressionLanguage())->evaluate($expression, ['request' => $request]);

$this->doTestRateLimiter(
templateFile: $templateFile,
isAccepted: $isAccepted,
expectedConsume: $expectedConsume,
expectedLimiterKey: $expectedKey,
expectedOutput: $expectedOutput,
requestStack: $requestStack
);
}

public static function provideRateLimitTemplatesUsingExpression(): array
{
$expression = new Expression('request.getClientIp()');

return [
['expression_key.twig', true, 1, $expression, 'expression_key: allowed'],
['expression_key.twig', false, 1, $expression, 'expression_key: denied'],
];
}

#[DataProvider('provideRateLimitTemplatesWithoutExpression')]
public function testRateLimiterWithoutExpression(
string $templateFile,
bool $isAccepted,
int|string $expectedConsume,
string $expectedKey,
string $expectedOutput,
): void {
$requestStack = new RequestStack();
$requestStack->push(Request::create('/'));

$this->doTestRateLimiter(
templateFile: $templateFile,
isAccepted: $isAccepted,
expectedConsume: $expectedConsume,
expectedLimiterKey: $expectedKey,
expectedOutput: $expectedOutput,
requestStack: $requestStack
);
}

public static function provideRateLimitTemplatesWithoutExpression(): array
{
return [
['custom_key.twig', true, 50, 'custom_key', 'custom_key: allowed'],
['custom_key.twig', false, 50, 'custom_key', 'custom_key: denied'],
['exceeded_limit.twig', false, 1, 'exceed_key', 'exceeded_limit: denied'],
['exceeded_limit.twig', true, 1, 'exceed_key', 'exceeded_limit: allowed'],
];
}

public function testRateLimiterThrowsIfServiceIsNotFactory()
{
$container = $this->createMock(ContainerInterface::class);
$container->method('get')
->with('limiter.invalid_service')
->willReturn(new \stdClass());

$requestStack = new RequestStack();
$requestStack->push(new Request());

$runtime = new RateLimiterRuntime($container, $requestStack);

$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The service "invalid_service" is not an instance of');

$runtime->rateLimit('invalid_service');
}

private function doTestRateLimiter(
string $templateFile,
bool $isAccepted,
int|string $expectedConsume,
int|string $expectedLimiterKey,
string $expectedOutput,
RequestStack $requestStack,
): void {
$rateLimit = $this->createMock(RateLimit::class);
$rateLimit->expects($this->once())
->method('isAccepted')
->willReturn($isAccepted);

$limiter = $this->createMock(LimiterInterface::class);
$limiter->expects($this->once())
->method('consume')
->with($expectedConsume)
->willReturn($rateLimit);

$factory = $this->createMock(RateLimiterFactoryInterface::class);
$factory->expects($this->once())
->method('create')
->with($expectedLimiterKey)
->willReturn($limiter);

$container = $this->createMock(ContainerInterface::class);
$container->expects($this->once())
->method('get')
->with('limiter.anonymous_api')
->willReturn($factory);

$runtime = new RateLimiterRuntime($container, $requestStack);
$twig = $this->createTwigEnvironment($runtime);

$templateCode = file_get_contents(__DIR__.'/Fixtures/templates/rate_limiter/'.$templateFile);
$twig->setLoader(new ArrayLoader(['template' => $templateCode]));

$this->assertSame($expectedOutput, trim($twig->render('template')));
}

private function createTwigEnvironment(RateLimiterRuntime $rateLimiterRuntime): Environment
{
$twig = new Environment(new ArrayLoader([]), ['debug' => true, 'cache' => false]);
$twig->addExtension(new RateLimiterExtension());
$twig->addExtension(new ExpressionExtension());

$loader = $this->createMock(RuntimeLoaderInterface::class);
$loader->method('load')
->willReturnMap([
[RateLimiterRuntime::class, $rateLimiterRuntime],
]);

$twig->addRuntimeLoader($loader);

return $twig;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Bridge/Twig/UndefinedCallableHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class UndefinedCallableHandler
'field_help' => 'form',
'field_errors' => 'form',
'field_choices' => 'form',
'rate_limit' => 'rate-limiter',
'logout_url' => 'security-http',
'logout_path' => 'security-http',
'is_granted' => 'security-core',
Expand Down
3 changes: 2 additions & 1 deletion src/Symfony/Bridge/Twig/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@
"symfony/workflow": "^6.4|^7.0|^8.0",
"twig/cssinliner-extra": "^3",
"twig/inky-extra": "^3",
"twig/markdown-extra": "^3"
"twig/markdown-extra": "^3",
"symfony/rate-limiter": "^7.3|^8.0"
},
"conflict": {
"phpdocumentor/reflection-docblock": "<3.2.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ class UnusedTagsPass implements CompilerPassInterface
'property_info.list_extractor',
'property_info.type_extractor',
'proxy',
'rate_limiter',
'remote_event.consumer',
'routing.condition_service',
'routing.expression_language_function',
Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Bundle/TwigBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
CHANGELOG
=========

7.4
---
* Add support for `rate_limit()` Twig function

7.3
---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Bundle\TwigBundle\DependencyInjection\Compiler;

use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Extension\RateLimiterExtension;
use Symfony\Component\Asset\Packages;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
Expand Down Expand Up @@ -146,5 +147,19 @@ public function process(ContainerBuilder $container): void
$container->getDefinition('twig.runtime.serializer')->addTag('twig.runtime');
$container->getDefinition('twig.extension.serializer')->addTag('twig.extension');
}

if (!$container->hasDefinition('cache.system')) {
$container->removeDefinition('cache.twig.runtime.rate_limiter_expression_language');
}

if ($container->has('limiter') && class_exists(RateLimiterExtension::class)) {
$container->getDefinition('twig.runtime.rate_limiter')->addTag('twig.runtime');
$container->getDefinition('twig.extension.rate_limiter')->addTag('twig.extension');
} else {
$container->removeDefinition('twig.runtime.rate_limiter');
$container->removeDefinition('twig.extension.rate_limiter');
$container->removeDefinition('cache.twig.runtime.rate_limiter_expression_language');
$container->removeDefinition('twig.runtime.rate_limiter_expression_language');
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,10 @@ public function load(array $configs, ContainerBuilder $container): void
}
}

if (!$container->hasDefinition('cache.system')) {
$container->removeDefinition('cache.twig.runtime.rate_limiter_expression_language');
}

if (isset($config['autoescape_service'])) {
$config['autoescape'] = [new Reference($config['autoescape_service']), $config['autoescape_service_method'] ?? '__invoke'];
} else {
Expand Down
Loading
Loading