8000 [HttpFoundation] `#[IsSignatureValid]` attribute by santysisi · Pull Request #60395 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[HttpFoundation] #[IsSignatureValid] attribute #60395

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.3
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
7 changes: 7 additions & 0 deletions src/Symfony/Bundle/SecurityBundle/Resources/config/security.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
use Symfony\Component\Security\Http\Controller\SecurityTokenValueResolver;
use Symfony\Component\Security\Http\Controller\UserValueResolver;
use Symfony\Component\Security\Http\EventListener\IsGrantedAttributeListener;
use Symfony\Component\Security\Http\EventListener\IsSignatureValidAttributeListener;
use Symfony\Component\Security\Http\Firewall;
use Symfony\Component\Security\Http\FirewallMapInterface;
use Symfony\Component\Security\Http\HttpUtils;
Expand Down Expand Up @@ -323,5 +324,11 @@
->set('cache.security_is_csrf_token_valid_attribute_expression_language')
->parent('cache.system')
->tag('cache.pool')

->set('controller.is_signature_valid_attribute_listener', IsSignatureValidAttributeListener::class)
->args([
service('uri_signer'),
])
->tag('kernel.event_subscriber')
;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?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;

use Symfony\Component\HttpFoundation\Response;

/**
* Attribute to ensure the request URI contains a valid signature before allowing controller execution.
*
* When applied, this attribute verifies that the request is signed and the signature is still valid (e.g., not expired).
* Behavior can be customized to either return a specific HTTP status code or throw an exception to be handled globally.
*
* @author Santiago San Martin <sanmartindev@gmail.com>
*/
#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)]
final class IsSignatureValid
{
/**
* @param int|null $validationFailedStatusCode The HTTP status code to return if the signature is invalid.
* Ignored when 'throw' is true. If null, error code 404 is used.
* @param bool|null $throw If true, an exception is thrown on signature failure instead of returning a response.
* Useful for global exception handling or listener-based workflows.
*/
public function __construct(
public ?int $validationFailedStatusCode = Response::HTTP_NOT_FOUND,
public ?bool $throw = null,
) {
}
}
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.4
---

* Add `#[IsSignatureValid]` attribute

7.3
---

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?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\HttpFoundation\UriSigner;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Http\Attribute\IsSignatureValid;

/**
* Handles the IsSignatureValid attribute.
*
* @author Santiago San Martin <sanmartindev@gmail.com>
*/
class IsSignatureValidAttributeListener implements EventSubscriberInterface
{
public function __construct(
private readonly UriSigner $uriSigner,
) {
}

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

$request = $event->getRequest();
foreach ($attributes as $attribute) {
if ($attribute->throw) {
$this->uriSigner->verify($request);
continue;
}
if (!$this->uriSigner->checkRequest($request)) {
throw new HttpException($attribute->validationFailedStatusCode, 'The URI signature is invalid.');
}
}
}

public static function getSubscribedEvents(): array
{
return [KernelEvents::CONTROLLER_ARGUMENTS => ['onKernelControllerArguments', 30]];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you explain this 30 why this value?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @94noni , thanks for your comment! ❤️

I set the priority to 30 because I want the IsSignatureValid validation to be executed first, before IsCsrfTokenValidAttributeListener and IsGrantedAttributeListener.
But maybe I'm wrong, and one of those validations should actually run first, please let me know if the priority needs to be changed.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i dont know on my side the proper priority but I wanted to know why you chose 30 that all
hope other review will confirm this choice :)

6D40 Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • IsCsrfTokenValidAttributeListener: priority 25
  • IsGrantedAttributeListener: priority 20

30 makes sense to me if we want it run first, which I think we do.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I too think it should run before any auth-related check that might open a session.

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
<?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\EventListener;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Exception\UnsignedUriException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Http\EventListener\IsSignatureValidAttributeListener;
use Symfony\Component\Security\Http\Tests\Fixtures\IsSignatureValidAttributeController;
use Symfony\Component\Security\Http\Tests\Fixtures\IsSignatureValidAttributeMethodsController;

