8000 [RFC][HttpKernel][Security] Allowed adding attributes on controller arguments that will be passed to argument resolvers. by jvasseur · Pull Request #37829 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[RFC][HttpKernel][Security] Allowed adding attributes on controller arguments that will be passed to argument resolvers. #37829

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
Sep 12, 2020
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
19 changes: 19 additions & 0 deletions src/Symfony/Component/HttpKernel/Attribute/ArgumentInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?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\HttpKernel\Attribute;

/**
* Marker interface for controller argument attributes.
*/
interface ArgumentInterface
{
}
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ CHANGELOG
`kernel.trusted_proxies` and `kernel.trusted_headers` parameters
* content of request parameter `_password` is now also hidden
in the request profiler raw content section
* Allowed adding attributes on controller arguments that will be passed to argument resolvers.

5.1.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\HttpKernel\ControllerMetadata;

use Symfony\Component\HttpKernel\Attribute\ArgumentInterface;

/**
* Responsible for storing metadata of an argument.
*
Expand All @@ -24,15 +26,17 @@ class ArgumentMetadata
private $hasDefaultValue;
private $defaultValue;
private $isNullable;
private $attribute;

public function __construct(string $name, ?string $type, bool $isVariadic, bool $hasDefaultValue, $defaultValue, bool $isNullable = false)
public function __construct(string $name, ?string $type, bool $isVariadic, bool $hasDefaultValue, $defaultValue, bool $isNullable = false, ?ArgumentInterface $attribute = null)
{
$this->name = $name;
$this->type = $type;
$this->isVariadic = $isVariadic;
$this->hasDefaultValue = $hasDefaultValue;
$this->defaultValue = $defaultValue;
$this->isNullable = $isNullable || null === $type || ($hasDefaultValue && null === $defaultValue);
$this->attribute = $attribute;
}

/**
Expand Down Expand Up @@ -104,4 +108,12 @@ public function getDefaultValue()

return $this->defaultValue;
}

/**
* Returns the attribute (if any) that was set on the argument.
*/
public function getAttribute(): ?ArgumentInterface
{
return $this->attribute;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

namespace Symfony\Component\HttpKernel\ControllerMetadata;

use Symfony\Component\HttpKernel\Attribute\ArgumentInterface;
use Symfony\Component\HttpKernel\Exception\InvalidMetadataException;

/**
* Builds {@see ArgumentMetadata} objects based on the given Controller.
*
Expand All @@ -34,7 +37,28 @@ public function createArgumentMetadata($controller): array
}

foreach ($reflection->getParameters() as $param) {
$arguments[] = new ArgumentMetadata($param->getName(), $this->getType($param, $reflection), $param->isVariadic(), $param->isDefaultValueAvailable(), $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull());
$attribute = null;
if (method_exists($param, 'getAttributes')) {
$reflectionAttributes = $param->getAttributes(ArgumentInterface::class, \ReflectionAttribute::IS_INSTANCEOF);

if (\count($reflectionAttributes) > 1) {
$representative = $controller;

if (\is_array($representative)) {
$representative = sprintf('%s::%s()', \get_class($representative[0]), $representative[1]);
} elseif (\is_object($representative)) {
$representative = \get_class($representative);
}

throw new InvalidMetadataException(sprintf('Controller "%s" has more than one attribute for "$%s" argument.', $representative, $param->getName()));
}

if (isset($reflectionAttributes[0])) {
$attribute = $reflectionAttributes[0]->newInstance();
}
}

$arguments[] = new ArgumentMetadata($param->getName(), $this->getType($param, $reflection), $param->isVariadic(), $param->isDefaultValueAvailable(), $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull(), $attribute);
}

return $arguments;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?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\HttpKernel\Exception;

class InvalidMetadataException extends \LogicException
{
}
Original file line number Diff line number Diff line change
Expand Up @@ - 9E88 15,6 +15,9 @@
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory;
use Symfony\Component\HttpKernel\Exception\InvalidMetadataException;
use Symfony\Component\HttpKernel\Tests\Fixtures\Attribute\Foo;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\AttributeController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\BasicTypesController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\NullableController;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
Expand Down Expand Up @@ -117,6 +120,28 @@ public function testNullableTypesSignature()
], $arguments);
}

/**
* @requires PHP 8
*/
public function testAttributeSignature()
{
$arguments = $this->factory->createArgumentMetadata([new AttributeController(), 'action']);

$this->assertEquals([
new ArgumentMetadata('baz', 'string', false, false, null, false, new Foo('bar')),
], $arguments);
}

/**
* @requires PHP 8
*/
public function testAttributeSignatureError()
{
$this->expectException(InvalidMetadataException::class);

$this->factory->createArgumentMetadata([new AttributeController(), 'invalidAction']);
}

private function signature1(self $foo, array $bar, callable $baz)
{
}
Expand Down
26 changes: 26 additions & 0 deletions src/Symfony/Component/HttpKernel/Tests/Fixtures/Attribute/Foo.php
F438
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?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\HttpKernel\Tests\Fixtures\Attribute;

use Attribute;
use Symfony\Component\HttpKernel\Attribute\ArgumentInterface;

#[Attribute(Attribute::TARGET_PARAMETER)]
class Foo implements ArgumentInterface
{
private $foo;

public function __construct($foo)
{
$this->foo = $foo;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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\HttpKernel\Tests\Fixtures\Controller;

use Symfony\Component\HttpKernel\Tests\Fixtures\Attribute\Foo;

class AttributeController
{
public function action(#[Foo('bar')] string $baz) {
}

public function invalidAction(#[Foo('bar'), Foo('bar')] string $baz) {
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Security/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ CHANGELOG
* Deprecated `setProviderKey()`/`getProviderKey()` in favor of `setFirewallName()/getFirewallName()` in `PreAuthenticatedToken`, `RememberMeToken`, `SwitchUserToken`, `UsernamePasswordToken`, `DefaultAuthenticationSuccessHandler`; and deprecated the `AbstractRememberMeServices::$providerKey` property in favor of `AbstractRememberMeServices::$firewallName`
* Added `FirewallListenerInterface` to make the execution order of firewall listeners configurable
* Added translator to `\Symfony\Component\Security\Http\Authenticator\JsonLoginAuthenticator` and `\Symfony\Component\Security\Http\Firewall\UsernamePasswordJsonAuthenticationListener` to translate authentication failure messages
* Added a CurrentUser attribute to force the UserValueResolver to resolve an argument to the current user.

5.1.0
-----
Expand Down
23 changes: 23 additions & 0 deletions src/Symfony/Component/Security/Http/Attribute/CurrentUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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 Attribute;
use Symfony\Component\HttpKernel\Attribute\ArgumentInterface;

/**
* Indicates that a controller argument should receive the current logged user.
*/
#[Attribute(Attribute::TARGET_PARAMETER)]
class CurrentUser implements ArgumentInterface
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

/**
* Supports the argument type of {@see UserInterface}.
Expand All @@ -34,6 +35,10 @@ public function __construct(TokenStorageInterface $tokenStorage)

public function supports(Request $request, ArgumentMetadata $argument): bool
{
if ($argument->getAttribute() instanceof CurrentUser) {
return true;
}

// only security user implementations are supported
if (UserInterface::class !== $argument->getType()) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Controller\UserValueResolver;

class UserValueResolverTest extends TestCase
Expand Down Expand Up @@ -68,6 +69,20 @@ public function testResolve()
$this->assertSame([$user], iterator_to_array($resolver->resolve(Request::create('/'), $metadata)));
}

public function testResolveWithAttribute()
{
$user = $this->getMockBuilder(UserInterface::class)->getMock();
$token = new UsernamePasswordToken($user, 'password', 'provider');
$tokenStorage = new TokenStorage();
$tokenStorage->setToken($token);

$resolver = new UserValueResolver($tokenStorage);
$metadata = new ArgumentMetadata('foo', null, false, false, null, false, new CurrentUser());

$this->assertTrue($resolver->supports(Request::create('/'), $metadata));
$this->assertSame([$user], iterator_to_array($resolver->resolve(Request::create('/'), $metadata)));
}

public function testIntegration()
{
$user = $this->getMockBuilder(UserInterface::class)->getMock();
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Security/Http/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"symfony/deprecation-contracts": "^2.1",
"symfony/security-core": "^5.2",
"symfony/http-foundation": "^4.4.7|^5.0.7",
"symfony/http-kernel": "^4.4|^5.0",
"symfony/http-kernel": "^5.2",
"symfony/polyfill-php80": "^1.15",
"symfony/property-access": "^4.4|^5.0"
},
Expand Down
0