Skip to content

[Security][SecurityBundle] Add #[IsCsrfTokenValid] attribute #52961

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

Merged
merged 1 commit into from
Dec 9, 2023
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\Security\Csrf\TokenStorage\ClearableTokenStorageInterface;
use Symfony\Component\Security\Http\EventListener\CsrfProtectionListener;
use Symfony\Component\Security\Http\EventListener\CsrfTokenClearingLogoutListener;
use Symfony\Component\Security\Http\EventListener\IsCsrfTokenValidAttributeListener;

/**
* @author Christian Flothmann <christian.flothmann@sensiolabs.de>
Expand All @@ -41,6 +42,10 @@ private function registerCsrfProtectionListener(ContainerBuilder $container): vo
$container->register('security.listener.csrf_protection', CsrfProtectionListener::class)
->addArgument(new Reference('security.csrf.token_manager'))
->addTag('kernel.event_subscriber');

$container->register('controller.is_csrf_token_valid_attribute_listener', IsCsrfTokenValidAttributeListener::class)
->addArgument(new Reference('security.csrf.token_manager'))
->addTag('kernel.event_subscriber');
}

protected function registerLogoutHandler(ContainerBuilder $container): void
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/SecurityBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"symfony/password-hasher": "^6.4|^7.0",
"symfony/security-core": "^6.4|^7.0",
"symfony/security-csrf": "^6.4|^7.0",
"symfony/security-http": "^6.4|^7.0",
"symfony/security-http": "^7.1",
"symfony/service-contracts": "^2.5|^3"
},
"require-dev": {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?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\Component\Security\Http\Attribute;

#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)]
final class IsCsrfTokenValid
{
public function __construct(
/**
* Sets the id used when generating the token.
*/
public string $id,

/**
* Sets the key of the request that contains the actual token value that should be validated.
*/
public ?string $tokenKey = '_token',
) {
}
}
5 changes: 5 additions & 0 deletions src/Symfony/Component/Security/Http/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.1
---

* Add `#[IsCsrfTokenValid]` attribute

7.0
---

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?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\Component\Security\Http\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;