class IsSignatureValidAttributeListenerTest extends TestCase
{
public function testInvokableControllerWithValidSignature()
{
$request = new Request();

/** @var UriSigner&MockObject $signer */
$signer = $this->createMock(UriSigner::class);
$signer->expects($this->once())->method('checkRequest')->with($request)->willReturn(true);

/** @var HttpKernelInterface&MockObject $kernel */
$kernel = $this->createMock(HttpKernelInterface::class);

$event = new ControllerArgumentsEvent(
$kernel,
new IsSignatureValidAttributeController(),
[],
$request,
null
);

$listener = new IsSignatureValidAttributeListener($signer);
$listener->onKernelControllerArguments($event);
}

public function testNoAttributeSkipsValidation()
{
/** @var UriSigner&MockObject $signer */
$signer = $this->createMock(UriSigner::class);
$signer->expects($this->never())->method('checkRequest');

/** @var HttpKernelInterface&MockObject $kernel */
$kernel = $this->createMock(HttpKernelInterface::class);

$event = new ControllerArgumentsEvent(
$kernel,
[new IsSignatureValidAttributeMethodsController(), 'noAttribute'],
[],
new Request(),
null
);

$listener = new IsSignatureValidAttributeListener($signer);
$listener->onKernelControllerArguments($event);
}

public function testDefaultCheckRequestSucceeds()
{
$request = new Request();
/** @var UriSigner&MockObject $signer */
$signer = $this->createMock(UriSigner::class);
$signer->expects($this->once())->method('checkRequest')->with($request)->willReturn(true);

/** @var HttpKernelInterface&MockObject $kernel */
$kernel = $this->createMock(HttpKernelInterface::class);

$event = new ControllerArgumentsEvent(
$kernel,
[new IsSignatureValidAttributeMethodsController(), 'withDefaultBehavior'],
[],
$request,
null
);

$listener = new IsSignatureValidAttributeListener($signer);
$listener->onKernelControllerArguments($event);
}

public function testCheckRequestFailsThrowsHttpException()
{
$request = new Request();
/** @var UriSigner&MockObject $signer */
$signer = $this->createMock(UriSigner::class);
$signer->expects($this->once())->method('checkRequest')->willReturn(false);

/** @var HttpKernelInterface&MockObject $kernel */
$kernel = $this->createMock(HttpKernelInterface::class);

$event = new ControllerArgumentsEvent(
$kernel,
[new IsSignatureValidAttributeMethodsController(), 'withDefaultBehavior'],
[],
$request,
null
);

$listener = new IsSignatureValidAttributeListener($signer);

try {
$listener->onKernelControllerArguments($event);
} catch (HttpException $e) {
$this->assertSame(404, $e->getStatusCode());
$this->assertSame('The URI signature is invalid.', $e->getMessage());
}
}

public function testVerifyThrowsCustomException()
{
$request = new Request();
$signer = new UriSigner('foobar');

/** @var HttpKernelInterface&MockObject $kernel */
$kernel = $this->createMock(HttpKernelInterface::class);

$event = new ControllerArgumentsEvent(
$kernel,
[new IsSignatureValidAttributeMethodsController(), 'withExceptionThrowing'],
[],
$request,
null
);

$listener = new IsSignatureValidAttributeListener($signer);

$this->expectException(UnsignedUriException::class);
$listener->onKernelControllerArguments($event);
}

public function testCustomStatusCodeReturnedOnInvalidSignature()
{
$request = new Request();

/** @var UriSigner&MockObject $signer */
$signer = $this->createMock(UriSigner::class);
$signer->expects($this->once())->method('checkRequest')->with($request)->willReturn(false);

/** @var HttpKernelInterface&MockObject $kernel */
$kernel = $this->createMock(HttpKernelInterface::class);

$event = new ControllerArgumentsEvent(
$kernel,
[new IsSignatureValidAttributeMethodsController(), 'withCustomStatusCode'],
[],
$request,
null
);

$listener = new IsSignatureValidAttributeListener($signer);

try {
$listener->onKernelControllerArguments($event);
} catch (HttpException $e) {
$this->assertSame(401, $e->getStatusCode());
$this->assertSame('The URI signature is invalid.', $e->getMessage());
}
10000 }

public function testWithThrowAndCustomStatusFails()
{
$request = new Request();
$signer = new UriSigner('foobar');

/** @var HttpKernelInterface&MockObject $kernel */
$kernel = $this->createMock(HttpKernelInterface::class);

$event = new ControllerArgumentsEvent(
$kernel,
[new IsSignatureValidAttributeMethodsController(), 'withThrowAndCustomStatus'],
[],
$request,
null
);

$listener = new IsSignatureValidAttributeListener($signer);

$this->expectException(UnsignedUriException::class);
$listener->onKernelControllerArguments($event);
}

public function testWithExplicitNoThrowIgnoresSignatureFailure()
{
$request = new Request();

/** @var UriSigner&MockObject $signer */
$signer = $this->createMock(UriSigner::class);
$signer->expects($this->once())->method('checkRequest')->with($request)->willReturn(false);

/** @var HttpKernelInterface&MockObject $kernel */
$kernel = $this->createMock(HttpKernelInterface::class);

$event = new ControllerArgumentsEvent(
$kernel,
[new IsSignatureValidAttributeMethodsController(), 'withExplicitNoThrow'],
[],
$request,
null
);

$listener = new IsSignatureValidAttributeListener($signer);
$this->expectException(HttpException::class);
$listener->onKernelControllerArguments($event);
}

public function testMultipleAttributesAllValid()
{
$request = new Request();

/** @var UriSigner&MockObject $signer */
$signer = $this->createMock(UriSigner::class);
$signer->expects($this->exactly(2))->method('checkRequest')->with($request)->willReturn(true);

/** @var HttpKernelInterface&MockObject $kernel */
$kernel = $this->createMock(HttpKernelInterface::class);

$event = new ControllerArgumentsEvent(
$kernel,
[new IsSignatureValidAttributeMethodsController(), 'withMultiple'],
[],
$request,
null
);

$listener = new IsSignatureValidAttributeListener($signer);
$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\IsSignatureValid;

#[IsSignatureValid]
class IsSignatureValidAttributeController
{
public function __invoke()
{
}
}
Loading
Loading
0