8000 [Security] Add the ability for voter to return decision reason by alamirault · Pull Request #46493 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Security] Add the ability for voter to return decision reason #46493

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

Closed
wants to merge 5 commits into from
Closed
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
14 changes: 14 additions & 0 deletions UPGRADE-7.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,20 @@ FrameworkBundle

* Mark classes `ConfigBuilderCacheWarmer`, `Router`, `SerializerCacheWarmer`, `TranslationsCacheWarmer`, `Translator` and `ValidatorCacheWarmer` as `final`

Security
--------

* Add method `getDecision()` to `AccessDecisionStrategyInterface`
* Deprecate `AccessDecisionStrategyInterface::decide()` in favor of `AccessDecisionStrategyInterface::getDecision()`
* Add method `getVote()` to `VoterInterface`
* Deprecate `VoterInterface::vote()` in favor of `AccessDecisionStrategyInterface::getVote()`
* Deprecate returning `bool` from `Voter::voteOnAttribute()` (it must return a `Vote`)
* Add method `getDecision()` to `AccessDecisionManagerInterface`
* Deprecate `AccessDecisionManagerInterface::decide()` in favor of `AccessDecisionManagerInterface::getDecision()`
* Add method `getDecision()` to `AuthorizationCheckerInterface`
* Add methods `setAccessDecision()` and `getAccessDecision()` to `AccessDeniedException`
* Add method `getDecision()` to `Security`

