Actualización

This commit is contained in:
Xes
2025-04-10 12:24:57 +02:00
parent 8969cc929d
commit 45420b6f0d
39760 changed files with 4303286 additions and 0 deletions

View File

@@ -0,0 +1,196 @@
<?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\Tests\Authentication;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class AuthenticationProviderManagerTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testAuthenticateWithoutProviders()
{
new AuthenticationProviderManager(array());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testAuthenticateWithProvidersWithIncorrectInterface()
{
new AuthenticationProviderManager(array(
new \stdClass(),
));
}
public function testAuthenticateWhenNoProviderSupportsToken()
{
$manager = new AuthenticationProviderManager(array(
$this->getAuthenticationProvider(false),
));
try {
$manager->authenticate($token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->fail();
} catch (ProviderNotFoundException $e) {
$this->assertSame($token, $e->getToken());
}
}
public function testAuthenticateWhenProviderReturnsAccountStatusException()
{
$manager = new AuthenticationProviderManager(array(
$this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AccountStatusException'),
));
try {
$manager->authenticate($token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->fail();
} catch (AccountStatusException $e) {
$this->assertSame($token, $e->getToken());
}
}
public function testAuthenticateWhenProviderReturnsAuthenticationException()
{
$manager = new AuthenticationProviderManager(array(
$this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'),
));
try {
$manager->authenticate($token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->fail();
} catch (AuthenticationException $e) {
$this->assertSame($token, $e->getToken());
}
}
public function testAuthenticateWhenOneReturnsAuthenticationExceptionButNotAll()
{
$manager = new AuthenticationProviderManager(array(
$this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'),
$this->getAuthenticationProvider(true, $expected = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()),
));
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertSame($expected, $token);
}
public function testAuthenticateReturnsTokenOfTheFirstMatchingProvider()
{
$second = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock();
$second
->expects($this->never())
->method('supports')
;
$manager = new AuthenticationProviderManager(array(
$this->getAuthenticationProvider(true, $expected = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()),
$second,
));
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertSame($expected, $token);
}
public function testEraseCredentialFlag()
{
$manager = new AuthenticationProviderManager(array(
$this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')),
));
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertEquals('', $token->getCredentials());
$manager = new AuthenticationProviderManager(array(
$this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')),
), false);
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertEquals('bar', $token->getCredentials());
}
public function testAuthenticateDispatchesAuthenticationFailureEvent()
{
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$provider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock();
$provider->expects($this->once())->method('supports')->willReturn(true);
$provider->expects($this->once())->method('authenticate')->willThrowException($exception = new AuthenticationException());
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher
->expects($this->once())
->method('dispatch')
->with(AuthenticationEvents::AUTHENTICATION_FAILURE, $this->equalTo(new AuthenticationFailureEvent($token, $exception)));
$manager = new AuthenticationProviderManager(array($provider));
$manager->setEventDispatcher($dispatcher);
try {
$manager->authenticate($token);
$this->fail('->authenticate() should rethrow exceptions');
} catch (AuthenticationException $e) {
$this->assertSame($token, $exception->getToken());
}
}
public function testAuthenticateDispatchesAuthenticationSuccessEvent()
{
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$provider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock();
$provider->expects($this->once())->method('supports')->willReturn(true);
$provider->expects($this->once())->method('authenticate')->willReturn($token);
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher
->expects($this->once())
->method('dispatch')
->with(AuthenticationEvents::AUTHENTICATION_SUCCESS, $this->equalTo(new AuthenticationEvent($token)));
$manager = new AuthenticationProviderManager(array($provider));
$manager->setEventDispatcher($dispatcher);
$this->assertSame($token, $manager->authenticate($token));
}
protected function getAuthenticationProvider($supports, $token = null, $exception = null)
{
$provider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock();
$provider->expects($this->once())
->method('supports')
->will($this->returnValue($supports))
;
if (null !== $token) {
$provider->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
;
} elseif (null !== $exception) {
$provider->expects($this->once())
->method('authenticate')
->will($this->throwException($this->getMockBuilder($exception)->setMethods(null)->getMock()))
;
}
return $provider;
}
}

View File

@@ -0,0 +1,71 @@
<?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\Tests\Authentication;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
class AuthenticationTrustResolverTest extends TestCase
{
public function testIsAnonymous()
{
$resolver = $this->getResolver();
$this->assertFalse($resolver->isAnonymous(null));
$this->assertFalse($resolver->isAnonymous($this->getToken()));
$this->assertFalse($resolver->isAnonymous($this->getRememberMeToken()));
$this->assertTrue($resolver->isAnonymous($this->getAnonymousToken()));
}
public function testIsRememberMe()
{
$resolver = $this->getResolver();
$this->assertFalse($resolver->isRememberMe(null));
$this->assertFalse($resolver->isRememberMe($this->getToken()));
$this->assertFalse($resolver->isRememberMe($this->getAnonymousToken()));
$this->assertTrue($resolver->isRememberMe($this->getRememberMeToken()));
}
public function testisFullFledged()
{
$resolver = $this->getResolver();
$this->assertFalse($resolver->isFullFledged(null));
$this->assertFalse($resolver->isFullFledged($this->getAnonymousToken()));
$this->assertFalse($resolver->isFullFledged($this->getRememberMeToken()));
$this->assertTrue($resolver->isFullFledged($this->getToken()));
}
protected function getToken()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
}
protected function getAnonymousToken()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setConstructorArgs(array('', ''))->getMock();
}
protected function getRememberMeToken()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(array('setPersistent'))->disableOriginalConstructor()->getMock();
}
protected function getResolver()
{
return new AuthenticationTrustResolver(
'Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken',
'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken'
);
}
}

View File

@@ -0,0 +1,67 @@
<?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\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Provider\AnonymousAuthenticationProvider;
class AnonymousAuthenticationProviderTest extends TestCase
{
public function testSupports()
{
$provider = $this->getProvider('foo');
$this->assertTrue($provider->supports($this->getSupportedToken('foo')));
$this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
}
public function testAuthenticateWhenTokenIsNotSupported()
{
$provider = $this->getProvider('foo');
$this->assertNull($provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenSecretIsNotValid()
{
$provider = $this->getProvider('foo');
$provider->authenticate($this->getSupportedToken('bar'));
}
public function testAuthenticate()
{
$provider = $this->getProvider('foo');
$token = $this->getSupportedToken('foo');
$this->assertSame($token, $provider->authenticate($token));
}
protected function getSupportedToken($secret)
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setMethods(array('getSecret'))->disableOriginalConstructor()->getMock();
$token->expects($this->any())
->method('getSecret')
->will($this->returnValue($secret))
;
return $token;
}
protected function getProvider($secret)
{
return new AnonymousAuthenticationProvider($secret);
}
}

View File

@@ -0,0 +1,301 @@
<?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\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
class DaoAuthenticationProviderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
*/
public function testRetrieveUserWhenProviderDoesNotReturnAnUserInterface()
{
$provider = $this->getProvider('fabien');
$method = new \ReflectionMethod($provider, 'retrieveUser');
$method->setAccessible(true);
$method->invoke($provider, 'fabien', $this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testRetrieveUserWhenUsernameIsNotFound()
{
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new UsernameNotFoundException()))
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
$method = new \ReflectionMethod($provider, 'retrieveUser');
$method->setAccessible(true);
$method->invoke($provider, 'fabien', $this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
*/
public function testRetrieveUserWhenAnExceptionOccurs()
{
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new \RuntimeException()))
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
$method = new \ReflectionMethod($provider, 'retrieveUser');
$method->setAccessible(true);
$method->invoke($provider, 'fabien', $this->getSupportedToken());
}
public function testRetrieveUserReturnsUserFromTokenOnReauthentication()
{
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->never())
->method('loadUserByUsername')
;
$user = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user))
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
$reflection = new \ReflectionMethod($provider, 'retrieveUser');
$reflection->setAccessible(true);
$result = $reflection->invoke($provider, null, $token);
$this->assertSame($user, $result);
}
public function testRetrieveUser()
{
$user = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->returnValue($user))
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
$method = new \ReflectionMethod($provider, 'retrieveUser');
$method->setAccessible(true);
$this->assertSame($user, $method->invoke($provider, 'fabien', $this->getSupportedToken()));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testCheckAuthenticationWhenCredentialsAreEmpty()
{
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder
->expects($this->never())
->method('isPasswordValid')
;
$provider = $this->getProvider(null, null, $encoder);
$method = new \ReflectionMethod($provider, 'checkAuthentication');
$method->setAccessible(true);
$token = $this->getSupportedToken();
$token
->expects($this->once())
->method('getCredentials')
->will($this->returnValue(''))
;
$method->invoke(
$provider,
$this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(),
$token
);
}
public function testCheckAuthenticationWhenCredentialsAre0()
{
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder
->expects($this->once())
->method('isPasswordValid')
->will($this->returnValue(true))
;
$provider = $this->getProvider(null, null, $encoder);
$method = new \ReflectionMethod($provider, 'checkAuthentication');
$method->setAccessible(true);
$token = $this->getSupportedToken();
$token
->expects($this->once())
->method('getCredentials')
->will($this->returnValue('0'))
;
$method->invoke(
$provider,
$this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(),
$token
);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testCheckAuthenticationWhenCredentialsAreNotValid()
{
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder->expects($this->once())
->method('isPasswordValid')
->will($this->returnValue(false))
;
$provider = $this->getProvider(null, null, $encoder);
$method = new \ReflectionMethod($provider, 'checkAuthentication');
$method->setAccessible(true);
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
;
$method->invoke($provider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(), $token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChanged()
{
$user = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$user->expects($this->once())
->method('getPassword')
->will($this->returnValue('foo'))
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user));
$dbUser = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$dbUser->expects($this->once())
->method('getPassword')
->will($this->returnValue('newFoo'))
;
$provider = $this->getProvider();
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, $dbUser, $token);
}
public function testCheckAuthenticationWhenTokenNeedsReauthenticationWorksWithoutOriginalCredentials()
{
$user = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$user->expects($this->once())
->method('getPassword')
->will($this->returnValue('foo'))
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user));
$dbUser = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$dbUser->expects($this->once())
->method('getPassword')
->will($this->returnValue('foo'))
;
$provider = $this->getProvider();
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, $dbUser, $token);
}
public function testCheckAuthentication()
{
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder->expects($this->once())
->method('isPasswordValid')
->will($this->returnValue(true))
;
$provider = $this->getProvider(null, null, $encoder);
$method = new \ReflectionMethod($provider, 'checkAuthentication');
$method->setAccessible(true);
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
;
$method->invoke($provider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(), $token);
}
protected function getSupportedToken()
{
$mock = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken')->setMethods(array('getCredentials', 'getUser', 'getProviderKey'))->disableOriginalConstructor()->getMock();
$mock
->expects($this->any())
->method('getProviderKey')
->will($this->returnValue('key'))
;
return $mock;
}
protected function getProvider($user = null, $userChecker = null, $passwordEncoder = null)
{
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
if (null !== $user) {
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->returnValue($user))
;
}
if (null === $userChecker) {
$userChecker = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock();
}
if (null === $passwordEncoder) {
$passwordEncoder = new PlaintextPasswordEncoder();
}
$encoderFactory = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock();
$encoderFactory
->expects($this->any())
->method('getEncoder')
->will($this->returnValue($passwordEncoder))
;
return new DaoAuthenticationProvider($userProvider, $userChecker, 'key', $encoderFactory);
}
}

