summaryrefslogtreecommitdiffstats
path: root/Http/Tests/Firewall
diff options
context:
space:
mode:
Diffstat (limited to 'Http/Tests/Firewall')
-rw-r--r--Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.php252
-rw-r--r--Http/Tests/Firewall/AccessListenerTest.php208
-rw-r--r--Http/Tests/Firewall/AnonymousAuthenticationListenerTest.php72
-rw-r--r--Http/Tests/Firewall/BasicAuthenticationListenerTest.php249
-rw-r--r--Http/Tests/Firewall/ChannelListenerTest.php181
-rw-r--r--Http/Tests/Firewall/ContextListenerTest.php248
-rw-r--r--Http/Tests/Firewall/DigestDataTest.php181
-rw-r--r--Http/Tests/Firewall/LogoutListenerTest.php237
-rw-r--r--Http/Tests/Firewall/RememberMeListenerTest.php184
-rw-r--r--Http/Tests/Firewall/SwitchUserListenerTest.php202
-rw-r--r--Http/Tests/Firewall/X509AuthenticationListenerTest.php123
11 files changed, 2137 insertions, 0 deletions
diff --git a/Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.php b/Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.php
new file mode 100644
index 0000000..6e34532
--- /dev/null
+++ b/Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.php
@@ -0,0 +1,252 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
+use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
+use Symfony\Component\Security\Core\Exception\AuthenticationException;
+
+class AbstractPreAuthenticatedListenerTest extends \PHPUnit_Framework_TestCase
+{
+ public function testHandleWithValidValues()
+ {
+ $userCredentials = array('TheUser', 'TheCredentials');
+
+ $request = new Request(array(), array(), array(), array(), array(), array());
+
+ $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue(null))
+ ;
+ $context
+ ->expects($this->once())
+ ->method('setToken')
+ ->with($this->equalTo($token))
+ ;
+
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+ $authenticationManager
+ ->expects($this->once())
+ ->method('authenticate')
+ ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
+ ->will($this->returnValue($token))
+ ;
+
+ $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
+ $context,
+ $authenticationManager,
+ 'TheProviderKey',
+ ));
+ $listener
+ ->expects($this->once())
+ ->method('getPreAuthenticatedData')
+ ->will($this->returnValue($userCredentials));
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testHandleWhenAuthenticationFails()
+ {
+ $userCredentials = array('TheUser', 'TheCredentials');
+
+ $request = new Request(array(), array(), array(), array(), array(), array());
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue(null))
+ ;
+ $context
+ ->expects($this->never())
+ ->method('setToken')
+ ;
+
+ $exception = new AuthenticationException('Authentication failed.');
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+ $authenticationManager
+ ->expects($this->once())
+ ->method('authenticate')
+ ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
+ ->will($this->throwException($exception))
+ ;
+
+ $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
+ $context,
+ $authenticationManager,
+ 'TheProviderKey',
+ ));
+ $listener
+ ->expects($this->once())
+ ->method('getPreAuthenticatedData')
+ ->will($this->returnValue($userCredentials));
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testHandleWhenAuthenticationFailsWithDifferentToken()
+ {
+ $userCredentials = array('TheUser', 'TheCredentials');
+
+ $token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', array('ROLE_FOO'));
+
+ $request = new Request(array(), array(), array(), array(), array(), array());
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($token))
+ ;
+ $context
+ ->expects($this->never())
+ ->method('setToken')
+ ;
+
+ $exception = new AuthenticationException('Authentication failed.');
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+ $authenticationManager
+ ->expects($this->once())
+ ->method('authenticate')
+ ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
+ ->will($this->throwException($exception))
+ ;
+
+ $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
+ $context,
+ $authenticationManager,
+ 'TheProviderKey',
+ ));
+ $listener
+ ->expects($this->once())
+ ->method('getPreAuthenticatedData')
+ ->will($this->returnValue($userCredentials));
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testHandleWithASimilarAuthenticatedToken()
+ {
+ $userCredentials = array('TheUser', 'TheCredentials');
+
+ $request = new Request(array(), array(), array(), array(), array(), array());
+
+ $token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($token))
+ ;
+
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+ $authenticationManager
+ ->expects($this->never())
+ ->method('authenticate')
+ ;
+
+ $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
+ $context,
+ $authenticationManager,
+ 'TheProviderKey',
+ ));
+ $listener
+ ->expects($this->once())
+ ->method('getPreAuthenticatedData')
+ ->will($this->returnValue($userCredentials));
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testHandleWithAnInvalidSimilarToken()
+ {
+ $userCredentials = array('TheUser', 'TheCredentials');
+
+ $request = new Request(array(), array(), array(), array(), array(), array());
+
+ $token = new PreAuthenticatedToken('AnotherUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($token))
+ ;
+ $context
+ ->expects($this->once())
+ ->method('setToken')
+ ->with($this->equalTo(null))
+ ;
+
+ $exception = new AuthenticationException('Authentication failed.');
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+ $authenticationManager
+ ->expects($this->once())
+ ->method('authenticate')
+ ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
+ ->will($this->throwException($exception))
+ ;
+
+ $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
+ $context,
+ $authenticationManager,
+ 'TheProviderKey',
+ ));
+ $listener
+ ->expects($this->once())
+ ->method('getPreAuthenticatedData')
+ ->will($this->returnValue($userCredentials));
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+}
diff --git a/Http/Tests/Firewall/AccessListenerTest.php b/Http/Tests/Firewall/AccessListenerTest.php
new file mode 100644
index 0000000..f9b0f3c
--- /dev/null
+++ b/Http/Tests/Firewall/AccessListenerTest.php
@@ -0,0 +1,208 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\Security\Http\Firewall\AccessListener;
+
+class AccessListenerTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
+ */
+ public function testHandleWhenTheAccessDecisionManagerDecidesToRefuseAccess()
+ {
+ $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
+
+ $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
+ $accessMap
+ ->expects($this->any())
+ ->method('getPatterns')
+ ->with($this->equalTo($request))
+ ->will($this->returnValue(array(array('foo' => 'bar'), null)))
+ ;
+
+ $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+ $token
+ ->expects($this->any())
+ ->method('isAuthenticated')
+ ->will($this->returnValue(true))
+ ;
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($token))
+ ;
+
+ $accessDecisionManager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');
+ $accessDecisionManager
+ ->expects($this->once())
+ ->method('decide')
+ ->with($this->equalTo($token), $this->equalTo(array('foo' => 'bar')), $this->equalTo($request))
+ ->will($this->returnValue(false))
+ ;
+
+ $listener = new AccessListener(
+ $context,
+ $accessDecisionManager,
+ $accessMap,
+ $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')
+ );
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testHandleWhenTheTokenIsNotAuthenticated()
+ {
+ $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
+
+ $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
+ $accessMap
+ ->expects($this->any())
+ ->method('getPatterns')
+ ->with($this->equalTo($request))
+ ->will($this->returnValue(array(array('foo' => 'bar'), null)))
+ ;
+
+ $notAuthenticatedToken = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+ $notAuthenticatedToken
+ ->expects($this->any())
+ ->method('isAuthenticated')
+ ->will($this->returnValue(false))
+ ;
+
+ $authenticatedToken = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+ $authenticatedToken
+ ->expects($this->any())
+ ->method('isAuthenticated')
+ ->will($this->returnValue(true))
+ ;
+
+ $authManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+ $authManager
+ ->expects($this->once())
+ ->method('authenticate')
+ ->with($this->equalTo($notAuthenticatedToken))
+ ->will($this->returnValue($authenticatedToken))
+ ;
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($notAuthenticatedToken))
+ ;
+ $context
+ ->expects($this->once())
+ ->method('setToken')
+ ->with($this->equalTo($authenticatedToken))
+ ;
+
+ $accessDecisionManager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');
+ $accessDecisionManager
+ ->expects($this->once())
+ ->method('decide')
+ ->with($this->equalTo($authenticatedToken), $this->equalTo(array('foo' => 'bar')), $this->equalTo($request))
+ ->will($this->returnValue(true))
+ ;
+
+ $listener = new AccessListener(
+ $context,
+ $accessDecisionManager,
+ $accessMap,
+ $authManager
+ );
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testHandleWhenThereIsNoAccessMapEntryMatchingTheRequest()
+ {
+ $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
+
+ $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
+ $accessMap
+ ->expects($this->any())
+ ->method('getPatterns')
+ ->with($this->equalTo($request))
+ ->will($this->returnValue(array(null, null)))
+ ;
+
+ $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+ $token
+ ->expects($this->never())
+ ->method('isAuthenticated')
+ ;
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($token))
+ ;
+
+ $listener = new AccessListener(
+ $context,
+ $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface'),
+ $accessMap,
+ $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')
+ );
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ /**
+ * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
+ */
+ public function testHandleWhenTheSecurityContextHasNoToken()
+ {
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue(null))
+ ;
+
+ $listener = new AccessListener(
+ $context,
+ $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface'),
+ $this->getMock('Symfony\Component\Security\Http\AccessMapInterface'),
+ $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')
+ );
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+
+ $listener->handle($event);
+ }
+}
diff --git a/Http/Tests/Firewall/AnonymousAuthenticationListenerTest.php b/Http/Tests/Firewall/AnonymousAuthenticationListenerTest.php
new file mode 100644
index 0000000..1fb7350
--- /dev/null
+++ b/Http/Tests/Firewall/AnonymousAuthenticationListenerTest.php
@@ -0,0 +1,72 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\Security\Http\Firewall\AnonymousAuthenticationListener;
+
+class AnonymousAuthenticationListenerTest extends \PHPUnit_Framework_TestCase
+{
+ public function testHandleWithContextHavingAToken()
+ {
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')))
+ ;
+ $context
+ ->expects($this->never())
+ ->method('setToken')
+ ;
+
+ $listener = new AnonymousAuthenticationListener($context, 'TheKey');
+ $listener->handle($this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false));
+ }
+
+ public function testHandleWithContextHavingNoToken()
+ {
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue(null))
+ ;
+ $context
+ ->expects($this->once())
+ ->method('setToken')
+ ->with(self::logicalAnd(
+ $this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken'),
+ $this->attributeEqualTo('key', 'TheKey')
+ ))
+ ;
+
+ $listener = new AnonymousAuthenticationListener($context, 'TheKey');
+ $listener->handle($this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false));
+ }
+
+ public function testHandledEventIsLogged()
+ {
+ if (!interface_exists('Psr\Log\LoggerInterface')) {
+ $this->markTestSkipped('The "LoggerInterface" is not available');
+ }
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $logger = $this->getMock('Psr\Log\LoggerInterface');
+ $logger->expects($this->once())
+ ->method('info')
+ ->with('Populated SecurityContext with an anonymous Token')
+ ;
+
+ $listener = new AnonymousAuthenticationListener($context, 'TheKey', $logger);
+ $listener->handle($this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false));
+ }
+}
diff --git a/Http/Tests/Firewall/BasicAuthenticationListenerTest.php b/Http/Tests/Firewall/BasicAuthenticationListenerTest.php
new file mode 100644
index 0000000..0ef993f
--- /dev/null
+++ b/Http/Tests/Firewall/BasicAuthenticationListenerTest.php
@@ -0,0 +1,249 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
+use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\Security\Http\Firewall\BasicAuthenticationListener;
+use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
+
+class BasicAuthenticationListenerTest extends \PHPUnit_Framework_TestCase
+{
+ public function testHandleWithValidUsernameAndPasswordServerParameters()
+ {
+ $request = new Request(array(), array(), array(), array(), array(), array(
+ 'PHP_AUTH_USER' => 'TheUsername',
+ 'PHP_AUTH_PW' => 'ThePassword',
+ ));
+
+ $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue(null))
+ ;
+ $context
+ ->expects($this->once())
+ ->method('setToken')
+ ->with($this->equalTo($token))
+ ;
+
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+ $authenticationManager
+ ->expects($this->once())
+ ->method('authenticate')
+ ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken'))
+ ->will($this->returnValue($token))
+ ;
+
+ $listener = new BasicAuthenticationListener(
+ $context,
+ $authenticationManager,
+ 'TheProviderKey',
+ $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')
+ );
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testHandleWhenAuthenticationFails()
+ {
+ $request = new Request(array(), array(), array(), array(), array(), array(
+ 'PHP_AUTH_USER' => 'TheUsername',
+ 'PHP_AUTH_PW' => 'ThePassword',
+ ));
+
+ $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue(null))
+ ;
+ $context
+ ->expects($this->never())
+ ->method('setToken')
+ ;
+
+ $response = new Response();
+
+ $authenticationEntryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
+ $authenticationEntryPoint
+ ->expects($this->any())
+ ->method('start')
+ ->with($this->equalTo($request), $this->isInstanceOf('Symfony\Component\Security\Core\Exception\AuthenticationException'))
+ ->will($this->returnValue($response))
+ ;
+
+ $listener = new BasicAuthenticationListener(
+ $context,
+ new AuthenticationProviderManager(array($this->getMock('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface'))),
+ 'TheProviderKey',
+ $authenticationEntryPoint
+ );
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+ $event
+ ->expects($this->once())
+ ->method('setResponse')
+ ->with($this->equalTo($response))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testHandleWithNoUsernameServerParameter()
+ {
+ $request = new Request();
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->never())
+ ->method('getToken')
+ ;
+
+ $listener = new BasicAuthenticationListener(
+ $context,
+ $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'),
+ 'TheProviderKey',
+ $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')
+ );
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testHandleWithASimilarAuthenticatedToken()
+ {
+ $request = new Request(array(), array(), array(), array(), array(), array('PHP_AUTH_USER' => 'TheUsername'));
+
+ $token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', array('ROLE_FOO'));
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($token))
+ ;
+
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+ $authenticationManager
+ ->expects($this->never())
+ ->method('authenticate')
+ ;
+
+ $listener = new BasicAuthenticationListener(
+ $context,
+ $authenticationManager,
+ 'TheProviderKey',
+ $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')
+ );
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+
+ $listener->handle($event);
+ }
+
+ /**
+ * @expectedException \InvalidArgumentException
+ * @expectedExceptionMessage $providerKey must not be empty
+ */
+ public function testItRequiresProviderKey()
+ {
+ new BasicAuthenticationListener(
+ $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'),
+ $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'),
+ '',
+ $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')
+ );
+ }
+
+ public function testHandleWithADifferentAuthenticatedToken()
+ {
+ $request = new Request(array(), array(), array(), array(), array(), array(
+ 'PHP_AUTH_USER' => 'TheUsername',
+ 'PHP_AUTH_PW' => 'ThePassword',
+ ));
+
+ $token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context
+ ->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($token))
+ ;
+ $context
+ ->expects($this->never())
+ ->method('setToken')
+ ;
+
+ $response = new Response();
+
+ $authenticationEntryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
+ $authenticationEntryPoint
+ ->expects($this->any())
+ ->method('start')
+ ->with($this->equalTo($request), $this->isInstanceOf('Symfony\Component\Security\Core\Exception\AuthenticationException'))
+ ->will($this->returnValue($response))
+ ;
+
+ $listener = new BasicAuthenticationListener(
+ $context,
+ new AuthenticationProviderManager(array($this->getMock('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface'))),
+ 'TheProviderKey',
+ $authenticationEntryPoint
+ );
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+ $event
+ ->expects($this->once())
+ ->method('setResponse')
+ ->with($this->equalTo($response))
+ ;
+
+ $listener->handle($event);
+ }
+}
diff --git a/Http/Tests/Firewall/ChannelListenerTest.php b/Http/Tests/Firewall/ChannelListenerTest.php
new file mode 100644
index 0000000..2b27e75
--- /dev/null
+++ b/Http/Tests/Firewall/ChannelListenerTest.php
@@ -0,0 +1,181 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\Security\Http\Firewall\ChannelListener;
+use Symfony\Component\HttpKernel\Event\GetResponseEvent;
+use Symfony\Component\HttpFoundation\Response;
+
+class ChannelListenerTest extends \PHPUnit_Framework_TestCase
+{
+ public function testHandleWithNotSecuredRequestAndHttpChannel()
+ {
+ $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
+ $request
+ ->expects($this->any())
+ ->method('isSecure')
+ ->will($this->returnValue(false))
+ ;
+
+ $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
+ $accessMap
+ ->expects($this->any())
+ ->method('getPatterns')
+ ->with($this->equalTo($request))
+ ->will($this->returnValue(array(array(), 'http')))
+ ;
+
+ $entryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
+ $entryPoint
+ ->expects($this->never())
+ ->method('start')
+ ;
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+ $event
+ ->expects($this->never())
+ ->method('setResponse')
+ ;
+
+ $listener = new ChannelListener($accessMap, $entryPoint);
+ $listener->handle($event);
+ }
+
+ public function testHandleWithSecuredRequestAndHttpsChannel()
+ {
+ $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
+ $request
+ ->expects($this->any())
+ ->method('isSecure')
+ ->will($this->returnValue(true))
+ ;
+
+ $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
+ $accessMap
+ ->expects($this->any())
+ ->method('getPatterns')
+ ->with($this->equalTo($request))
+ ->will($this->returnValue(array(array(), 'https')))
+ ;
+
+ $entryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
+ $entryPoint
+ ->expects($this->never())
+ ->method('start')
+ ;
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+ $event
+ ->expects($this->never())
+ ->method('setResponse')
+ ;
+
+ $listener = new ChannelListener($accessMap, $entryPoint);
+ $listener->handle($event);
+ }
+
+ public function testHandleWithNotSecuredRequestAndHttpsChannel()
+ {
+ $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
+ $request
+ ->expects($this->any())
+ ->method('isSecure')
+ ->will($this->returnValue(false))
+ ;
+
+ $response = new Response();
+
+ $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
+ $accessMap
+ ->expects($this->any())
+ ->method('getPatterns')
+ ->with($this->equalTo($request))
+ ->will($this->returnValue(array(array(), 'https')))
+ ;
+
+ $entryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
+ $entryPoint
+ ->expects($this->once())
+ ->method('start')
+ ->with($this->equalTo($request))
+ ->will($this->returnValue($response))
+ ;
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+ $event
+ ->expects($this->once())
+ ->method('setResponse')
+ ->with($this->equalTo($response))
+ ;
+
+ $listener = new ChannelListener($accessMap, $entryPoint);
+ $listener->handle($event);
+ }
+
+ public function testHandleWithSecuredRequestAndHttpChannel()
+ {
+ $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
+ $request
+ ->expects($this->any())
+ ->method('isSecure')
+ ->will($this->returnValue(true))
+ ;
+
+ $response = new Response();
+
+ $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
+ $accessMap
+ ->expects($this->any())
+ ->method('getPatterns')
+ ->with($this->equalTo($request))
+ ->will($this->returnValue(array(array(), 'http')))
+ ;
+
+ $entryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
+ $entryPoint
+ ->expects($this->once())
+ ->method('start')
+ ->with($this->equalTo($request))
+ ->will($this->returnValue($response))
+ ;
+
+ $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ $event
+ ->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request))
+ ;
+ $event
+ ->expects($this->once())
+ ->method('setResponse')
+ ->with($this->equalTo($response))
+ ;
+
+ $listener = new ChannelListener($accessMap, $entryPoint);
+ $listener->handle($event);
+ }
+}
diff --git a/Http/Tests/Firewall/ContextListenerTest.php b/Http/Tests/Firewall/ContextListenerTest.php
new file mode 100644
index 0000000..d6bc5b4
--- /dev/null
+++ b/Http/Tests/Firewall/ContextListenerTest.php
@@ -0,0 +1,248 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpFoundation\Session\Session;
+use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
+use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
+use Symfony\Component\HttpKernel\HttpKernelInterface;
+use Symfony\Component\HttpKernel\KernelEvents;
+use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
+use Symfony\Component\Security\Core\SecurityContext;
+use Symfony\Component\Security\Http\Firewall\ContextListener;
+
+class ContextListenerTest extends \PHPUnit_Framework_TestCase
+{
+ protected function setUp()
+ {
+ $this->securityContext = new SecurityContext(
+ $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'),
+ $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')
+ );
+ }
+
+ protected function tearDown()
+ {
+ unset($this->securityContext);
+ }
+
+ /**
+ * @expectedException \InvalidArgumentException
+ * @expectedExceptionMessage $contextKey must not be empty
+ */
+ public function testItRequiresContextKey()
+ {
+ new ContextListener(
+ $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'),
+ array(),
+ ''
+ );
+ }
+
+ /**
+ * @expectedException \InvalidArgumentException
+ * @expectedExceptionMessage User provider "stdClass" must implement "Symfony\Component\Security\Core\User\UserProviderInterface
+ */
+ public function testUserProvidersNeedToImplementAnInterface()
+ {
+ new ContextListener(
+ $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'),
+ array(new \stdClass()),
+ 'key123'
+ );
+ }
+
+ public function testOnKernelResponseWillAddSession()
+ {
+ $session = $this->runSessionOnKernelResponse(
+ new UsernamePasswordToken('test1', 'pass1', 'phpunit'),
+ null
+ );
+
+ $token = unserialize($session->get('_security_session'));
+ $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $token);
+ $this->assertEquals('test1', $token->getUsername());
+ }
+
+ public function testOnKernelResponseWillReplaceSession()
+ {
+ $session = $this->runSessionOnKernelResponse(
+ new UsernamePasswordToken('test1', 'pass1', 'phpunit'),
+ 'C:10:"serialized"'
+ );
+
+ $token = unserialize($session->get('_security_session'));
+ $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $token);
+ $this->assertEquals('test1', $token->getUsername());
+ }
+
+ public function testOnKernelResponseWillRemoveSession()
+ {
+ $session = $this->runSessionOnKernelResponse(
+ null,
+ 'C:10:"serialized"'
+ );
+
+ $this->assertFalse($session->has('_security_session'));
+ }
+
+ public function testOnKernelResponseWithoutSession()
+ {
+ $this->securityContext->setToken(new UsernamePasswordToken('test1', 'pass1', 'phpunit'));
+ $request = new Request();
+ $session = new Session(new MockArraySessionStorage());
+ $request->setSession($session);
+
+ $event = new FilterResponseEvent(
+ $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'),
+ $request,
+ HttpKernelInterface::MASTER_REQUEST,
+ new Response()
+ );
+
+ $listener = new ContextListener($this->securityContext, array(), 'session');
+ $listener->onKernelResponse($event);
+
+ $this->assertTrue($session->isStarted());
+ }
+
+ public function testOnKernelResponseWithoutSessionNorToken()
+ {
+ $request = new Request();
+ $session = new Session(new MockArraySessionStorage());
+ $request->setSession($session);
+
+ $event = new FilterResponseEvent(
+ $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'),
+ $request,
+ HttpKernelInterface::MASTER_REQUEST,
+ new Response()
+ );
+
+ $listener = new ContextListener($this->securityContext, array(), 'session');
+ $listener->onKernelResponse($event);
+
+ $this->assertFalse($session->isStarted());
+ }
+
+ /**
+ * @dataProvider provideInvalidToken
+ */
+ public function testInvalidTokenInSession($token)
+ {
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
+ $session = $this->getMock('Symfony\Component\HttpFoundation\Session\SessionInterface');
+
+ $event->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request));
+ $request->expects($this->any())
+ ->method('hasPreviousSession')
+ ->will($this->returnValue(true));
+ $request->expects($this->any())
+ ->method('getSession')
+ ->will($this->returnValue($session));
+ $session->expects($this->any())
+ ->method('get')
+ ->with('_security_key123')
+ ->will($this->returnValue($token));
+ $context->expects($this->once())
+ ->method('setToken')
+ ->with(null);
+
+ $listener = new ContextListener($context, array(), 'key123');
+ $listener->handle($event);
+ }
+
+ public function provideInvalidToken()
+ {
+ return array(
+ array(serialize(new \__PHP_Incomplete_Class())),
+ array(serialize(null)),
+ array(null),
+ );
+ }
+
+ public function testHandleAddsKernelResponseListener()
+ {
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
+ $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $listener = new ContextListener($context, array(), 'key123', null, $dispatcher);
+
+ $event->expects($this->any())
+ ->method('isMasterRequest')
+ ->will($this->returnValue(true));
+ $event->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($this->getMock('Symfony\Component\HttpFoundation\Request')));
+
+ $dispatcher->expects($this->once())
+ ->method('addListener')
+ ->with(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
+
+ $listener->handle($event);
+ }
+
+ public function testHandleRemovesTokenIfNoPreviousSessionWasFound()
+ {
+ $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
+ $request->expects($this->any())->method('hasPreviousSession')->will($this->returnValue(false));
+
+ $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $event->expects($this->any())->method('getRequest')->will($this->returnValue($request));
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $context->expects($this->once())->method('setToken')->with(null);
+
+ $listener = new ContextListener($context, array(), 'key123');
+ $listener->handle($event);
+ }
+
+ protected function runSessionOnKernelResponse($newToken, $original = null)
+ {
+ $session = new Session(new MockArraySessionStorage());
+
+ if ($original !== null) {
+ $session->set('_security_session', $original);
+ }
+
+ $this->securityContext->setToken($newToken);
+
+ $request = new Request();
+ $request->setSession($session);
+ $request->cookies->set('MOCKSESSID', true);
+
+ $event = new FilterResponseEvent(
+ $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'),
+ $request,
+ HttpKernelInterface::MASTER_REQUEST,
+ new Response()
+ );
+
+ $listener = new ContextListener($this->securityContext, array(), 'session');
+ $listener->onKernelResponse($event);
+
+ return $session;
+ }
+}
diff --git a/Http/Tests/Firewall/DigestDataTest.php b/Http/Tests/Firewall/DigestDataTest.php
new file mode 100644
index 0000000..a7c8d49
--- /dev/null
+++ b/Http/Tests/Firewall/DigestDataTest.php
@@ -0,0 +1,181 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\Security\Http\Firewall\DigestData;
+
+class DigestDataTest extends \PHPUnit_Framework_TestCase
+{
+ public function testGetResponse()
+ {
+ $digestAuth = new DigestData(
+ 'username="user", realm="Welcome, robot!", '.
+ 'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
+ 'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
+ 'response="b52938fc9e6d7c01be7702ece9031b42"'
+ );
+
+ $this->assertEquals('b52938fc9e6d7c01be7702ece9031b42', $digestAuth->getResponse());
+ }
+
+ public function testGetUsername()
+ {
+ $digestAuth = new DigestData(
+ 'username="user", realm="Welcome, robot!", '.
+ 'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
+ 'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
+ 'response="b52938fc9e6d7c01be7702ece9031b42"'
+ );
+
+ $this->assertEquals('user', $digestAuth->getUsername());
+ }
+
+ public function testGetUsernameWithQuote()
+ {
+ $digestAuth = new DigestData(
+ 'username="\"user\"", realm="Welcome, robot!", '.
+ 'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
+ 'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
+ 'response="b52938fc9e6d7c01be7702ece9031b42"'
+ );
+
+ $this->assertEquals('"user"', $digestAuth->getUsername());
+ }
+
+ public function testGetUsernameWithQuoteAndEscape()
+ {
+ $digestAuth = new DigestData(
+ 'username="\"u\\\\\"ser\"", realm="Welcome, robot!", '.
+ 'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
+ 'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
+ 'response="b52938fc9e6d7c01be7702ece9031b42"'
+ );
+
+ $this->assertEquals('"u\\"ser"', $digestAuth->getUsername());
+ }
+
+ public function testGetUsernameWithSingleQuote()
+ {
+ $digestAuth = new DigestData(
+ 'username="\"u\'ser\"", realm="Welcome, robot!", '.
+ 'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
+ 'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
+ 'response="b52938fc9e6d7c01be7702ece9031b42"'
+ );
+
+ $this->assertEquals('"u\'ser"', $digestAuth->getUsername());
+ }
+
+ public function testGetUsernameWithSingleQuoteAndEscape()
+ {
+ $digestAuth = new DigestData(
+ 'username="\"u\\\'ser\"", realm="Welcome, robot!", '.
+ 'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
+ 'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
+ 'response="b52938fc9e6d7c01be7702ece9031b42"'
+ );
+
+ $this->assertEquals('"u\\\'ser"', $digestAuth->getUsername());
+ }
+
+ public function testGetUsernameWithEscape()
+ {
+ $digestAuth = new DigestData(
+ 'username="\"u\\ser\"", realm="Welcome, robot!", '.
+ 'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
+ 'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
+ 'response="b52938fc9e6d7c01be7702ece9031b42"'
+ );
+
+ $this->assertEquals('"u\\ser"', $digestAuth->getUsername());
+ }
+
+ public function testValidateAndDecode()
+ {
+ $time = microtime(true);
+ $key = 'ThisIsAKey';
+ $nonce = base64_encode($time.':'.md5($time.':'.$key));
+
+ $digestAuth = new DigestData(
+ 'username="user", realm="Welcome, robot!", nonce="'.$nonce.'", '.
+ 'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
+ 'response="b52938fc9e6d7c01be7702ece9031b42"'
+ );
+
+ try {
+ $digestAuth->validateAndDecode($key, 'Welcome, robot!');
+ } catch (\Exception $e) {
+ $this->fail(sprintf('testValidateAndDecode fail with message: %s', $e->getMessage()));
+ }
+ }
+
+ public function testCalculateServerDigest()
+ {
+ $this->calculateServerDigest('user', 'Welcome, robot!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
+ }
+
+ public function testCalculateServerDigestWithQuote()
+ {
+ $this->calculateServerDigest('\"user\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
+ }
+
+ public function testCalculateServerDigestWithQuoteAndEscape()
+ {
+ $this->calculateServerDigest('\"u\\\\\"ser\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
+ }
+
+ public function testCalculateServerDigestEscape()
+ {
+ $this->calculateServerDigest('\"u\\ser\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
+ $this->calculateServerDigest('\"u\\ser\\\\\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
+ }
+
+ public function testIsNonceExpired()
+ {
+ $time = microtime(true) + 10;
+ $key = 'ThisIsAKey';
+ $nonce = base64_encode($time.':'.md5($time.':'.$key));
+
+ $digestAuth = new DigestData(
+ 'username="user", realm="Welcome, robot!", nonce="'.$nonce.'", '.
+ 'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
+ 'response="b52938fc9e6d7c01be7702ece9031b42"'
+ );
+
+ $digestAuth->validateAndDecode($key, 'Welcome, robot!');
+
+ $this->assertFalse($digestAuth->isNonceExpired());
+ }
+
+ protected function setUp()
+ {
+ class_exists('Symfony\Component\Security\Http\Firewall\DigestAuthenticationListener', true);
+ }
+
+ private function calculateServerDigest($username, $realm, $password, $key, $nc, $cnonce, $qop, $method, $uri)
+ {
+ $time = microtime(true);
+ $nonce = base64_encode($time.':'.md5($time.':'.$key));
+
+ $response = md5(
+ md5($username.':'.$realm.':'.$password).':'.$nonce.':'.$nc.':'.$cnonce.':'.$qop.':'.md5($method.':'.$uri)
+ );
+
+ $digest = sprintf('username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc=%s, qop="%s", response="%s"',
+ $username, $realm, $nonce, $uri, $cnonce, $nc, $qop, $response
+ );
+
+ $digestAuth = new DigestData($digest);
+
+ $this->assertEquals($digestAuth->getResponse(), $digestAuth->calculateServerDigest($password, $method));
+ }
+}
diff --git a/Http/Tests/Firewall/LogoutListenerTest.php b/Http/Tests/Firewall/LogoutListenerTest.php
new file mode 100644
index 0000000..041febc
--- /dev/null
+++ b/Http/Tests/Firewall/LogoutListenerTest.php
@@ -0,0 +1,237 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\Security\Http\Firewall\LogoutListener;
+
+class LogoutListenerTest extends \PHPUnit_Framework_TestCase
+{
+ public function testHandleUnmatchedPath()
+ {
+ list($listener, $context, $httpUtils, $options) = $this->getListener();
+
+ list($event, $request) = $this->getGetResponseEvent();
+
+ $event->expects($this->never())
+ ->method('setResponse');
+
+ $httpUtils->expects($this->once())
+ ->method('checkRequestPath')
+ ->with($request, $options['logout_path'])
+ ->will($this->returnValue(false));
+
+ $listener->handle($event);
+ }
+
+ public function testHandleMatchedPathWithSuccessHandlerAndCsrfValidation()
+ {
+ $successHandler = $this->getSuccessHandler();
+ $tokenManager = $this->getTokenManager();
+
+ list($listener, $context, $httpUtils, $options) = $this->getListener($successHandler, $tokenManager);
+
+ list($event, $request) = $this->getGetResponseEvent();
+
+ $request->query->set('_csrf_token', 'token');
+
+ $httpUtils->expects($this->once())
+ ->method('checkRequestPath')
+ ->with($request, $options['logout_path'])
+ ->will($this->returnValue(true));
+
+ $tokenManager->expects($this->once())
+ ->method('isTokenValid')
+ ->will($this->returnValue(true));
+
+ $successHandler->expects($this->once())
+ ->method('onLogoutSuccess')
+ ->with($request)
+ ->will($this->returnValue($response = new Response()));
+
+ $context->expects($this->once())
+ ->method('getToken')
+ ->will($this->returnValue($token = $this->getToken()));
+
+ $handler = $this->getHandler();
+ $handler->expects($this->once())
+ ->method('logout')
+ ->with($request, $response, $token);
+
+ $context->expects($this->once())
+ ->method('setToken')
+ ->with(null);
+
+ $event->expects($this->once())
+ ->method('setResponse')
+ ->with($response);
+
+ $listener->addHandler($handler);
+
+ $listener->handle($event);
+ }
+
+ public function testHandleMatchedPathWithoutSuccessHandlerAndCsrfValidation()
+ {
+ $successHandler = $this->getSuccessHandler();
+
+ list($listener, $context, $httpUtils, $options) = $this->getListener($successHandler);
+
+ list($event, $request) = $this->getGetResponseEvent();
+
+ $httpUtils->expects($this->once())
+ ->method('checkRequestPath')
+ ->with($request, $options['logout_path'])
+ ->will($this->returnValue(true));
+
+ $successHandler->expects($this->once())
+ ->method('onLogoutSuccess')
+ ->with($request)
+ ->will($this->returnValue($response = new Response()));
+
+ $context->expects($this->once())
+ ->method('getToken')
+ ->will($this->returnValue($token = $this->getToken()));
+
+ $handler = $this->getHandler();
+ $handler->expects($this->once())
+ ->method('logout')
+ ->with($request, $response, $token);
+
+ $context->expects($this->once())
+ ->method('setToken')
+ ->with(null);
+
+ $event->expects($this->once())
+ ->method('setResponse')
+ ->with($response);
+
+ $listener->addHandler($handler);
+
+ $listener->handle($event);
+ }
+
+ /**
+ * @expectedException \RuntimeException
+ */
+ public function testSuccessHandlerReturnsNonResponse()
+ {
+ $successHandler = $this->getSuccessHandler();
+
+ list($listener, $context, $httpUtils, $options) = $this->getListener($successHandler);
+
+ list($event, $request) = $this->getGetResponseEvent();
+
+ $httpUtils->expects($this->once())
+ ->method('checkRequestPath')
+ ->with($request, $options['logout_path'])
+ ->will($this->returnValue(true));
+
+ $successHandler->expects($this->once())
+ ->method('onLogoutSuccess')
+ ->with($request)
+ ->will($this->returnValue(null));
+
+ $listener->handle($event);
+ }
+
+ /**
+ * @expectedException \Symfony\Component\Security\Core\Exception\LogoutException
+ */
+ public function testCsrfValidationFails()
+ {
+ $tokenManager = $this->getTokenManager();
+
+ list($listener, $context, $httpUtils, $options) = $this->getListener(null, $tokenManager);
+
+ list($event, $request) = $this->getGetResponseEvent();
+
+ $request->query->set('_csrf_token', 'token');
+
+ $httpUtils->expects($this->once())
+ ->method('checkRequestPath')
+ ->with($request, $options['logout_path'])
+ ->will($this->returnValue(true));
+
+ $tokenManager->expects($this->once())
+ ->method('isTokenValid')
+ ->will($this->returnValue(false));
+
+ $listener->handle($event);
+ }
+
+ private function getTokenManager()
+ {
+ return $this->getMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
+ }
+
+ private function getContext()
+ {
+ return $this->getMockBuilder('Symfony\Component\Security\Core\SecurityContext')
+ ->disableOriginalConstructor()
+ ->getMock();
+ }
+
+ private function getGetResponseEvent()
+ {
+ $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $event->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request = new Request()));
+
+ return array($event, $request);
+ }
+
+ private function getHandler()
+ {
+ return $this->getMock('Symfony\Component\Security\Http\Logout\LogoutHandlerInterface');
+ }
+
+ private function getHttpUtils()
+ {
+ return $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')
+ ->disableOriginalConstructor()
+ ->getMock();
+ }
+
+ private function getListener($successHandler = null, $tokenManager = null)
+ {
+ $listener = new LogoutListener(
+ $context = $this->getContext(),
+ $httpUtils = $this->getHttpUtils(),
+ $successHandler ?: $this->getSuccessHandler(),
+ $options = array(
+ 'csrf_parameter' => '_csrf_token',
+ 'intention' => 'logout',
+ 'logout_path' => '/logout',
+ 'target_url' => '/',
+ ),
+ $tokenManager
+ );
+
+ return array($listener, $context, $httpUtils, $options);
+ }
+
+ private function getSuccessHandler()
+ {
+ return $this->getMock('Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface');
+ }
+
+ private function getToken()
+ {
+ return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+ }
+}
diff --git a/Http/Tests/Firewall/RememberMeListenerTest.php b/Http/Tests/Firewall/RememberMeListenerTest.php
new file mode 100644
index 0000000..99d7fcc
--- /dev/null
+++ b/Http/Tests/Firewall/RememberMeListenerTest.php
@@ -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\Http\Tests\Firewall;
+
+use Symfony\Component\Security\Core\Exception\AuthenticationException;
+use Symfony\Component\Security\Http\Firewall\RememberMeListener;
+use Symfony\Component\HttpFoundation\Request;
+
+class RememberMeListenerTest extends \PHPUnit_Framework_TestCase
+{
+ public function testOnCoreSecurityDoesNotTryToPopulateNonEmptySecurityContext()
+ {
+ list($listener, $context, $service, ,) = $this->getListener();
+
+ $context
+ ->expects($this->once())
+ ->method('getToken')
+ ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')))
+ ;
+
+ $context
+ ->expects($this->never())
+ ->method('setToken')
+ ;
+
+ $this->assertNull($listener->handle($this->getGetResponseEvent()));
+ }
+
+ public function testOnCoreSecurityDoesNothingWhenNoCookieIsSet()
+ {
+ list($listener, $context, $service, ,) = $this->getListener();
+
+ $context
+ ->expects($this->once())
+ ->method('getToken')
+ ->will($this->returnValue(null))
+ ;
+
+ $service
+ ->expects($this->once())
+ ->method('autoLogin')
+ ->will($this->returnValue(null))
+ ;
+
+ $event = $this->getGetResponseEvent();
+ $event
+ ->expects($this->once())
+ ->method('getRequest')
+ ->will($this->returnValue(new Request()))
+ ;
+
+ $this->assertNull($listener->handle($event));
+ }
+
+ public function testOnCoreSecurityIgnoresAuthenticationExceptionThrownByAuthenticationManagerImplementation()
+ {
+ list($listener, $context, $service, $manager,) = $this->getListener();
+
+ $context
+ ->expects($this->once())
+ ->method('getToken')
+ ->will($this->returnValue(null))
+ ;
+
+ $service
+ ->expects($this->once())
+ ->method('autoLogin')
+ ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')))
+ ;
+
+ $service
+ ->expects($this->once())
+ ->method('loginFail')
+ ;
+
+ $exception = new AuthenticationException('Authentication failed.');
+ $manager
+ ->expects($this->once())
+ ->method('authenticate')
+ ->will($this->throwException($exception))
+ ;
+
+ $event = $this->getGetResponseEvent();
+ $event
+ ->expects($this->once())
+ ->method('getRequest')
+ ->will($this->returnValue(new Request()))
+ ;
+
+ $listener->handle($event);
+ }
+
+ public function testOnCoreSecurity()
+ {
+ list($listener, $context, $service, $manager,) = $this->getListener();
+
+ $context
+ ->expects($this->once())
+ ->method('getToken')
+ ->will($this->returnValue(null))
+ ;
+
+ $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+ $service
+ ->expects($this->once())
+ ->method('autoLogin')
+ ->will($this->returnValue($token))
+ ;
+
+ $context
+ ->expects($this->once())
+ ->method('setToken')
+ ->with($this->equalTo($token))
+ ;
+
+ $manager
+ ->expects($this->once())
+ ->method('authenticate')
+ ->will($this->returnValue($token))
+ ;
+
+ $event = $this->getGetResponseEvent();
+ $event
+ ->expects($this->once())
+ ->method('getRequest')
+ ->will($this->returnValue(new Request()))
+ ;
+
+ $listener->handle($event);
+ }
+
+ protected function getGetResponseEvent()
+ {
+ return $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
+ }
+
+ protected function getFilterResponseEvent()
+ {
+ return $this->getMock('Symfony\Component\HttpKernel\Event\FilterResponseEvent', array(), array(), '', false);
+ }
+
+ protected function getListener()
+ {
+ $listener = new RememberMeListener(
+ $context = $this->getContext(),
+ $service = $this->getService(),
+ $manager = $this->getManager(),
+ $logger = $this->getLogger()
+ );
+
+ return array($listener, $context, $service, $manager, $logger);
+ }
+
+ protected function getLogger()
+ {
+ return $this->getMock('Psr\Log\LoggerInterface');
+ }
+
+ protected function getManager()
+ {
+ return $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+ }
+
+ protected function getService()
+ {
+ return $this->getMock('Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface');
+ }
+
+ protected function getContext()
+ {
+ return $this->getMockBuilder('Symfony\Component\Security\Core\SecurityContext')
+ ->disableOriginalConstructor()
+ ->getMock();
+ }
+}
diff --git a/Http/Tests/Firewall/SwitchUserListenerTest.php b/Http/Tests/Firewall/SwitchUserListenerTest.php
new file mode 100644
index 0000000..9e149a2
--- /dev/null
+++ b/Http/Tests/Firewall/SwitchUserListenerTest.php
@@ -0,0 +1,202 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\Security\Http\Firewall\SwitchUserListener;
+
+class SwitchUserListenerTest extends \PHPUnit_Framework_TestCase
+{
+ private $securityContext;
+
+ private $userProvider;
+
+ private $userChecker;
+
+ private $accessDecisionManager;
+
+ private $request;
+
+ private $event;
+
+ protected function setUp()
+ {
+ $this->securityContext = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+ $this->userProvider = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface');
+ $this->userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface');
+ $this->accessDecisionManager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');
+ $this->request = $this->getMock('Symfony\Component\HttpFoundation\Request');
+ $this->request->query = $this->getMock('Symfony\Component\HttpFoundation\ParameterBag');
+ $this->request->server = $this->getMock('Symfony\Component\HttpFoundation\ServerBag');
+ $this->event = $this->getEvent($this->request);
+ }
+
+ /**
+ * @expectedException \InvalidArgumentException
+ * @expectedExceptionMessage $providerKey must not be empty
+ */
+ public function testProviderKeyIsRequired()
+ {
+ new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, '', $this->accessDecisionManager);
+ }
+
+ public function testEventIsIgnoredIfUsernameIsNotPassedWithTheRequest()
+ {
+ $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue(null));
+
+ $this->event->expects($this->never())->method('setResponse');
+ $this->securityContext->expects($this->never())->method('setToken');
+
+ $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
+ $listener->handle($this->event);
+ }
+
+ /**
+ * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
+ */
+ public function testExitUserThrowsAuthenticationExceptionIfOriginalTokenCannotBeFound()
+ {
+ $token = $this->getToken(array($this->getMock('Symfony\Component\Security\Core\Role\RoleInterface')));
+
+ $this->securityContext->expects($this->any())->method('getToken')->will($this->returnValue($token));
+ $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('_exit'));
+
+ $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
+ $listener->handle($this->event);
+ }
+
+ public function testExitUserUpdatesToken()
+ {
+ $originalToken = $this->getToken();
+ $role = $this->getMockBuilder('Symfony\Component\Security\Core\Role\SwitchUserRole')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $role->expects($this->any())->method('getSource')->will($this->returnValue($originalToken));
+
+ $this->securityContext->expects($this->any())
+ ->method('getToken')
+ ->will($this->returnValue($this->getToken(array($role))));
+
+ $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('_exit'));
+ $this->request->expects($this->any())->method('getUri')->will($this->returnValue('/'));
+ $this->request->query->expects($this->once())->method('remove', '_switch_user');
+ $this->request->query->expects($this->any())->method('all')->will($this->returnValue(array()));
+ $this->request->server->expects($this->once())->method('set')->with('QUERY_STRING', '');
+
+ $this->securityContext->expects($this->once())
+ ->method('setToken')->with($originalToken);
+ $this->event->expects($this->once())
+ ->method('setResponse')->with($this->isInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse'));
+
+ $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
+ $listener->handle($this->event);
+ }
+
+ /**
+ * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
+ */
+ public function testSwitchUserIsDisallowed()
+ {
+ $token = $this->getToken(array($this->getMock('Symfony\Component\Security\Core\Role\RoleInterface')));
+
+ $this->securityContext->expects($this->any())->method('getToken')->will($this->returnValue($token));
+ $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('kuba'));
+
+ $this->accessDecisionManager->expects($this->once())
+ ->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
+ ->will($this->returnValue(false));
+
+ $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
+ $listener->handle($this->event);
+ }
+
+ public function testSwitchUser()
+ {
+ $token = $this->getToken(array($this->getMock('Symfony\Component\Security\Core\Role\RoleInterface')));
+ $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
+ $user->expects($this->any())->method('getRoles')->will($this->returnValue(array()));
+
+ $this->securityContext->expects($this->any())->method('getToken')->will($this->returnValue($token));
+ $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('kuba'));
+ $this->request->query->expects($this->once())->method('remove', '_switch_user');
+ $this->request->query->expects($this->any())->method('all')->will($this->returnValue(array()));
+
+ $this->request->expects($this->any())->method('getUri')->will($this->returnValue('/'));
+ $this->request->server->expects($this->once())->method('set')->with('QUERY_STRING', '');
+
+ $this->accessDecisionManager->expects($this->once())
+ ->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
+ ->will($this->returnValue(true));
+
+ $this->userProvider->expects($this->once())
+ ->method('loadUserByUsername')->with('kuba')
+ ->will($this->returnValue($user));
+ $this->userChecker->expects($this->once())
+ ->method('checkPostAuth')->with($user);
+ $this->securityContext->expects($this->once())
+ ->method('setToken')->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken'));
+
+ $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
+ $listener->handle($this->event);
+ }
+
+ public function testSwitchUserKeepsOtherQueryStringParameters()
+ {
+ $token = $this->getToken(array($this->getMock('Symfony\Component\Security\Core\Role\RoleInterface')));
+ $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
+ $user->expects($this->any())->method('getRoles')->will($this->returnValue(array()));
+
+ $this->securityContext->expects($this->any())->method('getToken')->will($this->returnValue($token));
+ $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('kuba'));
+ $this->request->query->expects($this->once())->method('remove', '_switch_user');
+ $this->request->query->expects($this->any())->method('all')->will($this->returnValue(array('page' => 3,'section' => 2)));
+ $this->request->expects($this->any())->method('getUri')->will($this->returnValue('/'));
+ $this->request->server->expects($this->once())->method('set')->with('QUERY_STRING', 'page=3&section=2');
+
+ $this->accessDecisionManager->expects($this->once())
+ ->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
+ ->will($this->returnValue(true));
+
+ $this->userProvider->expects($this->once())
+ ->method('loadUserByUsername')->with('kuba')
+ ->will($this->returnValue($user));
+ $this->userChecker->expects($this->once())
+ ->method('checkPostAuth')->with($user);
+ $this->securityContext->expects($this->once())
+ ->method('setToken')->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken'));
+
+ $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
+ $listener->handle($this->event);
+ }
+
+ private function getEvent($request)
+ {
+ $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $event->expects($this->any())
+ ->method('getRequest')
+ ->will($this->returnValue($request));
+
+ return $event;
+ }
+
+ private function getToken(array $roles = array())
+ {
+ $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
+ $token->expects($this->any())
+ ->method('getRoles')
+ ->will($this->returnValue($roles));
+
+ return $token;
+ }
+}
diff --git a/Http/Tests/Firewall/X509AuthenticationListenerTest.php b/Http/Tests/Firewall/X509AuthenticationListenerTest.php
new file mode 100644
index 0000000..7f2da3e
--- /dev/null
+++ b/Http/Tests/Firewall/X509AuthenticationListenerTest.php
@@ -0,0 +1,123 @@
+<?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\Http\Tests\Firewall;
+
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\Security\Http\Firewall\X509AuthenticationListener;
+
+class X509AuthenticationListenerTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * @dataProvider dataProviderGetPreAuthenticatedData
+ */
+ public function testGetPreAuthenticatedData($user, $credentials)
+ {
+ $serverVars = array();
+ if ('' !== $user) {
+ $serverVars['SSL_CLIENT_S_DN_Email'] = $user;
+ }
+ if ('' !== $credentials) {
+ $serverVars['SSL_CLIENT_S_DN'] = $credentials;
+ }
+
+ $request = new Request(array(), array(), array(), array(), array(), $serverVars);
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+
+ $listener = new X509AuthenticationListener($context, $authenticationManager, 'TheProviderKey');
+
+ $method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
+ $method->setAccessible(true);
+
+ $result = $method->invokeArgs($listener, array($request));
+ $this->assertSame($result, array($user, $credentials));
+ }
+
+ public static function dataProviderGetPreAuthenticatedData()
+ {
+ return array(
+ 'validValues' => array('TheUser', 'TheCredentials'),
+ 'noCredentials' => array('TheUser', ''),
+ );
+ }
+
+ /**
+ * @dataProvider dataProviderGetPreAuthenticatedDataNoUser
+ */
+ public function testGetPreAuthenticatedDataNoUser($emailAddress)
+ {
+ $credentials = 'CN=Sample certificate DN/emailAddress='.$emailAddress;
+ $request = new Request(array(), array(), array(), array(), array(), array('SSL_CLIENT_S_DN' => $credentials));
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+
+ $listener = new X509AuthenticationListener($context, $authenticationManager, 'TheProviderKey');
+
+ $method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
+ $method->setAccessible(true);
+
+ $result = $method->invokeArgs($listener, array($request));
+ $this->assertSame($result, array($emailAddress, $credentials));
+ }
+
+ public static function dataProviderGetPreAuthenticatedDataNoUser()
+ {
+ return array(
+ 'basicEmailAddress' => array('cert@example.com'),
+ 'emailAddressWithPlusSign' => array('cert+something@example.com'),
+ );
+ }
+
+ /**
+ * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
+ */
+ public function testGetPreAuthenticatedDataNoData()
+ {
+ $request = new Request(array(), array(), array(), array(), array(), array());
+
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+
+ $listener = new X509AuthenticationListener($context, $authenticationManager, 'TheProviderKey');
+
+ $method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
+ $method->setAccessible(true);
+
+ $result = $method->invokeArgs($listener, array($request));
+ }
+
+ public function testGetPreAuthenticatedDataWithDifferentKeys()
+ {
+ $userCredentials = array('TheUser', 'TheCredentials');
+
+ $request = new Request(array(), array(), array(), array(), array(), array(
+ 'TheUserKey' => 'TheUser',
+ 'TheCredentialsKey' => 'TheCredentials',
+ ));
+ $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
+
+ $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
+
+ $listener = new X509AuthenticationListener($context, $authenticationManager, 'TheProviderKey', 'TheUserKey', 'TheCredentialsKey');
+
+ $method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
+ $method->setAccessible(true);
+
+ $result = $method->invokeArgs($listener, array($request));
+ $this->assertSame($result, $userCredentials);
+ }
+}