-
-
Notifications
You must be signed in to change notification settings - Fork 939
feat(symfony): isGranted before provider #7500
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the API Platform project. | ||
| * | ||
| * (c) Kévin Dunglas <[email protected]> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace ApiPlatform\Symfony\Security; | ||
|
|
||
| interface ObjectVariableCheckerInterface | ||
| { | ||
| /** | ||
| * @param string $expression a Expression Language string | ||
| * @param array<string, mixed> $variables | ||
| */ | ||
| public function usesObjectVariable(string $expression, array $variables = []): bool; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,6 +15,8 @@ | |
|
|
||
| use ApiPlatform\Metadata\ResourceAccessCheckerInterface; | ||
| use Symfony\Component\ExpressionLanguage\ExpressionLanguage; | ||
| use Symfony\Component\ExpressionLanguage\Node\NameNode; | ||
| use Symfony\Component\ExpressionLanguage\Node\Node; | ||
| use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface; | ||
| use Symfony\Component\Security\Core\Authentication\Token\NullToken; | ||
| use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; | ||
|
|
@@ -27,7 +29,7 @@ | |
| * | ||
| * @author Kévin Dunglas <[email protected]> | ||
| */ | ||
| final class ResourceAccessChecker implements ResourceAccessCheckerInterface | ||
| final class ResourceAccessChecker implements ResourceAccessCheckerInterface, ObjectVariableCheckerInterface | ||
| { | ||
| public function __construct(private readonly ?ExpressionLanguage $expressionLanguage = null, private readonly ?AuthenticationTrustResolverInterface $authenticationTrustResolver = null, private readonly ?RoleHierarchyInterface $roleHierarchy = null, private readonly ?TokenStorageInterface $tokenStorage = null, private readonly ?AuthorizationCheckerInterface $authorizationChecker = null) | ||
| { | ||
|
|
@@ -43,32 +45,32 @@ public function isGranted(string $resourceClass, string $expression, array $extr | |
| throw new \LogicException('The "symfony/expression-language" library must be installed to use the "security" attribute.'); | ||
| } | ||
|
|
||
| $variables = array_merge($extraVariables, [ | ||
| 'trust_resolver' => $this->authenticationTrustResolver, | ||
| 'auth_checker' => $this->authorizationChecker, // needed for the is_granted expression function | ||
| ]); | ||
|
|
||
| if (null === $token = $this->tokenStorage->getToken()) { | ||
| $token = new NullToken(); | ||
| } | ||
|
|
||
| $variables = array_merge($variables, $this->getVariables($token)); | ||
| return (bool) $this->expressionLanguage->evaluate($expression, $this->getVariables($extraVariables)); | ||
| } | ||
|
|
||
| return (bool) $this->expressionLanguage->evaluate($expression, $variables); | ||
| public function usesObjectVariable(string $expression, array $variables = []): bool | ||
| { | ||
| return $this->hasObjectVariable($this->expressionLanguage->parse($expression, array_keys($this->getVariables($variables)))->getNodes()->toArray()); | ||
| } | ||
|
|
||
| /** | ||
| * @copyright Fabien Potencier <[email protected]> | ||
| * | ||
| * @see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Core/Authorization/Voter/ExpressionVoter.php | ||
| */ | ||
| private function getVariables(TokenInterface $token): array | ||
| private function getVariables(array $variables): array | ||
| { | ||
| return [ | ||
| if (null === $token = $this->tokenStorage->getToken()) { | ||
| $token = new NullToken(); | ||
| } | ||
|
|
||
| return array_merge($variables, [ | ||
| 'token' => $token, | ||
| 'user' => $token->getUser(), | ||
| 'roles' => $this->getEffectiveRoles($token), | ||
| ]; | ||
| 'trust_resolver' => $this->authenticationTrustResolver, | ||
| 'auth_checker' => $this->authorizationChecker, // needed for the is_granted expression function | ||
| ]); | ||
| } | ||
|
|
||
| /** | ||
|
|
@@ -82,4 +84,44 @@ private function getEffectiveRoles(TokenInterface $token): array | |
|
|
||
| return $this->roleHierarchy->getReachableRoleNames($token->getRoleNames()); | ||
| } | ||
|
|
||
| /** | ||
| * Recursively checks if a variable named 'object' is present in the expression AST. | ||
| * | ||
| * @param Node|array<mixed>|null $nodeOrNodes the ExpressionLanguage Node instance or an array of nodes/values | ||
| */ | ||
| private function hasObjectVariable(Node|array|null $nodeOrNodes): bool | ||
| { | ||
| if ($nodeOrNodes instanceof NameNode) { | ||
| if ('object' === $nodeOrNodes->attributes['name'] || 'previous_object' === $nodeOrNodes->attributes['name']) { | ||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| if ($nodeOrNodes instanceof Node) { | ||
| foreach ($nodeOrNodes->nodes as $childNode) { | ||
| if ($this->hasObjectVariable($childNode)) { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| if (\is_array($nodeOrNodes)) { | ||
| foreach ($nodeOrNodes as $element) { | ||
| if (\is_string($element)) { | ||
| continue; | ||
| } | ||
|
|
||
| if ($this->hasObjectVariable($element)) { | ||
| return true; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -21,6 +21,7 @@ | |||||
| use ApiPlatform\Metadata\ResourceAccessCheckerInterface; | ||||||
| use ApiPlatform\State\ProviderInterface; | ||||||
| use ApiPlatform\Symfony\Security\Exception\AccessDeniedException; | ||||||
| use ApiPlatform\Symfony\Security\ObjectVariableCheckerInterface; | ||||||
| use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; | ||||||
|
|
||||||
| /** | ||||||
|
|
@@ -59,15 +60,15 @@ public function provide(Operation $operation, array $uriVariables = [], array $c | |||||
| $message = $operation->getSecurityMessage(); | ||||||
| } | ||||||
|
|
||||||
| $body = $this->decorated->provide($operation, $uriVariables, $context); | ||||||
| if (null === $isGranted) { | ||||||
| return $body; | ||||||
| if ( | ||||||
| null === $isGranted | ||||||
| // On a GraphQl QueryCollection we want to perform security stage only on the top-level query | ||||||
| || ($operation instanceof QueryCollection && null !== ($context['source'] ?? null)) | ||||||
| ) { | ||||||
| return $this->decorated->provide($operation, $uriVariables, $context); | ||||||
| } | ||||||
|
|
||||||
| // On a GraphQl QueryCollection we want to perform security stage only on the top-level query | ||||||
| if ($operation instanceof QueryCollection && null !== ($context['source'] ?? null)) { | ||||||
| return $body; | ||||||
| } | ||||||
| $body = 'pre_read' === $this->event ? null : $this->decorated->provide($operation, $uriVariables, $context); | ||||||
|
|
||||||
| if ($operation instanceof HttpOperation) { | ||||||
| $request = $context['request'] ?? null; | ||||||
|
|
@@ -84,10 +85,14 @@ public function provide(Operation $operation, array $uriVariables = [], array $c | |||||
| ]; | ||||||
| } | ||||||
|
|
||||||
| if ('pre_read' === $this->event && $this->resourceAccessChecker instanceof ObjectVariableCheckerInterface && $this->resourceAccessChecker->usesObjectVariable($isGranted, $resourceAccessCheckerContext)) { | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also, there is likely a missing test, because the missing use statement hasn't been caught. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. it did fail on behat :) |
||||||
| return $this->decorated->provide($operation, $uriVariables, $context); | ||||||
| } | ||||||
|
|
||||||
| if (!$this->resourceAccessChecker->isGranted($operation->getClass(), $isGranted, $resourceAccessCheckerContext)) { | ||||||
| $operation instanceof GraphQlOperation ? throw new AccessDeniedHttpException($message ?? 'Access Denied.') : throw new AccessDeniedException($message ?? 'Access Denied.'); | ||||||
| } | ||||||
|
|
||||||
| return $body; | ||||||
| return 'pre_read' === $this->event ? $this->decorated->provide($operation, $uriVariables, $context) : $body; | ||||||
soyuka marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
| } | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the API Platform project. | ||
| * | ||
| * (c) Kévin Dunglas <[email protected]> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource; | ||
|
|
||
| use ApiPlatform\Metadata\ApiResource; | ||
| use ApiPlatform\Metadata\Get; | ||
| use ApiPlatform\Metadata\Operation; | ||
|
|
||
| #[ApiResource( | ||
| operations: [ | ||
| new Get(uriTemplate: 'is_granted_tests/{id}', security: 'is_granted("ROLE_ADMIN")', uriVariables: ['id'], provider: [self::class, 'provide']), | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is the test really working? Because I expected There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes this test is working, when no There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Okay, that's on me then. I expected the test to work a little bit differently and I was looking for tests both with and without object in security to see that it behaves correctly in all cases There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh we already have a bunch of tests with |
||
| new Get(uriTemplate: 'is_granted_test_call_provider/{id}', uriVariables: ['id'], security: 'is_granted("ROLE_ADMIN")', provider: [self::class, 'provideShouldNotBeCalled']), | ||
| ] | ||
| )] | ||
| class IsGrantedTestResource | ||
| { | ||
| private ?int $id = null; | ||
|
|
||
| public function getId(): ?int | ||
| { | ||
| return $this->id; | ||
| } | ||
|
|
||
| public static function provide(Operation $operation, array $uriVariables = [], array $context = []) | ||
| { | ||
| return new self(); | ||
| } | ||
|
|
||
| public static function provideShouldNotBeCalled(Operation $operation, array $uriVariables = [], array $context = []) | ||
| { | ||
| throw new \RuntimeException('provider should not get called'); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the API Platform project. | ||
| * | ||
| * (c) Kévin Dunglas <[email protected]> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace ApiPlatform\Tests\Functional; | ||
|
|
||
| use ApiPlatform\Symfony\Bundle\Test\ApiTestCase; | ||
| use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\IsGrantedTestResource; | ||
| use ApiPlatform\Tests\SetupClassResourcesTrait; | ||
| use Symfony\Component\Security\Core\User\InMemoryUser; | ||
|
|
||
| final class IsGrantedTest extends ApiTestCase | ||
| { | ||
| use SetupClassResourcesTrait; | ||
|
|
||
| protected static ?bool $alwaysBootKernel = false; | ||
|
|
||
| /** | ||
| * @return class-string[] | ||
| */ | ||
| public static function getResources(): array | ||
| { | ||
| return [IsGrantedTestResource::class]; | ||
| } | ||
|
|
||
| public function testGetIsGrantedAsAdmin(): void | ||
| { | ||
| $client = self::createClient(); | ||
| $client->loginUser(new InMemoryUser('admin', 'password', ['ROLE_ADMIN'])); | ||
|
|
||
| $client->request('GET', '/is_granted_tests/1'); | ||
| $this->assertResponseIsSuccessful(); | ||
| } | ||
|
|
||
| public function testGetIsGrantedAsUser(): void | ||
| { | ||
| $client = self::createClient(); | ||
| $client->loginUser(new InMemoryUser('user', 'password', ['ROLE_USER'])); | ||
|
|
||
| $client->request('GET', '/is_granted_tests/1'); | ||
| $this->assertResponseStatusCodeSame(403); | ||
| } | ||
|
|
||
| public function testGetIsGrantedAsAnonymous(): void | ||
| { | ||
| $client = self::createClient(); | ||
|
|
||
| $client->request('GET', '/is_granted_tests/1'); | ||
| $this->assertResponseStatusCodeSame(401); | ||
| } | ||
|
|
||
| public function testGetIsGrantedShouldNotCallProvider(): void | ||
| { | ||
| $client = self::createClient(); | ||
|
|
||
| $client->request('GET', '/is_granted_test_call_provider/1'); | ||
| $this->assertResponseStatusCodeSame(401); | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.