View File

@@ -0,0 +1,85 @@
<?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\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Security\Core\Authentication\Provider\LdapBindAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* @requires extension ldap
*/
class LdapBindAuthenticationProviderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage The presented password must not be empty.
*/
public function testEmptyPasswordShouldThrowAnException()
{
$userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap);
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', '', 'key'));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage The presented password is invalid.
*/
public function testBindFailureShouldThrowAnException()
{
$userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock();
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('bind')
->will($this->throwException(new ConnectionException()))
;
$userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock();
$provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap);
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
}
public function testRetrieveUser()
{
$userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock();
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->with('foo')
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock();
$provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap);
$reflection = new \ReflectionMethod($provider, 'retrieveUser');
$reflection->setAccessible(true);
$reflection->invoke($provider, 'foo', new UsernamePasswordToken('foo', 'bar', 'key'));
}
}

View File

@@ -0,0 +1,135 @@
<?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\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Provider\PreAuthenticatedAuthenticationProvider;
use Symfony\Component\Security\Core\Exception\LockedException;
class PreAuthenticatedAuthenticationProviderTest extends TestCase
{
public function testSupports()
{
$provider = $this->getProvider();
$this->assertTrue($provider->supports($this->getSupportedToken()));
$this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken')
->disableOriginalConstructor()
->getMock()
;
$token
->expects($this->once())
->method('getProviderKey')
->will($this->returnValue('foo'))
;
$this->assertFalse($provider->supports($token));
}
public function testAuthenticateWhenTokenIsNotSupported()
{
$provider = $this->getProvider();
$this->assertNull($provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenNoUserIsSet()
{
$provider = $this->getProvider();
$provider->authenticate($this->getSupportedToken(''));
}
public function testAuthenticate()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array()))
;
$provider = $this->getProvider($user);
$token = $provider->authenticate($this->getSupportedToken('fabien', 'pass'));
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken', $token);
$this->assertEquals('pass', $token->getCredentials());
$this->assertEquals('key', $token->getProviderKey());
$this->assertEquals(array(), $token->getRoles());
$this->assertEquals(array('foo' => 'bar'), $token->getAttributes(), '->authenticate() copies token attributes');
$this->assertSame($user, $token->getUser());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\LockedException
*/
public function testAuthenticateWhenUserCheckerThrowsException()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPostAuth')
->will($this->throwException(new LockedException()))
;
$provider = $this->getProvider($user, $userChecker);
$provider->authenticate($this->getSupportedToken('fabien'));
}
protected function getSupportedToken($user = false, $credentials = false)
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken')->setMethods(array('getUser', 'getCredentials', 'getProviderKey'))->disableOriginalConstructor()->getMock();
if (false !== $user) {
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user))
;
}
if (false !== $credentials) {
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue($credentials))
;
}
$token
->expects($this->any())
->method('getProviderKey')
->will($this->returnValue('key'))
;
$token->setAttributes(array('foo' => 'bar'));
return $token;
}
protected function getProvider($user = null, $userChecker = null)
{
$userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
if (null !== $user) {
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->returnValue($user))
;
}
if (null === $userChecker) {
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
}
return new PreAuthenticatedAuthenticationProvider($userProvider, $userChecker, 'key');
}
}

View File

@@ -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\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Provider\RememberMeAuthenticationProvider;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Role\Role;
class RememberMeAuthenticationProviderTest extends TestCase
{
public function testSupports()
{
$provider = $this->getProvider();
$this->assertTrue($provider->supports($this->getSupportedToken()));
$this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
}
public function testAuthenticateWhenTokenIsNotSupported()
{
$provider = $this->getProvider();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$this->assertNull($provider->authenticate($token));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenSecretsDoNotMatch()
{
$provider = $this->getProvider(null, 'secret1');
$token = $this->getSupportedToken(null, 'secret2');
$provider->authenticate($token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\DisabledException
*/
public function testAuthenticateWhenPreChecksFails()
{
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPreAuth')
->will($this->throwException(new DisabledException()));
$provider = $this->getProvider($userChecker);
$provider->authenticate($this->getSupportedToken());
}
public function testAuthenticate()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->exactly(2))
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')));
$provider = $this->getProvider();
$token = $this->getSupportedToken($user);
$authToken = $provider->authenticate($token);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', $authToken);
$this->assertSame($user, $authToken->getUser());
$this->assertEquals(array(new Role('ROLE_FOO')), $authToken->getRoles());
$this->assertEquals('', $authToken->getCredentials());
}
protected function getSupportedToken($user = null, $secret = 'test')
{
if (null === $user) {
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->any())
->method('getRoles')
->will($this->returnValue(array()));
}
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(array('getProviderKey'))->setConstructorArgs(array($user, 'foo', $secret))->getMock();
$token
->expects($this->once())
->method('getProviderKey')
->will($this->returnValue('foo'));
return $token;
}
protected function getProvider($userChecker = null, $key = 'test')
{
if (null === $userChecker) {
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
}
return new RememberMeAuthenticationProvider($userChecker, $key, 'foo');
}
}

View File

@@ -0,0 +1,251 @@
<?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\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\AccountExpiredException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
class UserAuthenticationProviderTest extends TestCase
{
public function testSupports()
{
$provider = $this->getProvider();
$this->assertTrue($provider->supports($this->getSupportedToken()));
$this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
}
public function testAuthenticateWhenTokenIsNotSupported()
{
$provider = $this->getProvider();
$this->assertNull($provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testAuthenticateWhenUsernameIsNotFound()
{
$provider = $this->getProvider(false, false);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->throwException(new UsernameNotFoundException()))
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenUsernameIsNotFoundAndHideIsTrue()
{
$provider = $this->getProvider(false, true);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->throwException(new UsernameNotFoundException()))
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
*/
public function testAuthenticateWhenProviderDoesNotReturnAnUserInterface()
{
$provider = $this->getProvider(false, true);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue(null))
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\CredentialsExpiredException
*/
public function testAuthenticateWhenPreChecksFails()
{
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPreAuth')
->will($this->throwException(new CredentialsExpiredException()))
;
$provider = $this->getProvider($userChecker);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException
*/
public function testAuthenticateWhenPostChecksFails()
{
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPostAuth')
->will($this->throwException(new AccountExpiredException()))
;
$provider = $this->getProvider($userChecker);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage Bad credentials
*/
public function testAuthenticateWhenPostCheckAuthenticationFails()
{
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
;
$provider->expects($this->once())
->method('checkAuthentication')
->will($this->throwException(new BadCredentialsException()))
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage Foo
*/
public function testAuthenticateWhenPostCheckAuthenticationFailsWithHideFalse()
{
$provider = $this->getProvider(false, false);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
;
$provider->expects($this->once())
->method('checkAuthentication')
->will($this->throwException(new BadCredentialsException('Foo')))
;
$provider->authenticate($this->getSupportedToken());
}
public function testAuthenticate()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
;
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($user))
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
;
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue(array()))
;
$authToken = $provider->authenticate($token);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
$this->assertSame($user, $authToken->getUser());
$this->assertEquals(array(new Role('ROLE_FOO')), $authToken->getRoles());
$this->assertEquals('foo', $authToken->getCredentials());
$this->assertEquals(array('foo' => 'bar'), $authToken->getAttributes(), '->authenticate() copies token attributes');
}
public function testAuthenticateWithPreservingRoleSwitchUserRole()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
;
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($user))
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
;
$switchUserRole = new SwitchUserRole('foo', $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue(array($switchUserRole)))
;
$authToken = $provider->authenticate($token);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
$this->assertSame($user, $authToken->getUser());
$this->assertContains(new Role('ROLE_FOO'), $authToken->getRoles(), '', false, false);
$this->assertContains($switchUserRole, $authToken->getRoles(), '', false, false);
$this->assertEquals('foo', $authToken->getCredentials());
$this->assertEquals(array('foo' => 'bar'), $authToken->getAttributes(), '->authenticate() copies token attributes');
}
protected function getSupportedToken()
{
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken')->setMethods(array('getCredentials', 'getProviderKey', 'getRoles'))->disableOriginalConstructor()->getMock();
$mock
->expects($this->any())
->method('getProviderKey')
->will($this->returnValue('key'))
;
$mock->setAttributes(array('foo' => 'bar'));
return $mock;
}
protected function getProvider($userChecker = false, $hide = true)
{
if (false === $userChecker) {
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
}
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider', array($userChecker, 'key', $hide));
}
}

View File

