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

Skip to content

[HttpFoundation] Add #[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.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
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
use Symfony\Component\Routing\DependencyInjection\RoutingResolverPass;
use Symfony\Component\Runtime\SymfonyRuntime;
use Symfony\Component\Scheduler\DependencyInjection\AddScheduleMessengerPass;
use Symfony\Component\Security\Http\DependencyInjection\UriSignerLocatorPass;
use Symfony\Component\Serializer\DependencyInjection\SerializerPass;
use Symfony\Component\Translation\DependencyInjection\DataCollectorTranslatorPass;
use Symfony\Component\Translation\DependencyInjection\LoggingTranslatorPass;
Expand Down Expand Up @@ -192,6 +193,7 @@ public function build(ContainerBuilder $container): void
$container->addCompilerPass(new VirtualRequestStackPass());
$container->addCompilerPass(new TranslationUpdateCommandPass(), PassConfig::TYPE_BEFORE_REMOVING);
$this->addCompilerPassIfExists($container, StreamablePass::class);
$this->addCompilerPassIfExists($container, UriSignerLocatorPass::class);

if ($container->getParameter('kernel.debug')) {
$container->addCompilerPass(new AddDebugLogProcessorPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 2);
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpFoundation/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Deprecate using `Request::sendHeaders()` after headers have already been sent; use a `StreamedResponse` instead
* Add `#[WithHttpStatus]` to define status codes: 404 for `SignedUriException` and 403 for `ExpiredSignedUriException`

7.3
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@

namespace Symfony\Component\HttpFoundation\Exception;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\WithHttpStatus;

/**
* @author Kevin Bond <kevinbond@gmail.com>
*/
#[WithHttpStatus(Response::HTTP_FORBIDDEN)]
final class ExpiredSignedUriException extends SignedUriException
{
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@

namespace Symfony\Component\HttpFoundation\Exception;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\WithHttpStatus;

/**
* @author Kevin Bond <kevinbond@gmail.com>
*/
#[WithHttpStatus(Response::HTTP_NOT_FOUND)]
abstract class SignedUriException extends \RuntimeException implements ExceptionInterface
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?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\UriSigner;

/**
* Validates the request signature for specific HTTP methods.
*
* This class determines whether a request's signature should be validated
* based on the configured HTTP methods. If the request method matches one
* of the specified methods (or if no methods are specified), the signature
* is checked.
*
* If the signature is invalid, a {@see \Symfony\Component\HttpFoundation\Exception\SignedUriException}
* is thrown during validation.
*
* @author Santiago San Martin <sanmartindev@gmail.com>
*/
#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)]
final class IsSignatureValid
{
public readonly array $methods;
public readonly string $signer;

/**
* @param string[]|string $methods HTTP methods that require signature validation. An empty array means that no method filtering is done
* @param string $signer The ID of the UriSigner service to use for signature validation. Defaults to 'uri_signer'
*/
public function __construct(
array|string $methods = [],
string $signer = 'uri_signer',
) {
if (!method_exists(UriSigner::class, 'verify')) {
throw new \LogicException('The `IsSignatureValid` attribute requires symfony/http-foundation >= 7.3.');
}

$this->methods = (array) $methods;
$this->signer = $signer;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Security/Http/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Deprecate callable firewall listeners, extend `AbstractListener` or implement `FirewallListenerInterface` instead
* Deprecate `AbstractListener::__invoke`
* Add `#[IsSignatureValid]` attribute to validate URI signatures

7.3
---
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?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\DependencyInjection;

use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\Security\Http\EventListener\IsSignatureValidAttributeListener;

/**
* Registers all UriSigner services in a service locator and injects it into the IsSignatureValidAttributeListener for dynamic signer resolution.
*
* @author Santiago San Martin <sanmartindev@gmail.com>
*/
class UriSignerLocatorPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
$locateableServices = [];
foreach ($container->getDefinitions() as $id => $definition) {
if (UriSigner::class === $definition->getClass()) {
$locateableServices[$id] = new Reference($id);
}
}

8000 $container
->register('controller.is_signature_valid_attribute_listener', IsSignatureValidAttributeListener::class)
->addTag('kernel.event_subscriber')
->setBindings([
ContainerInterface::class => ServiceLocatorTagPass::register($container, $locateableServices),
]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?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 Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
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 ContainerInterface $container,
) {
}

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

$request = $event->getRequest();
foreach ($attributes as $attribute) {
$methods = array_map('strtoupper', $attribute->methods);
if ($methods && !\in_array($request->getMethod(), $methods, true)) {
continue;
}

$signer = $this->container->get($attribute->signer);
if (!$signer instanceof UriSigner) {
throw new \LogicException(\sprintf('The service "%s" is not an instance of "%s".', $attribute->signer, UriSigner::class));
}

$signer->verify($request);
}
}

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

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\Security\Http\DependencyInjection\UriSignerLocatorPass;

class UriSignerLocatorPassTest extends TestCase
{
public function testSetUriSignerLocator()
{
$container = new ContainerBuilder();

$container->register('controller.is_signature_valid_attribute_listener');

$container->register('UriSignerOne')->setClass(UriSigner::class);
$container->register('UriSignerTwo')->setClass(UriSigner::class);
$container->register('UriSignerThree')->setClass(UriSigner::class);
$container->register('One')->setClass('Foo');
$container->register('Two')->setClass('Bar');
$container->register('Three')->setClass('Baz');

$pass = new UriSignerLocatorPass();
$pass->process($container);

$id = (string) $container->getDefinition('controller.is_signature_valid_attribute_listener')->getBindings()[ContainerInterface::class]->getValues()[0];
$arguments = $container->getDefinition($id)->getArguments()[0];

$this->assertCount(3, $arguments);
$this->assertArrayHasKey('UriSignerOne', $arguments);
$this->assertArrayHasKey('UriSignerTwo', $arguments);
$this->assertArrayHasKey('UriSignerThree', $arguments);
}
}
Loading
Loading
0