Skip to content

[Security] Merge UserAuthorizationCheckerInterface into AuthorizationCheckerInterface #59793

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
1 change: 1 addition & 0 deletions UPGRADE-7.3.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Ldap
Security
--------

* Add `AuthorizationCheckerInterface::isGrantedForUser()` to test user authorization without relying on the session
* Deprecate `UserInterface::eraseCredentials()` and `TokenInterface::eraseCredentials()`;
erase credentials e.g. using `__serialize()` instead

Expand Down
13 changes: 4 additions & 9 deletions src/Symfony/Bridge/Twig/Extension/SecurityExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
use Symfony\Component\Security\Acl\Voter\FieldVote;
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\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Impersonate\ImpersonateUrlGenerator;
Expand All @@ -31,7 +30,6 @@
public function __construct(
private ?AuthorizationCheckerInterface $securityChecker = null,
private ?ImpersonateUrlGenerator $impersonateUrlGenerator = null,
private ?UserAuthorizationCheckerInterface $userSecurityChecker = null,
) {
}

Expand All @@ -58,8 +56,8 @@

public function isGrantedForUser(UserInterface $user, mixed $attribute, mixed $subject = null, ?string $field = null, ?AccessDecision $accessDecision = null): bool
{
if (!$this->userSecurityChecker) {
throw new \LogicException(\sprintf('An instance of "%s" must be provided to use "%s()".', UserAuthorizationCheckerInterface::class, __METHOD__));
if (null === $this->securityChecker) {
return false;
}

if (null !== $field) {
Expand All @@ -71,7 +69,7 @@
}

try {
return $this->userSecurityChecker->isGrantedForUser($user, $attribute, $subject, $accessDecision);
return $this->securityChecker->isGrantedForUser($user, $attribute, $subject, $accessDecision);

Check failure on line 72 in src/Symfony/Bridge/Twig/Extension/SecurityExtension.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Bridge/Twig/Extension/SecurityExtension.php:72:61: InvalidArgument: Argument 1 of isGrantedForUser expects Symfony\Component\Security\Core\Authorization\UserInterface, but Symfony\Component\Security\Core\User\UserInterface provided (see https://psalm.dev/004)

Check failure on line 72 in src/Symfony/Bridge/Twig/Extension/SecurityExtension.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Bridge/Twig/Extension/SecurityExtension.php:72:61: InvalidArgument: Argument 1 of isGrantedForUser expects Symfony\Component\Security\Core\Authorization\UserInterface, but Symfony\Component\Security\Core\User\UserInterface provided (see https://psalm.dev/004)
} catch (AuthenticationCredentialsNotFoundException) {
return false;
}
Expand Down Expand Up @@ -117,16 +115,13 @@
{
$functions = [
new TwigFunction('is_granted', $this->isGranted(...)),
new TwigFunction('is_granted_for_user', $this->isGrantedForUser(...)),
new TwigFunction('impersonation_exit_url', $this->getImpersonateExitUrl(...)),
new TwigFunction('impersonation_exit_path', $this->getImpersonateExitPath(...)),
new TwigFunction('impersonation_url', $this->getImpersonateUrl(...)),
new TwigFunction('impersonation_path', $this->getImpersonatePath(...)),
];

if ($this->userSecurityChecker) {
$functions[] = new TwigFunction('is_granted_for_user', $this->isGrantedForUser(...));
}

return $functions;
}
}
86 changes: 58 additions & 28 deletions src/Symfony/Bridge/Twig/Tests/Extension/SecurityExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,23 @@
use Symfony\Bridge\PhpUnit\ClassExistsMock;
use Symfony\Bridge\Twig\Extension\SecurityExtension;
use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\AccessDecision;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\UserAuthorizationCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class SecurityExtensionTest extends TestCase
{
public static function setUpBeforeClass(): void
{
ClassExistsMock::register(SecurityExtension::class);
}

protected function tearDown(): void
{
ClassExistsMock::withMockedClasses([FieldVote::class => true]);
}

/**
* @dataProvider provideObjectFieldAclCases
*/
Expand All @@ -39,17 +50,16 @@ public function testIsGrantedCreatesFieldVoteObjectWhenFieldNotNull($object, $fi

public function testIsGrantedThrowsWhenFieldNotNullAndFieldVoteClassDoesNotExist()
{
if (!class_exists(UserAuthorizationCheckerInterface::class)) {
if (!method_exists(AuthorizationChecker::class, 'isGrantedForUser')) {
$this->markTestSkipped('This test requires symfony/security-core 7.3 or superior.');
}

$securityChecker = $this->createMock(AuthorizationCheckerInterface::class);

ClassExistsMock::register(SecurityExtension::class);
ClassExistsMock::withMockedClasses([FieldVote::class => false]);

$this->expectException(\LogicException::class);
$this->expectExceptionMessageMatches('Passing a $field to the "is_granted()" function requires symfony/acl.');
$this->expectExceptionMessage('Passing a $field to the "is_granted()" function requires symfony/acl.');

$securityExtension = new SecurityExtension($securityChecker);
$securityExtension->isGranted('ROLE', 'object', 'bar');
Expand All @@ -60,38 +70,41 @@ public function testIsGrantedThrowsWhenFieldNotNullAndFieldVoteClassDoesNotExist
*/
public function testIsGrantedForUserCreatesFieldVoteObjectWhenFieldNotNull($object, $field, $expectedSubject)
{
if (!class_exists(UserAuthorizationCheckerInterface::class)) {
if (!method_exists(AuthorizationChecker::class, 'isGrantedForUser')) {
$this->markTestSkipped('This test requires symfony/security-core 7.3 or superior.');
}

$user = $this->createMock(UserInterface::class);
$userSecurityChecker = $this->createMock(UserAuthorizationCheckerInterface::class);
$userSecurityChecker
->expects($this->once())
->method('isGrantedForUser')
->with($user, 'ROLE', $expectedSubject)
->willReturn(true);
$securityChecker = new class implements AuthorizationCheckerInterface {
public UserInterface $user;
public mixed $attribute;
public mixed $subject;

public function isGranted(mixed $attribute, mixed $subject = null, ?AccessDecision $accessDecision = null): bool
{
throw new \BadMethodCallException('This method should not be called.');
}

public function isGrantedForUser(UserInterface $user, mixed $attribute, mixed $subject = null, ?AccessDecision $accessDecision = null): bool
{
$this->user = $user;
$this->attribute = $attribute;
$this->subject = $subject;

return true;
}
};

$securityExtension = new SecurityExtension(null, null, $userSecurityChecker);
$securityExtension = new SecurityExtension($securityChecker);
$this->assertTrue($securityExtension->isGrantedForUser($user, 'ROLE', $object, $field));
}
$this->assertSame($user, $securityChecker->user);
$this->assertSame('ROLE', $securityChecker->attribute);

public function testIsGrantedForUserThrowsWhenFieldNotNullAndFieldVoteClassDoesNotExist()
{
if (!class_exists(UserAuthorizationCheckerInterface::class)) {
$this->markTestSkipped('This test requires symfony/security-core 7.3 or superior.');
if (null === $field) {
$this->assertSame($object, $securityChecker->subject);
} else {
$this->assertEquals($expectedSubject, $securityChecker->subject);
}

$securityChecker = $this->createMock(UserAuthorizationCheckerInterface::class);

ClassExistsMock::register(SecurityExtension::class);
ClassExistsMock::withMockedClasses([FieldVote::class => false]);

$this->expectException(\LogicException::class);
$this->expectExceptionMessageMatches('Passing a $field to the "is_granted_for_user()" function requires symfony/acl.');

$securityExtension = new SecurityExtension(null, null, $securityChecker);
$securityExtension->isGrantedForUser($this->createMock(UserInterface::class), 'object', 'bar');
}

public static function provideObjectFieldAclCases()
Expand All @@ -105,4 +118,21 @@ public static function provideObjectFieldAclCases()
['object', 'field', new FieldVote('object', 'field')],
];
}

public function testIsGrantedForUserThrowsWhenFieldNotNullAndFieldVoteClassDoesNotExist()
{
if (!method_exists(AuthorizationChecker::class, 'isGrantedForUser')) {
$this->markTestSkipped('This test requires symfony/security-core 7.3 or superior.');
}

$securityChecker = $this->createMock(AuthorizationCheckerInterface::class);

ClassExistsMock::withMockedClasses([FieldVote::class => false]);

$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Passing a $field to the "is_granted_for_user()" function requires symfony/acl.');

$securityExtension = new SecurityExtension($securityChecker);
$securityExtension->isGrantedForUser($this->createMock(UserInterface::class), 'ROLE', 'object', 'bar');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\Authorization\UserAuthorizationChecker;
use Symfony\Component\Security\Core\Authorization\UserAuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter;
use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter;
Expand Down Expand Up @@ -69,12 +67,6 @@
])
->alias(AuthorizationCheckerInterface::class, 'security.authorization_checker')

->set('security.user_authorization_checker', UserAuthorizationChecker::class)
->args([
service('security.access.decision_manager'),
])
->alias(UserAuthorizationCheckerInterface::class, 'security.user_authorization_checker')

->set('security.token_storage', UsageTrackingTokenStorage::class)
->args([
service('security.untracked_token_storage'),
Expand All @@ -93,7 +85,6 @@
service_locator([
'security.token_storage' => service('security.token_storage'),
'security.authorization_checker' => service('security.authorization_checker'),
'security.user_authorization_checker' => service('security.user_authorization_checker'),
'security.authenticator.managers_locator' => service('security.authenticator.managers_locator')->ignoreOnInvalid(),
'request_stack' => service('request_stack'),
'security.firewall.map' => service('security.firewall.map'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
->args([
service('security.authorization_checker')->ignoreOnInvalid(),
service('security.impersonate_url_generator')->ignoreOnInvalid(),
service('security.user_authorization_checker')->ignoreOnInvalid(),
])
->tag('twig.extension')
;
Expand Down
25 changes: 12 additions & 13 deletions src/Symfony/Bundle/SecurityBundle/Security.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
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;
use Symfony\Component\Security\Core\Exception\LogoutException;
use Symfony\Component\Security\Core\User\UserInterface;
Expand All @@ -39,7 +38,7 @@
*
* @final
*/
class Security implements AuthorizationCheckerInterface, UserAuthorizationCheckerInterface
class Security implements AuthorizationCheckerInterface
{
public function __construct(
private readonly ContainerInterface $container,
Expand All @@ -65,6 +64,17 @@ public function isGranted(mixed $attributes, mixed $subject = null, ?AccessDecis
->isGranted($attributes, $subject, $accessDecision);
}

/**
* Checks if the attribute is granted against the user and optionally supplied subject.
*
* This should be used over isGranted() when checking permissions against a user that is not currently logged in or while in a CLI context.
*/
public function isGrantedForUser(UserInterface $user, mixed $attribute, mixed $subject = null, ?AccessDecision $accessDecision = null): bool
{
return $this->container->get('security.authorization_checker')
->isGrantedForUser($user, $attribute, $subject, $accessDecision);
}

public function getToken(): ?TokenInterface
{
return $this->container->get('security.token_storage')->getToken();
Expand Down Expand Up @@ -150,17 +160,6 @@ public function logout(bool $validateCsrfToken = true): ?Response
return $logoutEvent->getResponse();
}

/**
* Checks if the attribute is granted against the user and optionally supplied subject.
*
* This should be used over isGranted() when checking permissions against a user that is not currently logged in or while in a CLI context.
*/
public function isGrantedForUser(UserInterface $user, mixed $attribute, mixed $subject = null, ?AccessDecision $accessDecision = null): bool
{
return $this->container->get('security.user_authorization_checker')
->isGrantedForUser($user, $attribute, $subject, $accessDecision);
}

private function getAuthenticator(?string $authenticatorName, string $firewallName): AuthenticatorInterface
{
if (!isset($this->authenticators[$firewallName])) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@

namespace Symfony\Component\Security\Core\Authorization;

use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
use Symfony\Component\Security\Core\Authentication\Token\OfflineTokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
* AuthorizationChecker is the main authorization point of the Security component.
Expand Down Expand Up @@ -48,4 +51,19 @@ final public function isGranted(mixed $attribute, mixed $subject = null, ?Access
array_pop($this->accessDecisionStack);
}
}

final public function isGrantedForUser(UserInterface $user, mixed $attribute, mixed $subject = null, ?AccessDecision $accessDecision = null): bool
{
$token = new class($user->getRoles()) extends AbstractToken implements OfflineTokenInterface {};
$token->setUser($user);

$accessDecision ??= end($this->accessDecisionStack) ?: new AccessDecision();
$this->accessDecisionStack[] = $accessDecision;

try {
return $accessDecision->isGranted = $this->accessDecisionManager->decide($token, [$attribute], $subject, $accessDecision);
} finally {
array_pop($this->accessDecisionStack);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
* The AuthorizationCheckerInterface.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*
* @method bool isGrantedForUser(UserInterface $user, mixed $attribute, mixed $subject = null, ?AccessDecision $accessDecision = null)
*/
interface AuthorizationCheckerInterface
{
Expand Down

This file was deleted.

Loading
Loading