@@ -0,0 +1,64 @@
<?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\Tests\Authentication\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\Security\Core\Authentication\RememberMe\InMemoryTokenProvider;
class InMemoryTokenProviderTest extends TestCase
{
public function testCreateNewToken()
{
$provider = new InMemoryTokenProvider();
$token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime());
$provider->createNewToken($token);
$this->assertSame($provider->loadTokenBySeries('foo'), $token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException
*/
public function testLoadTokenBySeriesThrowsNotFoundException()
{
$provider = new InMemoryTokenProvider();
$provider->loadTokenBySeries('foo');
}
public function testUpdateToken()
{
$provider = new InMemoryTokenProvider();
$token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime());
$provider->createNewToken($token);
$provider->updateToken('foo', 'newFoo', $lastUsed = new \DateTime());
$token = $provider->loadTokenBySeries('foo');
$this->assertEquals('newFoo', $token->getTokenValue());
$this->assertSame($token->getLastUsed(), $lastUsed);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException
*/
public function testDeleteToken()
{
$provider = new InMemoryTokenProvider();
$token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime());
$provider->createNewToken($token);
$provider->deleteTokenBySeries('foo');
$provider->loadTokenBySeries('foo');
}
}

View File

@@ -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\Security\Core\Tests\Authentication\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
class PersistentTokenTest extends TestCase
{
public function testConstructor()
{
$lastUsed = new \DateTime();
$token = new PersistentToken('fooclass', 'fooname', 'fooseries', 'footokenvalue', $lastUsed);
$this->assertEquals('fooclass', $token->getClass());
$this->assertEquals('fooname', $token->getUsername());
$this->assertEquals('fooseries', $token->getSeries());
$this->assertEquals('footokenvalue', $token->getTokenValue());
$this->assertSame($lastUsed, $token->getLastUsed());
}
}

View File

@@ -0,0 +1,285 @@
<?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\Tests\Authentication\Token;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\User;
class TestUser
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function __toString()
{
return $this->name;
}
}
class ConcreteToken extends AbstractToken
{
private $credentials = 'credentials_value';
public function __construct($user, array $roles = array())
{
parent::__construct($roles);
$this->setUser($user);
}
public function serialize()
{
return serialize(array($this->credentials, parent::serialize()));
}
public function unserialize($serialized)
{
list($this->credentials, $parentStr) = unserialize($serialized);
parent::unserialize($parentStr);
}
public function getCredentials()
{
}
}
/** @noinspection PhpUndefinedClassInspection */
class AbstractTokenTest extends TestCase
{
public function testGetUsername()
{
$token = $this->getToken(array('ROLE_FOO'));
$token->setUser('fabien');
$this->assertEquals('fabien', $token->getUsername());
$token->setUser(new TestUser('fabien'));
$this->assertEquals('fabien', $token->getUsername());
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())->method('getUsername')->will($this->returnValue('fabien'));
$token->setUser($user);
$this->assertEquals('fabien', $token->getUsername());
}
public function testEraseCredentials()
{
$token = $this->getToken(array('ROLE_FOO'));
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())->method('eraseCredentials');
$token->setUser($user);
$token->eraseCredentials();
}
public function testSerialize()
{
$token = $this->getToken(array('ROLE_FOO', new Role('ROLE_BAR')));
$token->setAttributes(array('foo' => 'bar'));
$uToken = unserialize(serialize($token));
$this->assertEquals($token->getRoles(), $uToken->getRoles());
$this->assertEquals($token->getAttributes(), $uToken->getAttributes());
}
public function testSerializeWithRoleObjects()
{
$user = new User('name', 'password', array(new Role('ROLE_FOO'), new Role('ROLE_BAR')));
$token = new ConcreteToken($user, $user->getRoles());
$serialized = serialize($token);
$unserialized = unserialize($serialized);
$roles = $unserialized->getRoles();
$this->assertEquals($roles, $user->getRoles());
}
public function testSerializeParent()
{
$user = new TestUser('fabien');
$token = new ConcreteToken($user, array('ROLE_FOO'));
$parentToken = new ConcreteToken($user, array(new SwitchUserRole('ROLE_PREVIOUS', $token)));
$uToken = unserialize(serialize($parentToken));
$this->assertEquals(
current($parentToken->getRoles())->getSource()->getUser(),
current($uToken->getRoles())->getSource()->getUser()
);
}
public function testConstructor()
{
$token = $this->getToken(array('ROLE_FOO'));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = $this->getToken(array(new Role('ROLE_FOO')));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = $this->getToken(array(new Role('ROLE_FOO'), 'ROLE_BAR'));
$this->assertEquals(array(new Role('ROLE_FOO'), new Role('ROLE_BAR')), $token->getRoles());
}
public function testAuthenticatedFlag()
{
$token = $this->getToken();
$this->assertFalse($token->isAuthenticated());
$token->setAuthenticated(true);
$this->assertTrue($token->isAuthenticated());
$token->setAuthenticated(false);
$this->assertFalse($token->isAuthenticated());
}
public function testAttributes()
{
$attributes = array('foo' => 'bar');
$token = $this->getToken();
$token->setAttributes($attributes);
$this->assertEquals($attributes, $token->getAttributes(), '->getAttributes() returns the token attributes');
$this->assertEquals('bar', $token->getAttribute('foo'), '->getAttribute() returns the value of an attribute');
$token->setAttribute('foo', 'foo');
$this->assertEquals('foo', $token->getAttribute('foo'), '->setAttribute() changes the value of an attribute');
$this->assertTrue($token->hasAttribute('foo'), '->hasAttribute() returns true if the attribute is defined');
$this->assertFalse($token->hasAttribute('oof'), '->hasAttribute() returns false if the attribute is not defined');
try {
$token->getAttribute('foobar');
$this->fail('->getAttribute() throws an \InvalidArgumentException exception when the attribute does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->getAttribute() throws an \InvalidArgumentException exception when the attribute does not exist');
$this->assertEquals('This token has no "foobar" attribute.', $e->getMessage(), '->getAttribute() throws an \InvalidArgumentException exception when the attribute does not exist');
}
}
/**
* @dataProvider getUsers
*/
public function testSetUser($user)
{
$token = $this->getToken();
$token->setUser($user);
$this->assertSame($user, $token->getUser());
}
public function getUsers()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$advancedUser = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
return array(
array($advancedUser),
array($user),
array(new TestUser('foo')),
array('foo'),
);
}
/**
* @dataProvider getUserChanges
*/
public function testSetUserSetsAuthenticatedToFalseWhenUserChanges($firstUser, $secondUser)
{
$token = $this->getToken();
$token->setAuthenticated(true);
$this->assertTrue($token->isAuthenticated());
$token->setUser($firstUser);
$this->assertTrue($token->isAuthenticated());
$token->setUser($secondUser);
$this->assertFalse($token->isAuthenticated());
}
public function getUserChanges()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$advancedUser = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
return array(
array(
'foo', 'bar',
),
array(
'foo', new TestUser('bar'),
),
array(
'foo', $user,
),
array(
'foo', $advancedUser,
),
array(
$user, 'foo',
),
array(
$advancedUser, 'foo',
),
array(
$user, new TestUser('foo'),
),
array(
$advancedUser, new TestUser('foo'),
),
array(
new TestUser('foo'), new TestUser('bar'),
),
array(
new TestUser('foo'), 'bar',
),
array(
new TestUser('foo'), $user,
),
array(
new TestUser('foo'), $advancedUser,
),
array(
$user, $advancedUser,
),
array(
$advancedUser, $user,
),
);
}
/**
* @dataProvider getUsers
*/
public function testSetUserDoesNotSetAuthenticatedToFalseWhenUserDoesNotChange($user)
{
$token = $this->getToken();
$token->setAuthenticated(true);
$this->assertTrue($token->isAuthenticated());
$token->setUser($user);
$this->assertTrue($token->isAuthenticated());
$token->setUser($user);
$this->assertTrue($token->isAuthenticated());
}
protected function getToken(array $roles = array())
{
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Token\AbstractToken', array($roles));
}
}

View File

@@ -0,0 +1,46 @@
<?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\Tests\Authentication\Token;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Role\Role;
class AnonymousTokenTest extends TestCase
{
public function testConstructor()
{
$token = new AnonymousToken('foo', 'bar');
$this->assertTrue($token->isAuthenticated());
$token = new AnonymousToken('foo', 'bar', array('ROLE_FOO'));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
}
public function testGetKey()
{
$token = new AnonymousToken('foo', 'bar');
$this->assertEquals('foo', $token->getSecret());
}
public function testGetCredentials()
{
$token = new AnonymousToken('foo', 'bar');
$this->assertEquals('', $token->getCredentials());
}
public function testGetUser()
{
$token = new AnonymousToken('foo', 'bar');
$this->assertEquals('bar', $token->getUser());
}
}

View File

@@ -0,0 +1,49 @@
<?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\Tests\Authentication\Token;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Role\Role;
class PreAuthenticatedTokenTest extends TestCase
{
public function testConstructor()
{
$token = new PreAuthenticatedToken('foo', 'bar', 'key');
$this->assertFalse($token->isAuthenticated());
$token = new PreAuthenticatedToken('foo', 'bar', 'key', array('ROLE_FOO'));
$this->assertTrue($token->isAuthenticated());
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$this->assertEquals('key', $token->getProviderKey());
}
public function testGetCredentials()
{
$token = new PreAuthenticatedToken('foo', 'bar', 'key');
$this->assertEquals('bar', $token->getCredentials());
}
public function testGetUser()
{
$token = new PreAuthenticatedToken('foo', 'bar', 'key');
$this->assertEquals('foo', $token->getUser());
}
public function testEraseCredentials()
{
$token = new PreAuthenticatedToken('foo', 'bar', 'key');
$token->eraseCredentials();
$this->assertEquals('', $token->getCredentials());
}
}

View File

@@ -0,0 +1,67 @@
<?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\Tests\Authentication\Token;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Role\Role;
class RememberMeTokenTest extends TestCase
{
public function testConstructor()
{
$user = $this->getUser();
$token = new RememberMeToken($user, 'fookey', 'foo');
$this->assertEquals('fookey', $token->getProviderKey());
$this->assertEquals('foo', $token->getSecret());
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$this->assertSame($user, $token->getUser());
$this->assertTrue($token->isAuthenticated());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorSecretCannotBeNull()
{
new RememberMeToken(
$this->getUser(),
null,
null
);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorSecretCannotBeEmptyString()
{
new RememberMeToken(
$this->getUser(),
'',
''
);
}
protected function getUser($roles = array('ROLE_FOO'))
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue($roles))
;
return $user;
}
}

