8000 [Security][SecurityBundle] Add messages and score on votes by eltharin · Pull Request #58107 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Security][SecurityBundle] Add messages and score on votes #58107

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 12 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
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 @@ -202,6 +203,23 @@ protected function isGranted(mixed $attribute, mixed $subject = null): bool
return $this->container->get('security.authorization_checker')->isGranted($attribute, $subject);
}

/**
* Checks if the attribute is granted against the current authentication token and optionally supplied subject.
*
* @throws \LogicException
*/
protected function getAccessDecision(mixed $attribute, mixed $subject = null): AccessDecision
{
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".');
}

$accessDecision = null;
$decision = $this->container->get('security.authorization_checker')->isGranted($attribute, $subject, $accessDecision);

return null === $accessDecision ? new AccessDecision($decision) : $accessDecision;
}

/**
* Throws an exception unless the attribute is granted against the current authentication token and optionally
* supplied subject.
Expand All @@ -210,11 +228,13 @@ protected function isGranted(mixed $attribute, mixed $subject = null): bool
*/
protected function denyAccessUnlessGranted(mixed $attribute, mixed $subject = null, string $message = 'Access Denied.'): void
{
6D47 if (!$this->isGranted($attribute, $subject)) {
$decision = $this->getAccessDecision($attribute, $subject);

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

$exception->setAccessDecision($decision);
throw $exception;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\AccessDecision;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
Expand Down Expand Up @@ -362,7 +364,14 @@ public function testdenyAccessUnlessGranted()

$this->expectException(AccessDeniedException::class);

$controller->denyAccessUnlessGranted('foo');
try {
$controller->denyAccessUnlessGranted('foo');
} catch (AccessDeniedException $exception) {
$this->assertFalse($exception->getAccessDecision()->getAccess());
$this->assertEmpty($exception->getAccessDecision()->getVotes());
$this->assertEmpty($exception->getAccessDecision()->getMessage());
throw $exception;
}
}

/**
Expand Down Expand Up @@ -644,4 +653,33 @@ public function testSendEarlyHints()

$this->assertSame('</style.css>; rel="preload"; as="stylesheet",</script.js>; rel="preload"; as="script"', $response->headers->get('Link'));
}

public function testdenyAccessUnlessGrantedWithAccessDecisionObject()
{
$authorizationChecker = new class implements AuthorizationCheckerInterface {
public function isGranted(mixed $attribute, mixed $subject = null, ?AccessDecision &$accessDecision = null): bool
{
$accessDecision = new AccessDecision(false, [new Vote(-1)], 'access denied');

return $accessDecision->getAccess();
}
};

$container = new Container();
$container->set('security.authorization_checker', $authorizationChecker);

$controller = $this->createController();
$controller->setContainer($container);

$this->expectException(AccessDeniedException::class);

try {
$controller->denyAccessUnlessGranted('foo');
} catch (AccessDeniedException $exception) {
$this->assertFalse($exception->getAccessDecision()->getAccess());
$this->assertCount(1, $exception->getAccessDecision()->getVotes());
$this->assertSame('access denied', $exception->getAccessDecision()->getMessage());
throw $exception;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@
use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authorization\AccessDecision;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
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\VoteInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Http\Firewall\SwitchUserListener;
use Symfony\Component\Security\Http\FirewallMapInterface;
Expand Down Expand Up @@ -138,6 +141,7 @@ public function collect(Request $request, Response $response, ?\Throwable $excep

// collect voter details
$decisionLog = $this->accessDecisionManager->getDecisionLog();

foreach ($decisionLog as $key => $log) {
$decisionLog[$key]['voter_details'] = [];
foreach ($log['voterDetails'] as $voterDetail) {
Expand All @@ -146,10 +150,14 @@ public function collect(Request $request, Response $response, ?\Throwable $excep
$decisionLog[$key]['voter_details'][] = [
'class' => $classData,
'attributes' => $voterDetail['attributes'], // Only displayed for unanimous strategy
'vote' => $voterDetail['vote'],
'vote' => $voterDetail['vote'] instanceof VoteInterface ? $voterDetail['vote'] : new Vote($voterDetail['vote']),
];
}
unset($decisionLog[$key]['voterDetails']);

if (!$decisionLog[$key]['result'] instanceof AccessDecision) {
$decisionLog[$key]['result'] = new AccessDecision($decisionLog[$key]['result']);
}
}

$this->data['access_decision_log'] = $decisionLog;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ public function __construct(

public function onVoterVote(VoteEvent $event): void
{
$this->traceableAccessDecisionManager->addVoterVote($event->getVoter(), $event->getAttributes(), $event->getVote());
$voteObj = null;
$vote = $event->getVote($voteObj);
$this->traceableAccessDecisionManager->addVoterVote($event->getVoter(), $event->getAttributes(), $voteObj ?? $vote);
}

public static function getSubscribedEvents(): array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -351,11 +351,11 @@
{% else %}
<table>
<thead>
<tr>
<th>Listener</th>
<th>Duration</th>
<th>Response</th>
</tr>
<tr>
<th>Listener</th>
<th>Duration</th>
<th>Response</th>
</tr>
</thead>

{% set previous_event = (collector.listeners|first) %}
Expand Down Expand Up @@ -393,10 +393,10 @@
<col style="width: 100%">
</colgroup>
<thead>
<tr>
<th scope="col">Status</th>
<th scope="col">Authenticator</th>
</tr>
<tr>
<th scope="col">Status</th>
<th scope="col">Authenticator</th>
</tr>
</thead>
{% for i, authenticator in collector.authenticators %}
<tr class="sf-toggle"
Expand Down Expand Up @@ -518,14 +518,16 @@
<col style="width: 30px">
<col style="width: 120px">
<col style="width: 25%">
<col style="width: 60%">
<col style="width: 40%">
<col style="width: 20%">

<thead>
<tr>
<th>#</th>
<th>Result</th>
<th>Attributes</th>
<th>Object</th>
<th>Message</th>
</tr>
</thead>

Expand All @@ -534,7 +536,7 @@
<tr class="voter_result">
<td class="font-normal text-small text-muted nowrap">{{ loop.index }}</td>
<td class="font-normal">
{{ decision.result
{{ decision.result.access
? '<span class="label status-success same-width">GRANTED</span>'
: '<span class="label status-error same-width">DENIED</span>'
}}
Expand All @@ -554,6 +556,7 @@
{% endif %}
</td>
<td>{{ profiler_dump(decision.seek('object')) }}</td>
<td>{{ decision.result.message }}</td>
</tr>
<tr class="voter_details">
<td></td>
Expand All @@ -570,14 +573,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 %}
{% if voter_detail['vote'].messages is not empty %}
: {{ voter_detail['vote'].messages | join(', ') }}
{% endif %}
</td>
</tr>
Expand Down
5 changes: 3 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\Authorization\UserAuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\LogicException;
Expand Down Expand Up @@ -58,10 +59,10 @@ public function getUser(): ?UserInterface
/**
* Checks if the attributes are granted against the current authentication token and optionally supplied subject.
*/
public function isGranted(mixed $attributes, mixed $subject = null): bool
public function isGranted(mixed $attributes, mixed $subject = null, ?AccessDecision $accessDecision = null): bool
{
return $this->container->get('security.authorization_checker')
->isGranted($attributes, $subject);
->isGranted($attributes, $subject, $accessDecision);
}

public function getToken(): ?TokenInterface
Expand Down
Loading
Loading
0