Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Security] Cache voters that will always abstain #43066

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
Oct 28, 2021
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 @@ -12,6 +12,7 @@
namespace Symfony\Component\Security\Core\Authorization;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\CacheableVoterInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Exception\InvalidArgumentException;

Expand All @@ -29,6 +30,8 @@ class AccessDecisionManager implements AccessDecisionManagerInterface
public const STRATEGY_PRIORITY = 'priority';

private $voters;
private $votersCacheAttributes;
private $votersCacheObject;
private $strategy;
private $allowIfAllAbstainDecisions;
private $allowIfEqualGrantedDeniedDecisions;
Expand Down Expand Up @@ -80,7 +83,7 @@ public function decide(TokenInterface $token, array $attributes, $object = null/
private function decideAffirmative(TokenInterface $token, array $attributes, $object = null): bool
{
$deny = 0;
foreach ($this->voters as $voter) {
foreach ($this->getVoters($attributes, $object) as $voter) {
$result = $voter->vote($token, $object, $attributes);

if (VoterInterface::ACCESS_GRANTED === $result) {
Expand Down Expand Up @@ -119,7 +122,7 @@ private function decideConsensus(TokenInterface $token, array $attributes, $obje
{
$grant = 0;
$deny = 0;
foreach ($this->voters as $voter) {
foreach ($this->getVoters($attributes, $object) as $voter) {
$result = $voter->vote($token, $object, $attributes);

if (VoterInterface::ACCESS_GRANTED === $result) {
Expand Down Expand Up @@ -155,7 +158,7 @@ private function decideConsensus(TokenInterface $token, array $attributes, $obje
private function decideUnanimous(TokenInterface $token, array $attributes, $object = null): bool
{
$grant = 0;
foreach ($this->voters as $voter) {
foreach ($this->getVoters($attributes, $object) as $voter) {
foreach ($attributes as $attribute) {
$result = $voter->vote($token, $object, [$attribute]);

Expand Down Expand Up @@ -188,7 +191,7 @@ private function decideUnanimous(TokenInterface $token, array $attributes, $obje
*/
private function decidePriority(TokenInterface $token, array $attributes, $object = null)
{
foreach ($this->voters as $voter) {
foreach ($this->getVoters($attributes, $object) as $voter) {
$result = $voter->vote($token, $object, $attributes);

if (VoterInterface::ACCESS_GRANTED === $result) {
Expand All @@ -206,4 +209,48 @@ private function decidePriority(TokenInterface $token, array $attributes, $objec

return $this->allowIfAllAbstainDecisions;
}

private function getVoters(array $attributes, $object = null): iterable
{
$keyAttributes = [];
foreach ($attributes as $attribute) {
$keyAttributes[] = \is_string($attribute) ? $attribute : null;
}
// use `get_class` to handle anonymous classes
$keyObject = \is_object($object) ? \get_class($object) : get_debug_type($object);
lyrixx marked this conversation as resolved.
Show resolved Hide resolved
foreach ($this->voters as $key => $voter) {
if (!$voter instanceof CacheableVoterInterface) {
yield $voter;
continue;
}

$supports = true;
// The voter supports the attributes if it supports at least one attribute of the list
foreach ($keyAttributes as $keyAttribute) {
if (null === $keyAttribute) {
$supports = true;
} elseif (!isset($this->votersCacheAttributes[$keyAttribute][$key])) {
$this->votersCacheAttributes[$keyAttribute][$key] = $supports = $voter->supportsAttribute($keyAttribute);
} else {
$supports = $this->votersCacheAttributes[$keyAttribute][$key];
}
if ($supports) {
break;
}
}
if (!$supports) {
continue;
}

if (!isset($this->votersCacheObject[$keyObject][$key])) {
$this->votersCacheObject[$keyObject][$key] = $supports = $voter->supportsType($keyObject);
} else {
$supports = $this->votersCacheObject[$keyObject][$key];
}
if (!$supports) {
continue;
}
yield $voter;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class AuthenticatedVoter implements VoterInterface
class AuthenticatedVoter implements CacheableVoterInterface
{
public const IS_AUTHENTICATED_FULLY = 'IS_AUTHENTICATED_FULLY';
public const IS_AUTHENTICATED_REMEMBERED = 'IS_AUTHENTICATED_REMEMBERED';
Expand Down Expand Up @@ -116,4 +116,23 @@ public function vote(TokenInterface $token, $subject, array $attributes)

return $result;
}

public function supportsAttribute(string $attribute): bool
{
return \in_array($attribute, [
self::IS_AUTHENTICATED_FULLY,
self::IS_AUTHENTICATED_REMEMBERED,
self::IS_AUTHENTICATED_ANONYMOUSLY,
self::IS_AUTHENTICATED,
self::IS_ANONYMOUS,
self::IS_IMPERSONATOR,
self::IS_REMEMBERED,
self::PUBLIC_ACCESS,
], true);
}

public function supportsType(string $subjectType): bool
{
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?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\Core\Authorization\Voter;

/**
* Let voters expose the attributes and types they care about.
*
* By returning false to either `supportsAttribute` or `supportsType`, the
* voter will never be called for the specified attribute or subject.
*
* @author Jérémy Derussé <jeremy@derusse.com>
*/
interface CacheableVoterInterface extends VoterInterface
{
public function supportsAttribute(string $attribute): bool;

/**
* @param string $subjectType The type of the subject inferred by `get_class` or `get_debug_type`
*/
public function supportsType(string $subjectType): bool;
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RoleVoter implements VoterInterface
class RoleVoter implements CacheableVoterInterface
{
private $prefix;

Expand Down Expand Up @@ -55,6 +55,16 @@ public function vote(TokenInterface $token, $subject, array $attributes)
return $result;
}

public function supportsAttribute(string $attribute): bool
{
return str_starts_with($attribute, $this->prefix);
}

public function supportsType(string $subjectType): bool
{
return true;
}

protected function extractRoles(TokenInterface $token)
{
return $token->getRoleNames();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
*
* @internal
*/
class TraceableVoter implements VoterInterface
class TraceableVoter implements CacheableVoterInterface
{
private $voter;
private $eventDispatcher;
Expand All @@ -46,4 +46,14 @@ public function getDecoratedVoter(): VoterInterface
{
return $this->voter;
}

public function supportsAttribute(string $attribute): bool
{
return !$this->voter instanceof CacheableVoterInterface || $this->voter->supportsAttribute($attribute);
}

public function supportsType(string $subjectType): bool
{
return !$this->voter instanceof CacheableVoterInterface || $this->voter->supportsType($subjectType);
}
}
1 change: 1 addition & 0 deletions 1 src/Symfony/Component/Security/Core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
5.4
---

* Add a `CacheableVoterInterface` for voters that vote only on identified attributes and subjects
* Deprecate `AuthenticationEvents::AUTHENTICATION_FAILURE`, use the `LoginFailureEvent` instead
* Deprecate `AnonymousToken`, as the related authenticator was deprecated in 5.3
* Deprecate `Token::getCredentials()`, tokens should no longer contain credentials (as they represent authenticated sessions)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\Voter\CacheableVoterInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;

class AccessDecisionManagerTest extends TestCase
Expand Down Expand Up @@ -120,6 +121,143 @@ public function provideStrategies()
yield [AccessDecisionManager::STRATEGY_PRIORITY];
}

public function testCacheableVoters()
{
$token = $this->createMock(TokenInterface::class);
$voter = $this->getMockBuilder(CacheableVoterInterface::class)->getMockForAbstractClass();
$voter
->expects($this->once())
->method('supportsAttribute')
->with('foo')
->willReturn(true);
$voter
->expects($this->once())
->method('supportsType')
->with('string')
->willReturn(true);
$voter
->expects($this->once())
->method('vote')
->with($token, 'bar', ['foo'])
->willReturn(VoterInterface::ACCESS_GRANTED);

$manager = new AccessDecisionManager([$voter]);
$this->assertTrue($manager->decide($token, ['foo'], 'bar'));
}

public function testCacheableVotersIgnoresNonStringAttributes()
{
$token = $this->createMock(TokenInterface::class);
$voter = $this->getMockBuilder(CacheableVoterInterface::class)->getMockForAbstractClass();
$voter
->expects($this->never())
->method('supportsAttribute');
$voter
->expects($this->once())
->method('supportsType')
->with('string')
->willReturn(true);
$voter
->expects($this->once())
->method('vote')
->with($token, 'bar', [1337])
->willReturn(VoterInterface::ACCESS_GRANTED);

$manager = new AccessDecisionManager([$voter]);
$this->assertTrue($manager->decide($token, [1337], 'bar'));
}

public function testCacheableVotersWithMultipleAttributes()
{
$token = $this->createMock(TokenInterface::class);
$voter = $this->getMockBuilder(CacheableVoterInterface::class)->getMockForAbstractClass();
$voter
->expects($this->exactly(2))
->method('supportsAttribute')
->withConsecutive(['foo'], ['bar'])
->willReturnOnConsecutiveCalls(false, true);
$voter
->expects($this->once())
->method('supportsType')
->with('string')
->willReturn(true);
$voter
->expects($this->once())
->method('vote')
->with($token, 'bar', ['foo', 'bar'])
->willReturn(VoterInterface::ACCESS_GRANTED);

$manager = new AccessDecisionManager([$voter]);
$this->assertTrue($manager->decide($token, ['foo', 'bar'], 'bar', true));
}

public function testCacheableVotersWithEmptyAttributes()
{
$token = $this->createMock(TokenInterface::class);
$voter = $this->getMockBuilder(CacheableVoterInterface::class)->getMockForAbstractClass();
$voter
->expects($this->never())
->method('supportsAttribute');
$voter
->expects($this->once())
->method('supportsType')
->with('string')
->willReturn(true);
$voter
->expects($this->once())
->method('vote')
->with($token, 'bar', [])
->willReturn(VoterInterface::ACCESS_GRANTED);

$manager = new AccessDecisionManager([$voter]);
$this->assertTrue($manager->decide($token, [], 'bar'));
}

public function testCacheableVotersSupportsMethodsCalledOnce()
{
$token = $this->createMock(TokenInterface::class);
$voter = $this->getMockBuilder(CacheableVoterInterface::class)->getMockForAbstractClass();
$voter
->expects($this->once())
->method('supportsAttribute')
->with('foo')
->willReturn(true);
$voter
->expects($this->once())
->method('supportsType')
->with('string')
->willReturn(true);
$voter
->expects($this->exactly(2))
->method('vote')
->with($token, 'bar', ['foo'])
->willReturn(VoterInterface::ACCESS_GRANTED);

$manager = new AccessDecisionManager([$voter]);
$this->assertTrue($manager->decide($token, ['foo'], 'bar'));
$this->assertTrue($manager->decide($token, ['foo'], 'bar'));
}

public function testCacheableVotersNotCalled()
{
$token = $this->createMock(TokenInterface::class);
$voter = $this->getMockBuilder(CacheableVoterInterface::class)->getMockForAbstractClass();
$voter
->expects($this->once())
->method('supportsAttribute')
->with('foo')
->willReturn(false);
$voter
->expects($this->never())
->method('supportsType');
$voter
->expects($this->never())
->method('vote');

$manager = new AccessDecisionManager([$voter]);
$this->assertFalse($manager->decide($token, ['foo'], 'bar'));
}

protected function getVoters($grants, $denies, $abstains)
{
$voters = [];
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.