View File

@@ -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\Security\Core\Tests\Authentication\Token\Storage;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
class TokenStorageTest extends TestCase
{
public function testGetSetToken()
{
$tokenStorage = new TokenStorage();
$this->assertNull($tokenStorage->getToken());
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$tokenStorage->setToken($token);
$this->assertSame($token, $tokenStorage->getToken());
}
}

View File

@@ -0,0 +1,59 @@
<?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\Tests\Authentication\Token;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Role\Role;
class UsernamePasswordTokenTest extends TestCase
{
public function testConstructor()
{
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$this->assertFalse($token->isAuthenticated());
$token = new UsernamePasswordToken('foo', 'bar', 'key', array('ROLE_FOO'));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$this->assertTrue($token->isAuthenticated());
$this->assertEquals('key', $token->getProviderKey());
}
/**
* @expectedException \LogicException
*/
public function testSetAuthenticatedToTrue()
{
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$token->setAuthenticated(true);
}
public function testSetAuthenticatedToFalse()
{
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$token->setAuthenticated(false);
$this->assertFalse($token->isAuthenticated());
}
public function testEraseCredentials()
{
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$token->eraseCredentials();
$this->assertEquals('', $token->getCredentials());
}
public function testToString()
{
$token = new UsernamePasswordToken('foo', '', 'foo', array('A', 'B'));
$this->assertEquals('UsernamePasswordToken(user="foo", authenticated=true, roles="A, B")', (string) $token);
}
}

View File

@@ -0,0 +1,141 @@
<?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\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class AccessDecisionManagerTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testSetUnsupportedStrategy()
{
new AccessDecisionManager(array($this->getVoter(VoterInterface::ACCESS_GRANTED)), 'fooBar');
}
/**
* @dataProvider getStrategyTests
*/
public function testStrategies($strategy, $voters, $allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions, $expected)
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$manager = new AccessDecisionManager($voters, $strategy, $allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions);
$this->assertSame($expected, $manager->decide($token, array('ROLE_FOO')));
}
/**
* @dataProvider getStrategiesWith2RolesTests
*/
public function testStrategiesWith2Roles($token, $strategy, $voter, $expected)
{
$manager = new AccessDecisionManager(array($voter), $strategy);
$this->assertSame($expected, $manager->decide($token, array('ROLE_FOO', 'ROLE_BAR')));
}
public function getStrategiesWith2RolesTests()
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
return array(
array($token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_DENIED), false),
array($token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_GRANTED), true),
array($token, 'consensus', $this->getVoter(VoterInterface::ACCESS_DENIED), false),
array($token, 'consensus', $this->getVoter(VoterInterface::ACCESS_GRANTED), true),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_DENIED), false),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_GRANTED), false),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_DENIED), false),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_GRANTED), true),
);
}
protected function getVoterFor2Roles($token, $vote1, $vote2)
{
$voter = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\Voter\VoterInterface')->getMock();
$voter->expects($this->any())
->method('vote')
->will($this->returnValueMap(array(
array($token, null, array('ROLE_FOO'), $vote1),
array($token, null, array('ROLE_BAR'), $vote2),
)))
;
return $voter;
}
public function getStrategyTests()
{
return array(
// affirmative
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 0, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 2, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 1, 0), false, true, false),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), false, true, false),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), true, true, true),
// consensus
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 0, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 2, 0), false, true, false),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 1, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), false, true, false),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), true, true, true),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, true, true),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, false, false),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, false, false),
// unanimous
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 1), false, true, true),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 1, 0), false, true, false),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), false, true, false),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), true, true, true),
);
}
protected function getVoters($grants, $denies, $abstains)
{
$voters = array();
for ($i = 0; $i < $grants; ++$i) {
$voters[] = $this->getVoter(VoterInterface::ACCESS_GRANTED);
}
for ($i = 0; $i < $denies; ++$i) {
$voters[] = $this->getVoter(VoterInterface::ACCESS_DENIED);
}
for ($i = 0; $i < $abstains; ++$i) {
$voters[] = $this->getVoter(VoterInterface::ACCESS_ABSTAIN);
}
return $voters;
}
protected function getVoter($vote)
{
$voter = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\Voter\VoterInterface')->getMock();
$voter->expects($this->any())
->method('vote')
->will($this->returnValue($vote));
return $voter;
}
}

View File

@@ -0,0 +1,100 @@
<?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\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
class AuthorizationCheckerTest extends TestCase
{
private $authenticationManager;
private $accessDecisionManager;
private $authorizationChecker;
private $tokenStorage;
protected function setUp()
{
$this->authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$this->accessDecisionManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock();
$this->tokenStorage = new TokenStorage();
$this->authorizationChecker = new AuthorizationChecker(
$this->tokenStorage,
$this->authenticationManager,
$this->accessDecisionManager
);
}
public function testVoteAuthenticatesTokenIfNecessary()
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$this->tokenStorage->setToken($token);
$newToken = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$this->authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->equalTo($token))
->will($this->returnValue($newToken));
// default with() isn't a strict check
$tokenComparison = function ($value) use ($newToken) {
// make sure that the new token is used in "decide()" and not the old one
return $value === $newToken;
};
$this->accessDecisionManager
->expects($this->once())
->method('decide')
->with($this->callback($tokenComparison))
->will($this->returnValue(true));
// first run the token has not been re-authenticated yet, after isGranted is called, it should be equal
$this->assertFalse($newToken === $this->tokenStorage->getToken());
$this->assertTrue($this->authorizationChecker->isGranted('foo'));
$this->assertTrue($newToken === $this->tokenStorage->getToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testVoteWithoutAuthenticationToken()
{
$this->authorizationChecker->isGranted('ROLE_FOO');
}
/**
* @dataProvider isGrantedProvider
*/
public function testIsGranted($decide)
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('isAuthenticated')
->will($this->returnValue(true));
$this->accessDecisionManager
->expects($this->once())
->method('decide')
->will($this->returnValue($decide));
$this->tokenStorage->setToken($token);
$this->assertTrue($decide === $this->authorizationChecker->isGranted('ROLE_FOO'));
}
public function isGrantedProvider()
{
return array(array(true), array(false));
}
}

View File

@@ -0,0 +1,44 @@
<?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\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\DebugAccessDecisionManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class DebugAccessDecisionManagerTest extends TestCase
{
/**
* @dataProvider provideObjectsAndLogs
*/
public function testDecideLog($expectedLog, $object)
{
$adm = new DebugAccessDecisionManager(new AccessDecisionManager());
$adm->decide($this->getMockBuilder(TokenInterface::class)->getMock(), array('ATTRIBUTE_1'), $object);
$this->assertSame($expectedLog, $adm->getDecisionLog());
}
public function provideObjectsAndLogs()
{
$object = new \stdClass();
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => null, 'result' => false)), null);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => true, 'result' => false)), true);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => 'jolie string', 'result' => false)), 'jolie string');
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => 12345, 'result' => false)), 12345);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => $x = fopen(__FILE__, 'r'), 'result' => false)), $x);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => $x = array(), 'result' => false)), $x);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => $object, 'result' => false)), $object);
}
}

View File

@@ -0,0 +1,80 @@
<?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\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;
class ExpressionLanguageTest extends TestCase
{
/**
* @dataProvider provider
*/
public function testIsAuthenticated($token, $expression, $result, array $roles = array())
{
$anonymousTokenClass = 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken';
$rememberMeTokenClass = 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken';
$expressionLanguage = new ExpressionLanguage();
$trustResolver = new AuthenticationTrustResolver($anonymousTokenClass, $rememberMeTokenClass);
$context = array();
$context['trust_resolver'] = $trustResolver;
$context['token'] = $token;
$context['roles'] = $roles;
$this->assertEquals($result, $expressionLanguage->evaluate($expression, $context));
}
public function provider()
{
$roles = array('ROLE_USER', 'ROLE_ADMIN');
$user = new User('username', 'password', $roles);
$noToken = null;
$anonymousToken = new AnonymousToken('firewall', 'anon.');
$rememberMeToken = new RememberMeToken($user, 'providerkey', 'firewall');
$usernamePasswordToken = new UsernamePasswordToken('username', 'password', 'providerkey', $roles);
return array(
array($noToken, 'is_anonymous()', false),
array($noToken, 'is_authenticated()', false),
array($noToken, 'is_fully_authenticated()', false),
array($noToken, 'is_remember_me()', false),
array($noToken, "has_role('ROLE_USER')", false),
array($anonymousToken, 'is_anonymous()', true),
array($anonymousToken, 'is_authenticated()', false),
array($anonymousToken, 'is_fully_authenticated()', false),
array($anonymousToken, 'is_remember_me()', false),
array($anonymousToken, "has_role('ROLE_USER')", false),
array($rememberMeToken, 'is_anonymous()', false),
array($rememberMeToken, 'is_authenticated()', true),
array($rememberMeToken, 'is_fully_authenticated()', false),
array($rememberMeToken, 'is_remember_me()', true),
array($rememberMeToken, "has_role('ROLE_FOO')", false, $roles),
array($rememberMeToken, "has_role('ROLE_USER')", true, $roles),
array($usernamePasswordToken, 'is_anonymous()', false),
array($usernamePasswordToken, 'is_authenticated()', true),
array($usernamePasswordToken, 'is_fully_authenticated()', true),
array($usernamePasswordToken, 'is_remember_me()', false),
array($usernamePasswordToken, "has_role('ROLE_FOO')", false, $roles),
array($usernamePasswordToken, "has_role('ROLE_USER')", true, $roles),
);
}
}

View File

