Skip to content

[AccessControl] Add Access Control component with strategies and voters #59439

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 3 commits 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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"symfony/polyfill-uuid": "^1.15"
},
"replace": {
"symfony/access-control": "self.version",
"symfony/asset": "self.version",
"symfony/asset-mapper": "self.version",
"symfony/browser-kit": "self.version",
Expand Down
3 changes: 3 additions & 0 deletions src/Symfony/Component/AccessControl/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.git* export-ignore
4 changes: 4 additions & 0 deletions src/Symfony/Component/AccessControl/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
vendor/
composer.lock
phpunit.xml
Tests/Fixtures/var/
112 changes: 112 additions & 0 deletions src/Symfony/Component/AccessControl/AccessControlManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

namespace Symfony\Component\AccessControl;

use Symfony\Component\AccessControl\Event\AccessDecisionEvent;
use Symfony\Component\AccessControl\Event\VoteEvent;
use Symfony\Component\AccessControl\Exception\InvalidStrategyException;
use Symfony\Component\AccessControl\Strategy\AffirmativeStrategy;
use Symfony\Component\AccessControl\Strategy\StrategyInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

/**
* @experimental
*/
final class AccessControlManager implements AccessControlManagerInterface
{
private readonly string $defaultStrategy;

/**
* @var array<string, StrategyInterface>
*/
private readonly array $strategies;

/**
* @var array<string, array<array-key, bool>>
*/
private array $votersCacheAttributes = [];
/**
* @var array<string, array<array-key, bool>>
*/
private mixed $votersCacheSubject = [];

/**
* @param iterable<StrategyInterface> $strategies
* @param iterable<VoterInterface> $voters
*/
public function __construct(
iterable $strategies,
private readonly iterable $voters,
?string $defaultStrategy = null,
private readonly ?EventDispatcherInterface $dispatcher = null
) {
$namedStrategies = [];
foreach ($strategies as $strategy) {
$namedStrategies[$strategy->getName()] = $strategy;
}
if (\count($namedStrategies) === 0) {
$namedStrategies['affirmative'] = new AffirmativeStrategy();
$defaultStrategy = 'affirmative';
}
if ($defaultStrategy === null) {
$defaultStrategy = array_key_first($namedStrategies);
assert($defaultStrategy !== null, 'The default strategy cannot be null.');
}
$this->defaultStrategy = $defaultStrategy;
$this->strategies = $namedStrategies;
}

public function decide(AccessRequest $accessRequest, ?string $strategy = null): AccessDecision
{
$strategy = $strategy ?? $this->defaultStrategy;
if (!isset($this->strategies[$strategy])) {
throw new InvalidStrategyException(sprintf('Strategy "%s" is not registered. Valid strategies are: %s', $strategy, implode(', ', array_keys($this->strategies))));
}
$votes = [];
foreach ($this->getVoters($accessRequest) as $voter) {
$vote = $voter->vote($accessRequest);
$votes[] = $vote;
$this->dispatcher?->dispatch(new VoteEvent($voter, $accessRequest, $vote));
}

$accessDecision = $this->strategies[$strategy]->evaluate($accessRequest, $votes);
if ($accessDecision->decision !== DecisionVote::ACCESS_ABSTAIN) {
$this->dispatcher?->dispatch(new AccessDecisionEvent($accessRequest, $accessDecision));
return $accessDecision;
}

$accessDecision = AccessDecision::deny($accessRequest, $votes, $accessDecision->reason);
if ($accessRequest->allowIfAllAbstainOrTie) {
$accessDecision = AccessDecision::grant($accessRequest, $votes, $accessDecision->reason);
}

$this->dispatcher?->dispatch(new AccessDecisionEvent($accessRequest, $accessDecision));

return $accessDecision;
}

/**
* @return iterable<VoterInterface>
*/
private function getVoters(AccessRequest $accessRequest): iterable
{
$keyAttribute = \is_object($accessRequest->attribute) ? $accessRequest->attribute::class : get_debug_type($accessRequest->attribute);
$keySubject = \is_object($accessRequest->subject) ? $accessRequest->subject::class : get_debug_type($accessRequest->subject);
foreach ($this->voters as $key => $voter) {
if (!isset($this->votersCacheAttributes[$keyAttribute][$key])) {
$this->votersCacheAttributes[$keyAttribute][$key] = $voter->supportsAttribute($accessRequest->attribute);
}
if (!$this->votersCacheAttributes[$keyAttribute][$key]) {
continue;
}

if (!isset($this->votersCacheSubject[$keySubject][$key])) {
$this->votersCacheSubject[$keySubject][$key] = $voter->supportsSubject($accessRequest->subject);
}
if (!$this->votersCacheSubject[$keySubject][$key]) {
continue;
}
yield $voter;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Symfony\Component\AccessControl;

/**
* @experimental
*/
interface AccessControlManagerInterface
{
public function decide(AccessRequest $accessRequest, ?string $strategy = null): AccessDecision;
}
41 changes: 41 additions & 0 deletions src/Symfony/Component/AccessControl/AccessDecision.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace Symfony\Component\AccessControl;

/**
* @experimental
*/
readonly class AccessDecision
{
/**
* @param iterable<VoterOutcome> $votes
*/
public function __construct(
public AccessRequest $accessRequest,
public DecisionVote $decision,
public iterable $votes,
public ?string $reason = null,
) {
}

/**
* @param iterable<VoterOutcome> $votes
*/
public static function grant(AccessRequest $accessRequest, iterable $votes, ?string $reason = null): self
{
return new self($accessRequest, DecisionVote::ACCESS_GRANTED, $votes, $reason);
}

/**
* @param iterable<VoterOutcome> $votes
*/
public static function deny(AccessRequest $accessRequest, iterable $votes, ?string $reason = null): self
{
return new self($accessRequest, DecisionVote::ACCESS_DENIED, $votes, $reason);
}

public static function abstain(AccessRequest $accessRequest, iterable $votes, ?string $reason = null): self
{
return new self($accessRequest, DecisionVote::ACCESS_ABSTAIN, $votes, $reason);
}
}
22 changes: 22 additions & 0 deletions src/Symfony/Component/AccessControl/AccessRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Symfony\Component\AccessControl;

use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
* @experimental
*/
readonly class AccessRequest
{
public function __construct(
public null|TokenInterface $requester,
public mixed $attribute,
public mixed $subject = null,
public MetadataBag $metadata = new MetadataBag(),
public bool $allowIfAllAbstainOrTie = false,
) {
}
}
34 changes: 34 additions & 0 deletions src/Symfony/Component/AccessControl/Attribute/AccessPolicy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?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\AccessControl\Attribute;

/**
* @experimental
*/
#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)]
readonly class AccessPolicy
{
/**
* @param array<array-key, mixed> $metadata
*/
public function __construct(
public mixed $attribute,
public mixed $subject = null,
public ?string $strategy = null,
public array $metadata = [],
public bool $allowIfAllAbstain = false,
public string $message = 'Access Denied.',
public ?int $statusCode = null,
public ?int $exceptionCode = null,
) {
}
}
30 changes: 30 additions & 0 deletions src/Symfony/Component/AccessControl/Attribute/All.php
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\AccessControl\Attribute;

/**
* @experimental
*/
#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)]
final readonly class All
{
/**
* @param list<AccessPolicy> $accessPolicies
*/
public function __construct(
public array $accessPolicies,
public string $message = 'Access Denied.',
public ?int $statusCode = null,
public ?int $exceptionCode = null,
) {
}
}
27 changes: 27 additions & 0 deletions src/Symfony/Component/AccessControl/Attribute/AtLeastOneOf.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?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\AccessControl\Attribute;

/**
* @experimental
*/
#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)]
final readonly class AtLeastOneOf
{
/**
* @param list<AccessPolicy> $accessPolicies
*/
public function __construct(
public array $accessPolicies,
) {
}
}
7 changes: 7 additions & 0 deletions src/Symfony/Component/AccessControl/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

7.3
---

* Add the component as experimental
13 changes: 13 additions & 0 deletions src/Symfony/Component/AccessControl/DecisionVote.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Symfony\Component\AccessControl;

/**
* @experimental
*/
enum DecisionVote: string
{
case ACCESS_GRANTED = 'ACCESS_GRANTED';
case ACCESS_DENIED= 'ACCESS_DENIED';
case ACCESS_ABSTAIN= 'ACCESS_ABSTAIN';
}
21 changes: 21 additions & 0 deletions src/Symfony/Component/AccessControl/Event/AccessDecisionEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Symfony\Component\AccessControl\Event;

use Symfony\Component\AccessControl\AccessRequest;
use Symfony\Component\AccessControl\AccessDecision;
use Symfony\Component\AccessControl\VoterOutcome;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Contracts\EventDispatcher\Event;

/**
* @experimental
*/
final class AccessDecisionEvent extends Event
{
public function __construct(
public readonly AccessRequest $accessRequest,
public readonly AccessDecision $accessDecision
) {
}
}
21 changes: 21 additions & 0 deletions src/Symfony/Component/AccessControl/Event/VoteEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Symfony\Component\AccessControl\Event;

use Symfony\Component\AccessControl\AccessRequest;
use Symfony\Component\AccessControl\VoterInterface;
use Symfony\Component\AccessControl\VoterOutcome;
use Symfony\Contracts\EventDispatcher\Event;

/**
* @experimental
*/
final class VoteEvent extends Event
{
public function __construct(
public readonly VoterInterface $voter,
public readonly AccessRequest $accessRequest,
public readonly VoterOutcome $voterOutcome
) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Symfony\Component\AccessControl\Exception;

/**
* @experimental
*/
final class InvalidStrategyException extends \RuntimeException
{

}
Loading
Loading