/**
* Handles the IsCsrfTokenValid attribute on controllers.
*/
final class IsCsrfTokenValidAttributeListener implements EventSubscriberInterface
{
public function __construct(
private readonly CsrfTokenManagerInterface $csrfTokenManager,
) {
}

public function onKernelControllerArguments(ControllerArgumentsEvent $event): void
{
/** @var IsCsrfTokenValid[] $attributes */
if (!\is_array($attributes = $event->getAttributes()[IsCsrfTokenValid::class] ?? null)) {
return;
}

$request = $event->getRequest();

foreach ($attributes as $attribute) {
if (!$this->csrfTokenManager->isTokenValid(new CsrfToken($attribute->id, $request->request->getString($attribute->tokenKey)))) {
throw new InvalidCsrfTokenException('Invalid CSRF token.');
}
}
}

public static function getSubscribedEvents(): array
{
return [KernelEvents::CONTROLLER_ARGUMENTS => ['onKernelControllerArguments', 25]];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
<?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 EventListener;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Http\EventListener\IsCsrfTokenValidAttributeListener;
use Symfony\Component\Security\Http\Tests\Fixtures\IsCsrfTokenValidAttributeController;
use Symfony\Component\Security\Http\Tests\Fixtures\IsCsrfTokenValidAttributeMethodsController;

class IsCsrfTokenValidAttributeListenerTest extends TestCase
{
public function testIsCsrfTokenValidCalledCorrectlyOnInvokableClass()
{
$request = new Request(request: ['_token' => 'bar']);

$csrfTokenManager = $this->createMock(CsrfTokenManagerInterface::class);
$csrfTokenManager->expects($this->once())
->method('isTokenValid')
->with(new CsrfToken('foo', 'bar'))
->willReturn(true);

$event = new ControllerArgumentsEvent(
$this->createMock(HttpKernelInterface::class),
new IsCsrfTokenValidAttributeController(),
[],
$request,
null
);

$listener = new IsCsrfTokenValidAttributeListener($csrfTokenManager);
$listener->onKernelControllerArguments($event);
}

public function testNothingHappensWithNoConfig()
{
$csrfTokenManager = $this->createMock(CsrfTokenManagerInterface::class);
$csrfTokenManager->expects($this->never())
->method('isTokenValid');

$event = new ControllerArgumentsEvent(
$this->createMock(HttpKernelInterface::class),
[new IsCsrfTokenValidAttributeMethodsController(), 'noAttribute'],
[],
new Request(),
null
);

$listener = new IsCsrfTokenValidAttributeListener($csrfTokenManager);
$listener->onKernelControllerArguments($event);
}

public function testIsCsrfTokenValidCalledCorrectly()
{
$request = new Request(request: ['_token' => 'bar']);

$csrfTokenManager = $this->createMock(CsrfTokenManagerInterface::class);
$csrfTokenManager->expects($this->once())
->method('isTokenValid')
->with(new CsrfToken('foo', 'bar'))
->willReturn(true);

$event = new ControllerArgumentsEvent(
$this->createMock(HttpKernelInterface::class),
[new IsCsrfTokenValidAttributeMethodsController(), 'withDefaultTokenKey'],
[],
$request,
null
);

$listener = new IsCsrfTokenValidAttributeListener($csrfTokenManager);
$listener->onKernelControllerArguments($event);
}

public function testIsCsrfTokenValidCalledCorrectlyWithCustomTokenKey()
{
$request = new Request(request: ['my_token_key' => 'bar']);

$csrfTokenManager = $this->createMock(CsrfTokenManagerInterface::class);
$csrfTokenManager->expects($this->once())
->method('isTokenValid')
->with(new CsrfToken('foo', 'bar'))
->willReturn(true);

$event = new ControllerArgumentsEvent(
$this->createMock(HttpKernelInterface::class),
[new IsCsrfTokenValidAttributeMethodsController(), 'withCustomTokenKey'],
[],
$request,
null
);

$listener = new IsCsrfTokenValidAttributeListener($csrfTokenManager);
$listener->onKernelControllerArguments($event);
}

public function testIsCsrfTokenValidCalledCorrectlyWithInvalidTokenKey()
{
$request = new Request(request: ['_token' => 'bar']);

$csrfTokenManager = $this->createMock(CsrfTokenManagerInterface::class);
$csrfTokenManager->expects($this->once())
->method('isTokenValid')
->with(new CsrfToken('foo', ''))
->willReturn(true);

$event = new ControllerArgumentsEvent(
$this->createMock(HttpKernelInterface::class),
[new IsCsrfTokenValidAttributeMethodsController(), 'withInvalidTokenKey'],
[],
$request,
null
);

$listener = new IsCsrfTokenValidAttributeListener($csrfTokenManager);
$listener->onKernelControllerArguments($event);
}

public function testExceptionWhenInvalidToken()
{
$this->expectException(InvalidCsrfTokenException::class);

$csrfTokenManager = $this->createMock(CsrfTokenManagerInterface::class);
$csrfTokenManager->expects($this->once())
->method('isTokenValid')
->withAnyParameters()
->willReturn(false);

$event = new ControllerArgumentsEvent(
$this->createMock(HttpKernelInterface::class),
[new IsCsrfTokenValidAttributeMethodsController(), 'withDefaultTokenKey'],
[],
new Request(),
null
);

$listener = new IsCsrfTokenValidAttributeListener($csrfTokenManager);
$listener->onKernelControllerArguments($event);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?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\Component\Security\Http\Tests\Fixtures;

use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;

#[IsCsrfTokenValid('foo')]
class IsCsrfTokenValidAttributeController
{
public function __invoke()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?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\Component\Security\Http\Tests\Fixtures;

use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;

class IsCsrfTokenValidAttributeMethodsController
{
public function noAttribute()
{
}

#[IsCsrfTokenValid('foo')]
public function withDefaultTokenKey()
{
}

#[IsCsrfTokenValid('foo', tokenKey: 'my_token_key')]
public function withCustomTokenKey()
{
}

#[IsCsrfTokenValid('foo', tokenKey: 'invalid_token_key')]
public function withInvalidTokenKey()
{
}
}