@@ -0,0 +1,73 @@
<?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\Tests\Authorization\Voter;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class AuthenticatedVoterTest extends TestCase
{
/**
* @dataProvider getVoteTests
*/
public function testVote($authenticated, $attributes, $expected)
{
$voter = new AuthenticatedVoter($this->getResolver());
$this->assertSame($expected, $voter->vote($this->getToken($authenticated), null, $attributes));
}
public function getVoteTests()
{
return array(
array('fully', array(), VoterInterface::ACCESS_ABSTAIN),
array('fully', array('FOO'), VoterInterface::ACCESS_ABSTAIN),
array('remembered', array(), VoterInterface::ACCESS_ABSTAIN),
array('remembered', array('FOO'), VoterInterface::ACCESS_ABSTAIN),
array('anonymously', array(), VoterInterface::ACCESS_ABSTAIN),
array('anonymously', array('FOO'), VoterInterface::ACCESS_ABSTAIN),
array('fully', array('IS_AUTHENTICATED_ANONYMOUSLY'), VoterInterface::ACCESS_GRANTED),
array('remembered', array('IS_AUTHENTICATED_ANONYMOUSLY'), VoterInterface::ACCESS_GRANTED),
array('anonymously', array('IS_AUTHENTICATED_ANONYMOUSLY'), VoterInterface::ACCESS_GRANTED),
array('fully', array('IS_AUTHENTICATED_REMEMBERED'), VoterInterface::ACCESS_GRANTED),
array('remembered', array('IS_AUTHENTICATED_REMEMBERED'), VoterInterface::ACCESS_GRANTED),
array('anonymously', array('IS_AUTHENTICATED_REMEMBERED'), VoterInterface::ACCESS_DENIED),
array('fully', array('IS_AUTHENTICATED_FULLY'), VoterInterface::ACCESS_GRANTED),
array('remembered', array('IS_AUTHENTICATED_FULLY'), VoterInterface::ACCESS_DENIED),
array('anonymously', array('IS_AUTHENTICATED_FULLY'), VoterInterface::ACCESS_DENIED),
);
}
protected function getResolver()
{
return new AuthenticationTrustResolver(
'Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken',
'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken'
);
}
protected function getToken($authenticated)
{
if ('fully' === $authenticated) {
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
} elseif ('remembered' === $authenticated) {
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(array('setPersistent'))->disableOriginalConstructor()->getMock();
} else {
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setConstructorArgs(array('', ''))->getMock();
}
}
}

View File

@@ -0,0 +1,89 @@
<?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\Tests\Authorization\Voter;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\Role;
class ExpressionVoterTest extends TestCase
{
/**
* @dataProvider getVoteTests
*/
public function testVote($roles, $attributes, $expected, $tokenExpectsGetRoles = true, $expressionLanguageExpectsEvaluate = true)
{
$voter = new ExpressionVoter($this->createExpressionLanguage($expressionLanguageExpectsEvaluate), $this->createTrustResolver());
$this->assertSame($expected, $voter->vote($this->getToken($roles, $tokenExpectsGetRoles), null, $attributes));
}
public function getVoteTests()
{
return array(
array(array(), array(), VoterInterface::ACCESS_ABSTAIN, false, false),
array(array(), array('FOO'), VoterInterface::ACCESS_ABSTAIN, false, false),
array(array(), array($this->createExpression()), VoterInterface::ACCESS_DENIED, true, false),
array(array('ROLE_FOO'), array($this->createExpression(), $this->createExpression()), VoterInterface::ACCESS_GRANTED),
array(array('ROLE_BAR', 'ROLE_FOO'), array($this->createExpression()), VoterInterface::ACCESS_GRANTED),
);
}
protected function getToken(array $roles, $tokenExpectsGetRoles = true)
{
foreach ($roles as $i => $role) {
$roles[$i] = new Role($role);
}
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
if ($tokenExpectsGetRoles) {
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue($roles));
}
return $token;
}
protected function createExpressionLanguage($expressionLanguageExpectsEvaluate = true)
{
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\ExpressionLanguage')->getMock();
if ($expressionLanguageExpectsEvaluate) {
$mock->expects($this->once())
->method('evaluate')
->will($this->returnValue(true));
}
return $mock;
}
protected function createTrustResolver()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface')->getMock();
}
protected function createRoleHierarchy()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Role\RoleHierarchyInterface')->getMock();
}
protected function createExpression()
{
return $this->getMockBuilder('Symfony\Component\ExpressionLanguage\Expression')
->disableOriginalConstructor()
->getMock();
}
}

View File

