Skip to content

Navigation Menu

Sign in
Appearance settings

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] Add strategy resolvers #21178

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
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
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,14 @@ public function collect(Request $request, Response $response, \Exception $except
return $decision;
}, $this->accessDecisionManager->getDecisionLog());

$this->data['voter_strategy'] = $this->accessDecisionManager->getStrategy();
$this->data['voter_default_strategy'] = $this->accessDecisionManager->getDefaultStrategy();

foreach ($this->accessDecisionManager->getVoters() as $voter) {
$this->data['voters'][] = get_class($voter);
}
} else {
$this->data['access_decision_log'] = array();
$this->data['voter_strategy'] = 'unknown';
$this->data['voter_default_strategy'] = 'unknown';
$this->data['voters'] = array();
}

Expand Down Expand Up @@ -263,13 +263,13 @@ public function getVoters()
}

/**
* Returns the strategy configured for the security voters.
* Returns the default strategy configured for the security voters.
*
* @return string
*/
public function getVoterStrategy()
public function getVoterDefaultStrategy()
{
return $this->data['voter_strategy'];
return $this->data['voter_default_strategy'];
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?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\Bundle\SecurityBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\Security\Core\Authorization\StrategyResolverInterface;

class AddStrategyResolversPass implements CompilerPassInterface
{
use PriorityTaggedServiceTrait;

/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('security.access.decision_manager')) {
return;
}

$strategyResolverReferences = $this->findAndSortTaggedServices('security.strategy_resolver', $container);
foreach ($strategyResolverReferences as $strategyResolverReference) {
$strategyResolverServiceId = $strategyResolverReference->__toString();
$class = $container->getDefinition($strategyResolverServiceId)->getClass();
if (!is_subclass_of($class, StrategyResolverInterface::class)) {
throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $strategyResolverServiceId, StrategyResolverInterface::class));
}
}

$container->getDefinition('security.access.decision_manager')->replaceArgument(4, $strategyResolverReferences);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public function load(array $configs, ContainerBuilder $container)
->addArgument($config['access_decision_manager']['strategy'])
->addArgument($config['access_decision_manager']['allow_if_all_abstain'])
->addArgument($config['access_decision_manager']['allow_if_equal_granted_denied'])
->addArgument(array());
;
$container->setParameter('security.access.always_authenticate_before_granting', $config['always_authenticate_before_granting']);
$container->setParameter('security.authentication.hide_user_not_found', $config['hide_user_not_found']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,8 @@

<div class="metrics">
<div class="metric">
<span class="value">{{ collector.voterStrategy|default('unknown') }}</span>
<span class="label">Strategy</span>
<span class="value">{{ collector.voterDefaultStrategy|default('unknown') }}</span>
<span class="label">Default strategy</span>
</div>
</div>

Expand Down Expand Up @@ -235,13 +235,15 @@
<table class="decision-log">
<col style="width: 30px">
<col style="width: 120px">
<col style="width: 120px">
<col style="width: 25%">
<col style="width: 60%">
<col style="width: 50%">

<thead>
<tr>
<th>#</th>
<th>Result</th>
<th>Strategy</th>
<th>Attributes</th>
<th>Object</th>
</tr>
Expand All @@ -257,6 +259,7 @@
: '<span class="label status-error same-width">DENIED</span>'
}}
</td>
<td>{{ decision.strategy }}</td>
<td>{{ decision.attributes|length == 1 ? decision.attributes|first : profiler_dump(decision.attributes) }}</td>
<td>{{ profiler_dump(decision.object) }}</td>
</tr>
Expand Down
2 changes: 2 additions & 0 deletions 2 src/Symfony/Bundle/SecurityBundle/SecurityBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddSecurityVotersPass;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddStrategyResolversPass;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\FormLoginFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\FormLoginLdapFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\HttpBasicFactory;
Expand Down Expand Up @@ -57,5 +58,6 @@ public function build(ContainerBuilder $container)
$extension->addUserProviderFactory(new InMemoryFactory());
$extension->addUserProviderFactory(new LdapFactory());
$container->addCompilerPass(new AddSecurityVotersPass());
$container->addCompilerPass(new AddStrategyResolversPass());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,31 +27,41 @@ class AccessDecisionManager implements AccessDecisionManagerInterface
const STRATEGY_UNANIMOUS = 'unanimous';

private $voters;
private $strategy;
private $defaultStrategy;
private $allowIfAllAbstainDecisions;
private $allowIfEqualGrantedDeniedDecisions;

/**
* @var array
*/
private $strategyResolvers;