SecurityBundle
--------------

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecision;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\UserInterface;
Expand Down Expand Up @@ -21 A93C 0,10 +211,22 @@ protected function isGranted(mixed $attribute, mixed $subject = null): bool
*/
protected function denyAccessUnlessGranted(mixed $attribute, mixed $subject = null, string $message = 'Access Denied.'): void
{
if (!$this->isGranted($attribute, $subject)) {
if (!$this->container->has('security.authorization_checker')) {
throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
}

$checker = $this->container->get('security.authorization_checker');
if (method_exists($checker, 'getDecision')) {
$decision = $checker->getDecision($attribute, $subject);
} else {
$decision = $checker->isGranted($attribute, $subject) ? AccessDecision::createGranted() : AccessDecision::createDenied();
}

if (!$decision->isGranted()) {
$exception = $this->createAccessDeniedException($message);
$exception->setAttributes([$attribute]);
$exception->setSubject($subject);
$exception->setAccessDecision($decision);

throw $exception;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
"symfony/scheduler": "<6.4.4|>=7.0.0,<7.0.4",
"symfony/serializer": "<6.4",
"symfony/security-csrf": "<6.4",
"symfony/security-core": "<6.4",
"symfony/security-core": "<7.1",
"symfony/stopwatch": "<6.4",
"symfony/translation": "<6.4",
"symfony/twig-bridge": "<6.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function __construct(TraceableAccessDecisionManager $traceableAccessDecis

public function onVoterVote(VoteEvent $event): void
{
$this->traceableAccessDecisionManager->addVoterVote($event->getVoter(), $event->getAttributes(), $event->getVote());
$this->traceableAccessDecisionManager->addVoterVote($event->getVoter(), $event->getAttributes(), $event->getVoteDecision());
}

public static function getSubscribedEvents(): array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -476,16 +476,17 @@
<td class="font-normal text-small">attribute {{ voter_detail['attributes'][0] }}</td>
{% endif %}
<td class="font-normal text-small">
{% if voter_detail['vote'] == constant('Symfony\\Component\\Security\\Core\\Authorization\\Voter\\VoterInterface::ACCESS_GRANTED') %}
{% if voter_detail['vote'].access == constant('Symfony\\Component\\Security\\Core\\Authorization\\Voter\\VoterInterface::ACCESS_GRANTED') %}
ACCESS GRANTED
{% elseif voter_detail['vote'] == constant('Symfony\\Component\\Security\\Core\\Authorization\\Voter\\VoterInterface::ACCESS_ABSTAIN') %}
{% elseif voter_detail['vote'].access == constant('Symfony\\Component\\Security\\Core\\Authorization\\Voter\\VoterInterface::ACCESS_ABSTAIN') %}
ACCESS ABSTAIN
{% elseif voter_detail['vote'] == constant('Symfony\\Component\\Security\\Core\\Authorization\\Voter\\VoterInterface::ACCESS_DENIED') %}
{% elseif voter_detail['vote'].access == constant('Symfony\\Component\\Security\\Core\\Authorization\\Voter\\VoterInterface::ACCESS_DENIED') %}
ACCESS DENIED
{% else %}
unknown ({{ voter_detail['vote'] }})
unknown ({{ voter_detail['vote'].access }})
{% endif %}
</td>
<td class="font-normal text-small">{{ voter_detail['vote'].message|default('~') }}</td>
</tr>
{% endfor %}
</tbody>
Expand Down
17 changes: 15 additions & 2 deletions src/Symfony/Bundle/SecurityBundle/Security.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecision;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\LogicException;
use Symfony\Component\Security\Core\Exception\LogoutException;
Expand Down Expand Up @@ -59,8 +60,20 @@ public function getUser(): ?UserInterface
*/
public function isGranted(mixed $attributes, mixed $subject = null): bool
{
return $this->container->get('security.authorization_checker')
->isGranted($attributes, $subject);
return $this->getDecision($attributes, $subject)->isGranted();
}

/**
* Get the access decision against the current authentication token and optionally supplied subject.
*/
public function getDecision(mixed $attribute, mixed $subject = null): AccessDecision
{
$checker = $this->container->get('security.authorization_checker');
if (method_exists($checker, 'getDecision')) {
return $checker->getDecision($attribute, $subject);
}

return $checker->isGranted($attribute, $subject) ? AccessDecision::createGranted() : AccessDecision::createDenied();
}

public function getToken(): ?TokenInterface
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\Voter\TraceableVoter;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\User\InMemoryUser;
Expand Down Expand Up @@ -464,4 +465,8 @@ final class DummyVoter implements VoterInterface
public function vote(TokenInterface $token, mixed $subject, array $attributes): int
{
}

public function getVote(TokenInterface $token, mixed $subject, array $attributes): Vote
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\EventListener\VoteListener;
use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Event\VoteEvent;

Expand All @@ -29,10 +30,33 @@ public function testOnVoterVote()
->onlyMethods(['addVoterVote'])
->getMock();

$vote = Vote::createGranted();
$traceableAccessDecisionManager
->expects($this->once())
->method('addVoterVote')
->with($voter, ['myattr1', 'myattr2'], VoterInterface::ACCESS_GRANTED);
->with($voter, ['myattr1', 'myattr2'], $vote);

$sut = new VoteListener($traceableAccessDecisionManager);
$sut->onVoterVote(new VoteEvent($voter, 'mysubject', ['myattr1', 'myattr2'], $vote));
}

/**
* @group legacy
*/
public function testOnVoterVoteLegacy()
{
$voter = $this->createMock(VoterInterface::class);

$traceableAccessDecisionManager = $this
->getMockBuilder(TraceableAccessDecisionManager::class)
->disableOriginalConstructor()
->onlyMethods(['addVoterVote'])
->getMock();

$traceableAccessDecisionManager
->expects($this->once())
->method('addVoterVote')
->with($voter, ['myattr1', 'myattr2'], Vote::createGranted());

$sut = new VoteListener($traceableAccessDecisionManager);
$sut->onVoterVote(new VoteEvent($voter, 'mysubject', ['myattr1', 'myattr2'], VoterInterface::ACCESS_GRANTED));
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/SecurityBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"symfony/framework-bundle": "<6.4",
"symfony/http-client": "<6.4",
"symfony/ldap": "<6.4",
"symfony/security-core": "<7.1",
"symfony/serializer": "<6.4",
"symfony/twig-bundle": "<6.4",
"symfony/validator": "<6.4"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?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;

use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;

/**
* An AccessDecision is returned by an AccessDecisionManager and contains the access verdict and all the related votes.
*
* @author Dany Maillard <danymaillard93b@gmail.com>
*/
final class AccessDecision
{
/**
* @param int $access One of the VoterInterface::ACCESS_* constants
* @param Vote[] $votes
*/
private function __construct(private readonly int $access, private readonly array $votes = [])
{
}

public function getAccess(): int
{
return $this->access;
}

public function isGranted(): bool
{
return VoterInterface::ACCESS_GRANTED === $this->access;
}

public function isAbstain(): bool
{
return VoterInterface::ACCESS_ABSTAIN === $this->access;
}

public function isDenied(): bool
{
return VoterInterface::ACCESS_DENIED === $this->access;
}

/**
* @param Vote[] $votes
*/
public static function createGranted(array $votes = []): self
{
return new self(VoterInterface::ACCESS_GRANTED, $votes);
}

/**
* @param Vote[] $votes
*/
public static function createDenied(array $votes = []): self
{
return new self(VoterInterface::ACCESS_DENIED, $votes);
}

/**
* @return Vote[]
*/
public function getVotes(): array
{
return $this->votes;
}

/**
* @return Vote[]
*/
public function getGrantedVotes(): array
{
return $this->getVotesByAccess(Voter::ACCESS_GRANTED);
}

/**
* @return Vote[]
*/
public function getAbstainedVotes(): array
{
return $this->getVotesByAccess(Voter::ACCESS_ABSTAIN);
}

/**
* @return Vote[]
*/
public function getDeniedVotes(): array
{
return $this->getVotesByAccess(Voter::ACCESS_DENIED);
}

/**
* @return Vote[]
*/
private function getVotesByAccess(int $access): array
{
return array_filter($this->votes, static fn (Vote $vote): bool => $vote->getAccess() === $access);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\Security\Core\Authorization\Strategy\AccessDecisionStrategyInterface;
use Symfony\Component\Security\Core\Authorization\Strategy\AffirmativeStrategy;
use Symfony\Component\Security\Core\Authorization\Voter\CacheableVoterInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Exception\InvalidArgumentException;

Expand All @@ -26,12 +27,6 @@
*/
final class AccessDecisionManager implements AccessDecisionManagerInterface
{
private const VALID_VOTES = [
VoterInterface::ACCESS_GRANTED => true,
VoterInterface::ACCESS_DENIED => true,
VoterInterface::ACCESS_ABSTAIN => true,
];

private iterable $voters;
private array $votersCacheAttributes = [];
private array $votersCacheObject = [];
Expand All @@ -46,11 +41,35 @@ public function __construct(iterable $voters = [], ?AccessDecisionStrategyInterf
$this->strategy = $strategy ?? new AffirmativeStrategy();
}

public function getDecision(TokenInterface $token, array $attributes, mixed $object = null, bool $allowMultipleAttributes = false): AccessDecision
Copy link
Contributor Author
@alamirault alamirault May 29, 2022

Choose a reason for hiding this comment

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

$allowMultipleAttributes is in decide method (but not in interface). I think we can remove this arg and the check WDYT ?

Original comment:
Special case for AccessListener, do not remove the right side of the condition before 6.0

related to GHSA-g4m9-5hpf-hx72

{
// Special case for AccessListener, do not remove the right side of the condition before 6.0
Copy link
Contributor

Choose a reason for hiding this comment

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

to remove then now?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Related to #46493 (comment)

This was not removed on 6.x. I don't know why, and its impacts (CVE-2020-5275)

if (\count($attributes) > 1 && !$allowMultipleAttributes) {
throw new InvalidArgumentException(sprintf('Passing more than one Security attribute to "%s()" is not supported.', __METHOD__));
}

if (method_exists($this->strategy, 'getDecision')) {
$decision = $this->strategy->getDecision(
$this->collectVotes($token, $attributes, $object)
);
} else {
$decision = $this->strategy->decide(
$this->collectResults($token, $attributes, $object)
) ? AccessDecision::createGranted() : AccessDecision::createDenied();
}

return $decision;
}

/**
* @param bool $allowMultipleAttributes Whether to allow passing multiple values to the $attributes array
*
* @deprecated since Symfony 7.1, use {@see getDecision()} instead.
*/
public function decide(TokenInterface $token, array $attributes, mixed $object = null, bool $allowMultipleAttributes = false): bool
{
trigger_deprecation('symfony/security-core', '7.1', 'Method "%s::decide()" has been deprecated, use "%s::getDecision()" instead.', __CLASS__, __CLASS__);

// Special case for AccessListener, do not remove the right side of the condition before 6.0
if (\count($attributes) > 1 && !$allowMultipleAttributes) {
throw new InvalidArgumentException(sprintf('Passing more than one Security attribute to "%s()" is not supported.', __METHOD__));
Expand All @@ -62,17 +81,33 @@ public function decide(TokenInterface $token, array $attributes, mixed $object =
}

/**
* @return \Traversable<int, int>
* @return \Traversable<int, Vote>
*/
private function collectResults(TokenInterface $token, array $attributes, mixed $object): \Traversable
private function collectVotes(TokenInterface $token, array $attributes, mixed $object): \Traversable
{
foreach ($this->getVoters($attributes, $object) as $voter) {
$result = $voter->vote($token, $object, $attributes);
if (!\is_int($result) || !(self::VALID_VOTES[$result] ?? false)) {
throw new \LogicException(sprintf('"%s::vote()" must return one of "%s" constants ("ACCESS_GRANTED", "ACCESS_DENIED" or "ACCESS_ABSTAIN"), "%s" returned.', get_debug_type($voter), VoterInterface::class, var_export($result, true)));
if (method_exists($voter, 'getVote')) {
yield $voter->getVote($token, $object, $attributes);
} else {
$result = $voter->vote($token, $object, $attributes);
yield match ($result) {
VoterInterface::ACCESS_GRANTED => Vote::createGranted(),
VoterInterface::ACCESS_DENIED => Vote::createDenied(),
VoterInterface::ACCESS_ABSTAIN => Vote::createAbstain(),
default => throw new \LogicException(sprintf('"%s::vote()" must return one of "%s" constants ("ACCESS_GRANTED", "ACCESS_DENIED" or "ACCESS_ABSTAIN"), "%s" returned.', get_debug_type($voter), VoterInterface::class, var_export($result, true))),
};
}
}
}

yield $result;
/**
* @return \Traversable<int, int>
*/
private function collectResults(TokenInterface $token, array $attributes, mixed $object): \Traversable
{
/** @var Vote $vote */
foreach ($this->collectVotes($token, $attributes, $object) as $vote) {
yield $vote->getAccess();
}
}

Expand Down
Loading
0