@@ -0,0 +1,51 @@
<?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\Tests\Authorization\Voter;
use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
class RoleHierarchyVoterTest extends RoleVoterTest
{
/**
* @dataProvider getVoteTests
*/
public function testVote($roles, $attributes, $expected)
{
$voter = new RoleHierarchyVoter(new RoleHierarchy(array('ROLE_FOO' => array('ROLE_FOOBAR'))));
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
public function getVoteTests()
{
return array_merge(parent::getVoteTests(), array(
array(array('ROLE_FOO'), array('ROLE_FOOBAR'), VoterInterface::ACCESS_GRANTED),
));
}
/**
* @dataProvider getVoteWithEmptyHierarchyTests
*/
public function testVoteWithEmptyHierarchy($roles, $attributes, $expected)
{
$voter = new RoleHierarchyVoter(new RoleHierarchy(array()));
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
public function getVoteWithEmptyHierarchyTests()
{
return parent::getVoteTests();
}
}

View File

@@ -0,0 +1,61 @@
<?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\Tests\Authorization\Voter;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\Role;
class RoleVoterTest extends TestCase
{
/**
* @dataProvider getVoteTests
*/
public function testVote($roles, $attributes, $expected)
{
$voter = new RoleVoter();
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
public function getVoteTests()
{
return array(
array(array(), array(), VoterInterface::ACCESS_ABSTAIN),
array(array(), array('FOO'), VoterInterface::ACCESS_ABSTAIN),
array(array(), array('ROLE_FOO'), VoterInterface::ACCESS_DENIED),
array(array('ROLE_FOO'), array('ROLE_FOO'), VoterInterface::ACCESS_GRANTED),
array(array('ROLE_FOO'), array('FOO', 'ROLE_FOO'), VoterInterface::ACCESS_GRANTED),
array(array('ROLE_BAR', 'ROLE_FOO'), array('ROLE_FOO'), VoterInterface::ACCESS_GRANTED),
// Test mixed Types
array(array(), array(array()), VoterInterface::ACCESS_ABSTAIN),
array(array(), array(new \stdClass()), VoterInterface::ACCESS_ABSTAIN),
array(array('ROLE_BAR'), array(new Role('ROLE_BAR')), VoterInterface::ACCESS_GRANTED),
array(array('ROLE_BAR'), array(new Role('ROLE_FOO')), VoterInterface::ACCESS_DENIED),
);
}
protected function getToken(array $roles)
{
foreach ($roles as $i => $role) {
$roles[$i] = new Role($role);
}
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue($roles));
return $token;
}
}

View File

@@ -0,0 +1,71 @@
<?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\Tests\Authorization\Voter;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class VoterTest extends TestCase
{
protected $token;
protected function setUp()
{
$this->token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
}
public function getTests()
{
return array(
array(array('EDIT'), VoterInterface::ACCESS_GRANTED, new \stdClass(), 'ACCESS_GRANTED if attribute and class are supported and attribute grants access'),
array(array('CREATE'), VoterInterface::ACCESS_DENIED, new \stdClass(), 'ACCESS_DENIED if attribute and class are supported and attribute does not grant access'),
array(array('DELETE', 'EDIT'), VoterInterface::ACCESS_GRANTED, new \stdClass(), 'ACCESS_GRANTED if one attribute is supported and grants access'),
array(array('DELETE', 'CREATE'), VoterInterface::ACCESS_DENIED, new \stdClass(), 'ACCESS_DENIED if one attribute is supported and denies access'),
array(array('CREATE', 'EDIT'), VoterInterface::ACCESS_GRANTED, new \stdClass(), 'ACCESS_GRANTED if one attribute grants access'),
array(array('DELETE'), VoterInterface::ACCESS_ABSTAIN, new \stdClass(), 'ACCESS_ABSTAIN if no attribute is supported'),
array(array('EDIT'), VoterInterface::ACCESS_ABSTAIN, $this, 'ACCESS_ABSTAIN if class is not supported'),
array(array('EDIT'), VoterInterface::ACCESS_ABSTAIN, null, 'ACCESS_ABSTAIN if object is null'),
array(array(), VoterInterface::ACCESS_ABSTAIN, new \stdClass(), 'ACCESS_ABSTAIN if no attributes were provided'),
);
}
/**
* @dataProvider getTests
*/
public function testVote(array $attributes, $expectedVote, $object, $message)
{
$voter = new VoterTest_Voter();
$this->assertEquals($expectedVote, $voter->vote($this->token, $object, $attributes), $message);
}
}
class VoterTest_Voter extends Voter
{
protected function voteOnAttribute($attribute, $object, TokenInterface $token)
{
return 'EDIT' === $attribute;
}
protected function supports($attribute, $object)
{
return $object instanceof \stdClass && in_array($attribute, array('EDIT', 'CREATE'));
}
}

View File

@@ -0,0 +1,90 @@
<?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\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;
/**
* @author Elnur Abdurrakhimov <elnur@elnur.pro>
*/
class BCryptPasswordEncoderTest extends TestCase
{
const PASSWORD = 'password';
const VALID_COST = '04';
/**
* @expectedException \InvalidArgumentException
*/
public function testCostBelowRange()
{
new BCryptPasswordEncoder(3);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testCostAboveRange()
{
new BCryptPasswordEncoder(32);
}
/**
* @dataProvider validRangeData
*/
public function testCostInRange($cost)
{
$this->assertInstanceOf('Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder', new BCryptPasswordEncoder($cost));
}
public function validRangeData()
{
$costs = range(4, 31);
array_walk($costs, function (&$cost) { $cost = array($cost); });
return $costs;
}
public function testResultLength()
{
$encoder = new BCryptPasswordEncoder(self::VALID_COST);
$result = $encoder->encodePassword(self::PASSWORD, null);
$this->assertEquals(60, strlen($result));
}
public function testValidation()
{
$encoder = new BCryptPasswordEncoder(self::VALID_COST);
$result = $encoder->encodePassword(self::PASSWORD, null);
$this->assertTrue($encoder->isPasswordValid($result, self::PASSWORD, null));
$this->assertFalse($encoder->isPasswordValid($result, 'anotherPassword', null));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testEncodePasswordLength()
{
$encoder = new BCryptPasswordEncoder(self::VALID_COST);
$encoder->encodePassword(str_repeat('a', 73), 'salt');
}
public function testCheckPasswordLength()
{
$encoder = new BCryptPasswordEncoder(self::VALID_COST);
$result = $encoder->encodePassword(str_repeat('a', 72), null);
$this->assertFalse($encoder->isPasswordValid($result, str_repeat('a', 73), 'salt'));
$this->assertTrue($encoder->isPasswordValid($result, str_repeat('a', 72), 'salt'));
}
}

View File

@@ -0,0 +1,102 @@
<?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\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;
class PasswordEncoder extends BasePasswordEncoder
{
public function encodePassword($raw, $salt)
{
}
public function isPasswordValid($encoded, $raw, $salt)
{
}
}
class BasePasswordEncoderTest extends TestCase
{
public function testComparePassword()
{
$this->assertTrue($this->invokeComparePasswords('password', 'password'));
$this->assertFalse($this->invokeComparePasswords('password', 'foo'));
}
public function testDemergePasswordAndSalt()
{
$this->assertEquals(array('password', 'salt'), $this->invokeDemergePasswordAndSalt('password{salt}'));
$this->assertEquals(array('password', ''), $this->invokeDemergePasswordAndSalt('password'));
$this->assertEquals(array('', ''), $this->invokeDemergePasswordAndSalt(''));
}
public function testMergePasswordAndSalt()
{
$this->assertEquals('password{salt}', $this->invokeMergePasswordAndSalt('password', 'salt'));
$this->assertEquals('password', $this->invokeMergePasswordAndSalt('password', ''));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testMergePasswordAndSaltWithException()
{
$this->invokeMergePasswordAndSalt('password', '{foo}');
}
public function testIsPasswordTooLong()
{
$this->assertTrue($this->invokeIsPasswordTooLong(str_repeat('a', 10000)));
$this->assertFalse($this->invokeIsPasswordTooLong(str_repeat('a', 10)));
}
protected function invokeDemergePasswordAndSalt($password)
{
$encoder = new PasswordEncoder();
$r = new \ReflectionObject($encoder);
$m = $r->getMethod('demergePasswordAndSalt');
$m->setAccessible(true);
return $m->invoke($encoder, $password);
}
protected function invokeMergePasswordAndSalt($password, $salt)
{
$encoder = new PasswordEncoder();
$r = new \ReflectionObject($encoder);
$m = $r->getMethod('mergePasswordAndSalt');
$m->setAccessible(true);
return $m->invoke($encoder, $password, $salt);
}
protected function invokeComparePasswords($p1, $p2)
{
$encoder = new PasswordEncoder();
$r = new \ReflectionObject($encoder);
$m = $r->getMethod('comparePasswords');
$m->setAccessible(true);
return $m->invoke($encoder, $p1, $p2);
}
protected function invokeIsPasswordTooLong($p)
{
$encoder = new PasswordEncoder();
$r = new \ReflectionObject($encoder);
$m = $r->getMethod('isPasswordTooLong');
$m->setAccessible(true);
return $m->invoke($encoder, $p);
}
}

View File

@@ -0,0 +1,173 @@
<?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\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\EncoderAwareInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
class EncoderFactoryTest extends TestCase
{
public function testGetEncoderWithMessageDigestEncoder()
{
$factory = new EncoderFactory(array('Symfony\Component\Security\Core\User\UserInterface' => array(
'class' => 'Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder',
'arguments' => array('sha512', true, 5),
)));
$encoder = $factory->getEncoder($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock());
$expectedEncoder = new MessageDigestPasswordEncoder('sha512', true, 5);
$this->assertEquals($expectedEncoder->encodePassword('foo', 'moo'), $encoder->encodePassword('foo', 'moo'));
}
public function testGetEncoderWithService()
{
$factory = new EncoderFactory(array(
'Symfony\Component\Security\Core\User\UserInterface' => new MessageDigestPasswordEncoder('sha1'),
));
$encoder = $factory->getEncoder($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock());
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
$this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
$encoder = $factory->getEncoder(new User('user', 'pass'));
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
$this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
}
public function testGetEncoderWithClassName()
{
$factory = new EncoderFactory(array(
'Symfony\Component\Security\Core\User\UserInterface' => new MessageDigestPasswordEncoder('sha1'),
));
$encoder = $factory->getEncoder('Symfony\Component\Security\Core\Tests\Encoder\SomeChildUser');
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
$this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
}
public function testGetEncoderConfiguredForConcreteClassWithService()
{
$factory = new EncoderFactory(array(
'Symfony\Component\Security\Core\User\User' => new MessageDigestPasswordEncoder('sha1'),
));
$encoder = $factory->getEncoder(new User('user', 'pass'));
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
$this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
}
public function testGetEncoderConfiguredForConcreteClassWithClassName()
{
$factory = new EncoderFactory(array(
'Symfony\Component\Security\Core\Tests\Encoder\SomeUser' => new MessageDigestPasswordEncoder('sha1'),
));
$encoder = $factory->getEncoder('Symfony\Component\Security\Core\Tests\Encoder\SomeChildUser');
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
$this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
}
public function testGetNamedEncoderForEncoderAware()
{
$factory = new EncoderFactory(array(
'Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser' => new MessageDigestPasswordEncoder('sha256'),
'encoder_name' => new MessageDigestPasswordEncoder('sha1'),
));
$encoder = $factory->getEncoder(new EncAwareUser('user', 'pass'));
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
$this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
}
public function testGetNullNamedEncoderForEncoderAware()
{
$factory = new EncoderFactory(array(
'Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser' => new MessageDigestPasswordEncoder('sha1'),
'encoder_name' => new MessageDigestPasswordEncoder('sha256'),
));
$user = new EncAwareUser('user', 'pass');
$user->encoderName = null;
$encoder = $factory->getEncoder($user);
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
$this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
}
/**
* @expectedException \RuntimeException
*/
public function testGetInvalidNamedEncoderForEncoderAware()
{
$factory = new EncoderFactory(array(
'Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser' => new MessageDigestPasswordEncoder('sha1'),
'encoder_name' => new MessageDigestPasswordEncoder('sha256'),
));
$user = new EncAwareUser('user', 'pass');
$user->encoderName = 'invalid_encoder_name';
$encoder = $factory->getEncoder($user);
}
public function testGetEncoderForEncoderAwareWithClassName()
{
$factory = new EncoderFactory(array(
'Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser' => new MessageDigestPasswordEncoder('sha1'),
'encoder_name' => new MessageDigestPasswordEncoder('sha256'),
));
$encoder = $factory->getEncoder('Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser');
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
$this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
}
}
class SomeUser implements UserInterface
{
public function getRoles()
{
}
public function getPassword()
{
}
public function getSalt()
{
}
public function getUsername()
{
}
public function eraseCredentials()
{
}
}
class SomeChildUser extends SomeUser
{
}
class EncAwareUser extends SomeUser implements EncoderAwareInterface
{
public $encoderName = 'encoder_name';
public function getEncoderName()
{
return $this->encoderName;
}
}

View File

@@ -0,0 +1,63 @@
<?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\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
class MessageDigestPasswordEncoderTest extends TestCase
{
public function testIsPasswordValid()
{
$encoder = new MessageDigestPasswordEncoder('sha256', false, 1);
$this->assertTrue($encoder->isPasswordValid(hash('sha256', 'password'), 'password', ''));
}
public function testEncodePassword()
{
$encoder = new MessageDigestPasswordEncoder('sha256', false, 1);
$this->assertSame(hash('sha256', 'password'), $encoder->encodePassword('password', ''));
$encoder = new MessageDigestPasswordEncoder('sha256', true, 1);
$this->assertSame(base64_encode(hash('sha256', 'password', true)), $encoder->encodePassword('password', ''));
$encoder = new MessageDigestPasswordEncoder('sha256', false, 2);
$this->assertSame(hash('sha256', hash('sha256', 'password', true).'password'), $encoder->encodePassword('password', ''));
}
/**
* @expectedException \LogicException
*/
public function testEncodePasswordAlgorithmDoesNotExist()
{
$encoder = new MessageDigestPasswordEncoder('foobar');
$encoder->encodePassword('password', '');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testEncodePasswordLength()
{
$encoder = new MessageDigestPasswordEncoder();
$encoder->encodePassword(str_repeat('a', 5000), 'salt');
}
public function testCheckPasswordLength()
{
$encoder = new MessageDigestPasswordEncoder();
$this->assertFalse($encoder->isPasswordValid('encoded', str_repeat('a', 5000), 'salt'));
}
}

View File

@@ -0,0 +1,63 @@
<?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\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder;
class Pbkdf2PasswordEncoderTest extends TestCase
{
public function testIsPasswordValid()
{
$encoder = new Pbkdf2PasswordEncoder('sha256', false, 1, 40);
$this->assertTrue($encoder->isPasswordValid('c1232f10f62715fda06ae7c0a2037ca19b33cf103b727ba56d870c11f290a2ab106974c75607c8a3', 'password', ''));
}
public function testEncodePassword()
{
$encoder = new Pbkdf2PasswordEncoder('sha256', false, 1, 40);
$this->assertSame('c1232f10f62715fda06ae7c0a2037ca19b33cf103b727ba56d870c11f290a2ab106974c75607c8a3', $encoder->encodePassword('password', ''));
$encoder = new Pbkdf2PasswordEncoder('sha256', true, 1, 40);
$this->assertSame('wSMvEPYnFf2gaufAogN8oZszzxA7cnulbYcMEfKQoqsQaXTHVgfIow==', $encoder->encodePassword('password', ''));
$encoder = new Pbkdf2PasswordEncoder('sha256', false, 2, 40);
$this->assertSame('8bc2f9167a81cdcfad1235cd9047f1136271c1f978fcfcb35e22dbeafa4634f6fd2214218ed63ebb', $encoder->encodePassword('password', ''));
}
/**
* @expectedException \LogicException
*/
public function testEncodePasswordAlgorithmDoesNotExist()
{
$encoder = new Pbkdf2PasswordEncoder('foobar');
$encoder->encodePassword('password', '');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testEncodePasswordLength()
{
$encoder = new Pbkdf2PasswordEncoder('foobar');
$encoder->encodePassword(str_repeat('a', 5000), 'salt');
}
public function testCheckPasswordLength()
{
$encoder = new Pbkdf2PasswordEncoder('foobar');
$this->assertFalse($encoder->isPasswordValid('encoded', str_repeat('a', 5000), 'salt'));
}
}

View File

@@ -0,0 +1,57 @@
<?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\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
class PlaintextPasswordEncoderTest extends TestCase
{
public function testIsPasswordValid()
{
$encoder = new PlaintextPasswordEncoder();
$this->assertTrue($encoder->isPasswordValid('foo', 'foo', ''));
$this->assertFalse($encoder->isPasswordValid('bar', 'foo', ''));
$this->assertFalse($encoder->isPasswordValid('FOO', 'foo', ''));
$encoder = new PlaintextPasswordEncoder(true);
$this->assertTrue($encoder->isPasswordValid('foo', 'foo', ''));
$this->assertFalse($encoder->isPasswordValid('bar', 'foo', ''));
$this->assertTrue($encoder->isPasswordValid('FOO', 'foo', ''));
}
public function testEncodePassword()
{
$encoder = new PlaintextPasswordEncoder();
$this->assertSame('foo', $encoder->encodePassword('foo', ''));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testEncodePasswordLength()
{
$encoder = new PlaintextPasswordEncoder();
$encoder->encodePassword(str_repeat('a', 5000), 'salt');
}
public function testCheckPasswordLength()
{
$encoder = new PlaintextPasswordEncoder();
$this->assertFalse($encoder->isPasswordValid('encoded', str_repeat('a', 5000), 'salt'));
}
}

View File

@@ -0,0 +1,71 @@
<?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\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
class UserPasswordEncoderTest extends TestCase
{
public function testEncodePassword()
{
$userMock = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$userMock->expects($this->any())
->method('getSalt')
->will($this->returnValue('userSalt'));
$mockEncoder = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface')->getMock();
$mockEncoder->expects($this->any())
->method('encodePassword')
->with($this->equalTo('plainPassword'), $this->equalTo('userSalt'))
->will($this->returnValue('encodedPassword'));
$mockEncoderFactory = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')->getMock();
$mockEncoderFactory->expects($this->any())
->method('getEncoder')
->with($this->equalTo($userMock))
->will($this->returnValue($mockEncoder));
$passwordEncoder = new UserPasswordEncoder($mockEncoderFactory);
$encoded = $passwordEncoder->encodePassword($userMock, 'plainPassword');
$this->assertEquals('encodedPassword', $encoded);
}
public function testIsPasswordValid()
{
$userMock = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$userMock->expects($this->any())
->method('getSalt')
->will($this->returnValue('userSalt'));
$userMock->expects($this->any())
->method('getPassword')
->will($this->returnValue('encodedPassword'));
$mockEncoder = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface')->getMock();
$mockEncoder->expects($this->any())
->method('isPasswordValid')
->with($this->equalTo('encodedPassword'), $this->equalTo('plainPassword'), $this->equalTo('userSalt'))
->will($this->returnValue(true));
$mockEncoderFactory = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')->getMock();
$mockEncoderFactory->expects($this->any())
->method('getEncoder')
->with($this->equalTo($userMock))
->will($this->returnValue($mockEncoder));
$passwordEncoder = new UserPasswordEncoder($mockEncoderFactory);
$isValid = $passwordEncoder->isPasswordValid($userMock, 'plainPassword');
$this->assertTrue($isValid);
}
}

View File

@@ -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\Security\Core\Tests\Exception;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
class CustomUserMessageAuthenticationExceptionTest extends TestCase
{
public function testConstructWithSAfeMessage()
{
$e = new CustomUserMessageAuthenticationException('SAFE MESSAGE', array('foo' => true));
$this->assertEquals('SAFE MESSAGE', $e->getMessageKey());
$this->assertEquals(array('foo' => true), $e->getMessageData());
$this->assertEquals('SAFE MESSAGE', $e->getMessage());
}
}

View File

@@ -0,0 +1,26 @@
<?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\Tests\Exception;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
class UsernameNotFoundExceptionTest extends TestCase
{
public function testGetMessageData()
{
$exception = new UsernameNotFoundException('Username could not be found.');
$this->assertEquals(array('{{ username }}' => null), $exception->getMessageData());
$exception->setUsername('username');
$this->assertEquals(array('{{ username }}' => 'username'), $exception->getMessageData());
}
}

View File

@@ -0,0 +1,39 @@
<?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\Tests\Resources;
use PHPUnit\Framework\TestCase;
class TranslationFilesTest extends TestCase
{
/**
* @dataProvider provideTranslationFiles
*/
public function testTranslationFileIsValid($filePath)
{
if (class_exists('PHPUnit_Util_XML')) {
\PHPUnit_Util_XML::loadfile($filePath, false, false, true);
} else {
\PHPUnit\Util\XML::loadfile($filePath, false, false, true);
}
$this->addToAssertionCount(1);
}
public function provideTranslationFiles()
{
return array_map(
function ($filePath) { return (array) $filePath; },
glob(dirname(dirname(__DIR__)).'/Resources/translations/*.xlf')
);
}
}

View File

@@ -0,0 +1,33 @@
<?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\Tests\Role;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\Role\Role;
class RoleHierarchyTest extends TestCase
{
public function testGetReachableRoles()
{
$role = new RoleHierarchy(array(
'ROLE_ADMIN' => array('ROLE_USER'),
'ROLE_SUPER_ADMIN' => array('ROLE_ADMIN', 'ROLE_FOO'),
));
$this->assertEquals(array(new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_USER'))));
$this->assertEquals(array(new Role('ROLE_FOO')), $role->getReachableRoles(array(new Role('ROLE_FOO'))));
$this->assertEquals(array(new Role('ROLE_ADMIN'), new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_ADMIN'))));
$this->assertEquals(array(new Role('ROLE_FOO'), new Role('ROLE_ADMIN'), new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_FOO'), new Role('ROLE_ADMIN'))));
$this->assertEquals(array(new Role('ROLE_SUPER_ADMIN'), new Role('ROLE_ADMIN'), new Role('ROLE_FOO'), new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_SUPER_ADMIN'))));
}
}

View File

@@ -0,0 +1,25 @@
<?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\Tests\Role;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Role\Role;
class RoleTest extends TestCase
{
public function testGetRole()
{
$role = new Role('FOO');
$this->assertEquals('FOO', $role->getRole());
}
}

View File

@@ -0,0 +1,32 @@
<?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\Tests\Role;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
class SwitchUserRoleTest extends TestCase
{
public function testGetSource()
{
$role = new SwitchUserRole('FOO', $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertSame($token, $role->getSource());
}
public function testGetRole()
{
$role = new SwitchUserRole('FOO', $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertEquals('FOO', $role->getRole());
}
}

View File

@@ -0,0 +1,184 @@
<?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\Tests\User;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\ChainUserProvider;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
class ChainUserProviderTest extends TestCase
{
public function testLoadUserByUsername()
{
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foo'))
->will($this->throwException(new UsernameNotFoundException('not found')))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foo'))
->will($this->returnValue($account = $this->getAccount()))
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$this->assertSame($account, $provider->loadUserByUsername('foo'));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameThrowsUsernameNotFoundException()
{
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foo'))
->will($this->throwException(new UsernameNotFoundException('not found')))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foo'))
->will($this->throwException(new UsernameNotFoundException('not found')))
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$provider->loadUserByUsername('foo');
}
public function testRefreshUser()
{
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('refreshUser')
->will($this->throwException(new UnsupportedUserException('unsupported')))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('refreshUser')
->will($this->returnValue($account = $this->getAccount()))
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$this->assertSame($account, $provider->refreshUser($this->getAccount()));
}
public function testRefreshUserAgain()
{
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('refreshUser')
->will($this->throwException(new UsernameNotFoundException('not found')))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('refreshUser')
->will($this->returnValue($account = $this->getAccount()))
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$this->assertSame($account, $provider->refreshUser($this->getAccount()));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UnsupportedUserException
*/
public function testRefreshUserThrowsUnsupportedUserException()
{
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('refreshUser')
->will($this->throwException(new UnsupportedUserException('unsupported')))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('refreshUser')
->will($this->throwException(new UnsupportedUserException('unsupported')))
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$provider->refreshUser($this->getAccount());
}
public function testSupportsClass()
{
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('supportsClass')
->with($this->equalTo('foo'))
->will($this->returnValue(false))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('supportsClass')
->with($this->equalTo('foo'))
->will($this->returnValue(true))
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$this->assertTrue($provider->supportsClass('foo'));
}
public function testSupportsClassWhenNotSupported()
{
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('supportsClass')
->with($this->equalTo('foo'))
->will($this->returnValue(false))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('supportsClass')
->with($this->equalTo('foo'))
->will($this->returnValue(false))
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$this->assertFalse($provider->supportsClass('foo'));
}
protected function getAccount()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
}
protected function getProvider()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
}
}

View File

@@ -0,0 +1,84 @@
<?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\Tests\User;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\User;
class InMemoryUserProviderTest extends TestCase
{
public function testConstructor()
{
$provider = $this->createProvider();
$user = $provider->loadUserByUsername('fabien');
$this->assertEquals('foo', $user->getPassword());
$this->assertEquals(array('ROLE_USER'), $user->getRoles());
$this->assertFalse($user->isEnabled());
}
public function testRefresh()
{
$user = new User('fabien', 'bar');
$provider = $this->createProvider();
$refreshedUser = $provider->refreshUser($user);
$this->assertEquals('foo', $refreshedUser->getPassword());
$this->assertEquals(array('ROLE_USER'), $refreshedUser->getRoles());
$this->assertFalse($refreshedUser->isEnabled());
$this->assertFalse($refreshedUser->isCredentialsNonExpired());
}
/**
* @return InMemoryUserProvider
*/
protected function createProvider()
{
return new InMemoryUserProvider(array(
'fabien' => array(
'password' => 'foo',
'enabled' => false,
'roles' => array('ROLE_USER'),
),
));
}
public function testCreateUser()
{
$provider = new InMemoryUserProvider();
$provider->createUser(new User('fabien', 'foo'));
$user = $provider->loadUserByUsername('fabien');
$this->assertEquals('foo', $user->getPassword());
}
/**
* @expectedException \LogicException
*/
public function testCreateUserAlreadyExist()
{
$provider = new InMemoryUserProvider();
$provider->createUser(new User('fabien', 'foo'));
$provider->createUser(new User('fabien', 'foo'));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameDoesNotExist()
{
$provider = new InMemoryUserProvider();
$provider->loadUserByUsername('fabien');
}
}

View File

@@ -0,0 +1,362 @@
<?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\Tests\User;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Ldap\Adapter\CollectionInterface;
use Symfony\Component\Ldap\Adapter\QueryInterface;
use Symfony\Component\Ldap\Entry;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Security\Core\User\LdapUserProvider;
use Symfony\Component\Ldap\Exception\ConnectionException;
/**
* @requires extension ldap
*/
class LdapUserProviderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameFailsIfCantConnectToLdap()
{
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('bind')
->will($this->throwException(new ConnectionException()))
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
$provider->loadUserByUsername('foo');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameFailsIfNoLdapEntries()
{
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(0))
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
$provider->loadUserByUsername('foo');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameFailsIfMoreThanOneLdapEntry()
{
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(2))
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
$provider->loadUserByUsername('foo');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\InvalidArgumentException
*/
public function testLoadUserByUsernameFailsIfMoreThanOneLdapPasswordsInEntry()
{
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
'userpassword' => array('bar', 'baz'),
)
)))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, array(), 'sAMAccountName', '({uid_key}={username})', 'userpassword');
$this->assertInstanceOf(
'Symfony\Component\Security\Core\User\User',
$provider->loadUserByUsername('foo')
);
}
public function testLoadUserByUsernameShouldNotFailIfEntryHasNoUidKeyAttribute()
{
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array())))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, array(), 'sAMAccountName', '({uid_key}={username})');
$this->assertInstanceOf(
'Symfony\Component\Security\Core\User\User',
$provider->loadUserByUsername('foo')
);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\InvalidArgumentException
*/
public function testLoadUserByUsernameFailsIfEntryHasNoPasswordAttribute()
{
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
)
)))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, array(), 'sAMAccountName', '({uid_key}={username})', 'userpassword');
$this->assertInstanceOf(
'Symfony\Component\Security\Core\User\User',
$provider->loadUserByUsername('foo')
);
}
public function testLoadUserByUsernameIsSuccessfulWithoutPasswordAttribute()
{
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
)
)))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
$this->assertInstanceOf(
'Symfony\Component\Security\Core\User\User',
$provider->loadUserByUsername('foo')
);
}
public function testLoadUserByUsernameIsSuccessfulWithoutPasswordAttributeAndWrongCase()
{
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
)
)))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('Foo'))
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
$this->assertSame('foo', $provider->loadUserByUsername('Foo')->getUsername());
}
public function testLoadUserByUsernameIsSuccessfulWithPasswordAttribute()
{
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
'userpassword' => array('bar'),
)
)))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, array(), 'sAMAccountName', '({uid_key}={username})', 'userpassword');
$this->assertInstanceOf(
'Symfony\Component\Security\Core\User\User',
$provider->loadUserByUsername('foo')
);
}
}