/**
* Constructor.
*
* @param VoterInterface[] $voters An array of VoterInterface instances
* @param string $strategy The vote strategy
* @param bool $allowIfAllAbstainDecisions Whether to grant access if all voters abstained or not
* @param bool $allowIfEqualGrantedDeniedDecisions Whether to grant access if result are equals
* @param VoterInterface[] $voters An array of VoterInterface instances
* @param string $defaultStrategy The vote default strategy
* @param bool $allowIfAllAbstainDecisions Whether to grant access if all voters abstained or not
* @param bool $allowIfEqualGrantedDeniedDecisions Whether to grant access if result are equals
* @param StrategyResolverInterface[] $strategyResolvers An array of StrategyResolver instances
*
* @throws \InvalidArgumentException
*/
public function __construct(array $voters = array(), $strategy = self::STRATEGY_AFFIRMATIVE, $allowIfAllAbstainDecisions = false, $allowIfEqualGrantedDeniedDecisions = true)
public function __construct(array $voters = array(), $defaultStrategy = self::STRATEGY_AFFIRMATIVE, $allowIfAllAbstainDecisions = false, $allowIfEqualGrantedDeniedDecisions = true, array $strategyResolvers = array())
{
$strategyMethod = 'decide'.ucfirst($strategy);
if (!is_callable(array($this, $strategyMethod))) {
throw new \InvalidArgumentException(sprintf('The strategy "%s" is not supported.', $strategy));
if (!in_array($defaultStrategy, array(
self::STRATEGY_AFFIRMATIVE,
self::STRATEGY_CONSENSUS,
self::STRATEGY_UNANIMOUS
))) {
throw new \InvalidArgumentException(sprintf('The strategy "%s" is not supported.', $defaultStrategy));
}

$this->voters = $voters;
$this->strategy = $strategyMethod;
$this->defaultStrategy = $defaultStrategy;
$this->allowIfAllAbstainDecisions = (bool) $allowIfAllAbstainDecisions;
$this->allowIfEqualGrantedDeniedDecisions = (bool) $allowIfEqualGrantedDeniedDecisions;
$this->strategyResolvers = $strategyResolvers;
}

/**
Expand All @@ -69,7 +79,40 @@ public function setVoters(array $voters)
*/
public function decide(TokenInterface $token, array $attributes, $object = null)
{
return $this->{$this->strategy}($token, $attributes, $object);
$strategyMethod = 'decide' . ucfirst($this->getStrategy($token, $attributes, $object));

return $this->{$strategyMethod}($token, $attributes, $object);
}

/**
* @param TokenInterface $token
* @param array $attributes
* @param mixed $object
*
* @return string
*/
public function getStrategy(TokenInterface $token, array $attributes, $object = null)
{
$strategy = $this->defaultStrategy;
/* @var $strategyResolver StrategyResolverInterface */
foreach ($this->strategyResolvers as $strategyResolver) {
if ($strategyResolver->supports($token, $attributes, $object)) {
$resolvedStrategy = $strategyResolver->getStrategy($token, $attributes, $object);
if (!in_array($resolvedStrategy, array(
self::STRATEGY_AFFIRMATIVE,
self::STRATEGY_CONSENSUS,
self::STRATEGY_UNANIMOUS
))) {
continue;
}

$strategy = $resolvedStrategy;

break;
}
}

return $strategy;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?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\Authentication\Token\TokenInterface;

interface StrategyResolverInterface
{
/**
* This method must return one of the following constants from the AccessDecisionManager :
* STRATEGY_AFFIRMATIVE, STRATEGY_CONSENSUS, or STRATEGY_UNANIMOUS.
*
* @param TokenInterface $token
* @param array $attributes
* @param mixed $object
*
* @return string
*/
public function getStrategy(TokenInterface $token, array $attributes, $object = null);

/**
* @param TokenInterface $token
* @param array $attributes
* @param mixed $object
*
* @return bool
*/
public function supports(TokenInterface $token, array $attributes, $object = null);
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
class TraceableAccessDecisionManager implements AccessDecisionManagerInterface
{
private $manager;
private $strategy;
private $defaultStrategy;
private $voters = array();
private $decisionLog = array();

Expand All @@ -33,10 +33,10 @@ public function __construct(AccessDecisionManagerInterface $manager)
$this->manager = $manager;

if ($this->manager instanceof AccessDecisionManager) {
// The strategy is stored in a private property of the decorated service
$reflection = new \ReflectionProperty(AccessDecisionManager::class, 'strategy');
// The default strategy is stored in a private property of the decorated service
$reflection = new \ReflectionProperty(AccessDecisionManager::class, 'defaultStrategy');
$reflection->setAccessible(true);
$this->strategy = $reflection->getValue($manager);
$this->defaultStrategy = $reflection->getValue($manager);
}
}

Expand All @@ -47,10 +47,16 @@ public function decide(TokenInterface $token, array $attributes, $object = null)
{
$result = $this->manager->decide($token, $attributes, $object);

$strategy = 'unknown';
if ($this->manager instanceof AccessDecisionManager) {
$strategy = $this->manager->getStrategy($token, $attributes, $object);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't like the fact that there is a double call to the getStrategy method (the other in the decide call), but I don't see how else I can get the strategy (unless the last strategy used get stored in the AccessDecisionManager)

}

$this->decisionLog[] = array(
'attributes' => $attributes,
'object' => $object,
'result' => $result,
'strategy' => $strategy,
);

return $result;
Expand All @@ -72,12 +78,9 @@ public function setVoters(array $voters)
/**
* @return string
*/
public function getStrategy()
public function getDefaultStrategy()
{
// The $strategy property is misleading because it stores the name of its
// method (e.g. 'decideAffirmative') instead of the original strategy name
// (e.g. 'affirmative')
return null === $this->strategy ? '-' : strtolower(substr($this->strategy, 6));
return null === $this->defaultStrategy ? 'unknown' : $this->defaultStrategy;
}

/**
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.