View File

@@ -0,0 +1,109 @@
<?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\Tests\User;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\User\UserChecker;
class UserCheckerTest extends TestCase
{
public function testCheckPostAuthNotAdvancedUserInterface()
{
$checker = new UserChecker();
$this->assertNull($checker->checkPostAuth($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()));
}
public function testCheckPostAuthPass()
{
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isCredentialsNonExpired')->will($this->returnValue(true));
$this->assertNull($checker->checkPostAuth($account));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\CredentialsExpiredException
*/
public function testCheckPostAuthCredentialsExpired()
{
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isCredentialsNonExpired')->will($this->returnValue(false));
$checker->checkPostAuth($account);
}
public function testCheckPreAuthNotAdvancedUserInterface()
{
$checker = new UserChecker();
$this->assertNull($checker->checkPreAuth($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()));
}
public function testCheckPreAuthPass()
{
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true));
$account->expects($this->once())->method('isEnabled')->will($this->returnValue(true));
$account->expects($this->once())->method('isAccountNonExpired')->will($this->returnValue(true));
$this->assertNull($checker->checkPreAuth($account));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\LockedException
*/
public function testCheckPreAuthAccountLocked()
{
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(false));
$checker->checkPreAuth($account);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\DisabledException
*/
public function testCheckPreAuthDisabled()
{
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true));
$account->expects($this->once())->method('isEnabled')->will($this->returnValue(false));
$checker->checkPreAuth($account);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException
*/
public function testCheckPreAuthAccountExpired()
{
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true));
$account->expects($this->once())->method('isEnabled')->will($this->returnValue(true));
$account->expects($this->once())->method('isAccountNonExpired')->will($this->returnValue(false));
$checker->checkPreAuth($account);
}
}

View File

@@ -0,0 +1,102 @@
<?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\Tests\User;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\User\User;
class UserTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorException()
{
new User('', 'superpass');
}
public function testGetRoles()
{
$user = new User('fabien', 'superpass');
$this->assertEquals(array(), $user->getRoles());
$user = new User('fabien', 'superpass', array('ROLE_ADMIN'));
$this->assertEquals(array('ROLE_ADMIN'), $user->getRoles());
}
public function testGetPassword()
{
$user = new User('fabien', 'superpass');
$this->assertEquals('superpass', $user->getPassword());
}
public function testGetUsername()
{
$user = new User('fabien', 'superpass');
$this->assertEquals('fabien', $user->getUsername());
}
public function testGetSalt()
{
$user = new User('fabien', 'superpass');
$this->assertEquals('', $user->getSalt());
}
public function testIsAccountNonExpired()
{
$user = new User('fabien', 'superpass');
$this->assertTrue($user->isAccountNonExpired());
$user = new User('fabien', 'superpass', array(), true, false);
$this->assertFalse($user->isAccountNonExpired());
}
public function testIsCredentialsNonExpired()
{
$user = new User('fabien', 'superpass');
$this->assertTrue($user->isCredentialsNonExpired());
$user = new User('fabien', 'superpass', array(), true, true, false);
$this->assertFalse($user->isCredentialsNonExpired());
}
public function testIsAccountNonLocked()
{
$user = new User('fabien', 'superpass');
$this->assertTrue($user->isAccountNonLocked());
$user = new User('fabien', 'superpass', array(), true, true, true, false);
$this->assertFalse($user->isAccountNonLocked());
}
public function testIsEnabled()
{
$user = new User('fabien', 'superpass');
$this->assertTrue($user->isEnabled());
$user = new User('fabien', 'superpass', array(), false);
$this->assertFalse($user->isEnabled());
}
public function testEraseCredentials()
{
$user = new User('fabien', 'superpass');
$user->eraseCredentials();
$this->assertEquals('superpass', $user->getPassword());
}
public function testToString()
{
$user = new User('fabien', 'superpass');
$this->assertEquals('fabien', (string) $user);
}
}

View File

@@ -0,0 +1,192 @@
<?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\Tests\Validator\Constraints;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator;
use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
{
const PASSWORD = 's3Cr3t';
const SALT = '^S4lt$';
/**
* @var TokenStorageInterface
*/
protected $tokenStorage;
/**
* @var PasswordEncoderInterface
*/
protected $encoder;
/**
* @var EncoderFactoryInterface
*/
protected $encoderFactory;
protected function createValidator()
{
return new UserPasswordValidator($this->tokenStorage, $this->encoderFactory);
}
protected function setUp()
{
$user = $this->createUser();
$this->tokenStorage = $this->createTokenStorage($user);
$this->encoder = $this->createPasswordEncoder();
$this->encoderFactory = $this->createEncoderFactory($this->encoder);
parent::setUp();
}
public function testPasswordIsValid()
{
$constraint = new UserPassword(array(
'message' => 'myMessage',
));
$this->encoder->expects($this->once())
->method('isPasswordValid')
->with(static::PASSWORD, 'secret', static::SALT)
->will($this->returnValue(true));
$this->validator->validate('secret', $constraint);
$this->assertNoViolation();
}
public function testPasswordIsNotValid()
{
$constraint = new UserPassword(array(
'message' => 'myMessage',
));
$this->encoder->expects($this->once())
->method('isPasswordValid')
->with(static::PASSWORD, 'secret', static::SALT)
->will($this->returnValue(false));
$this->validator->validate('secret', $constraint);
$this->buildViolation('myMessage')
->assertRaised();
}
/**
* @dataProvider emptyPasswordData
*/
public function testEmptyPasswordsAreNotValid($password)
{
$constraint = new UserPassword(array(
'message' => 'myMessage',
));
$this->validator->validate($password, $constraint);
$this->buildViolation('myMessage')
->assertRaised();
}
public function emptyPasswordData()
{
return array(
array(null),
array(''),
);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testUserIsNotValid()
{
$user = $this->getMockBuilder('Foo\Bar\User')->getMock();
$this->tokenStorage = $this->createTokenStorage($user);
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
$this->validator->validate('secret', new UserPassword());
}
protected function createUser()
{
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$mock
->expects($this->any())
->method('getPassword')
->will($this->returnValue(static::PASSWORD))
;
$mock
->expects($this->any())
->method('getSalt')
->will($this->returnValue(static::SALT))
;
return $mock;
}
protected function createPasswordEncoder($isPasswordValid = true)
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface')->getMock();
}
protected function createEncoderFactory($encoder = null)
{
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')->getMock();
$mock
->expects($this->any())
->method('getEncoder')
->will($this->returnValue($encoder))
;
return $mock;
}
protected function createTokenStorage($user = null)
{
$token = $this->createAuthenticationToken($user);
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$mock
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
;
return $mock;
}
protected function createAuthenticationToken($user = null)
{
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$mock
->expects($this->any())
->method('getUser')
->will($this->returnValue($user))
;
return $mock;
}
}