Upgrade 1-11.38

This commit is contained in:
xesmyd
2026-03-30 14:10:30 +02:00
parent f2a7e6d1fc
commit ac648ef29d
24665 changed files with 69682 additions and 2205004 deletions
+6 -6
View File
@@ -23,10 +23,10 @@ class AccessMapTest extends TestCase
$requestMatcher2 = $this->getRequestMatcher($request, true);
$map = new AccessMap();
$map->add($requestMatcher1, array('ROLE_ADMIN'), 'http');
$map->add($requestMatcher2, array('ROLE_USER'), 'https');
$map->add($requestMatcher1, ['ROLE_ADMIN'], 'http');
$map->add($requestMatcher2, ['ROLE_USER'], 'https');
$this->assertSame(array(array('ROLE_USER'), 'https'), $map->getPatterns($request));
$this->assertSame([['ROLE_USER'], 'https'], $map->getPatterns($request));
}
public function testReturnsEmptyPatternIfNoneMatched()
@@ -35,9 +35,9 @@ class AccessMapTest extends TestCase
$requestMatcher = $this->getRequestMatcher($request, false);
$map = new AccessMap();
$map->add($requestMatcher, array('ROLE_USER'), 'https');
$map->add($requestMatcher, ['ROLE_USER'], 'https');
$this->assertSame(array(null, null), $map->getPatterns($request));
$this->assertSame([null, null], $map->getPatterns($request));
}
private function getRequestMatcher($request, $matches)
@@ -45,7 +45,7 @@ class AccessMapTest extends TestCase
$requestMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->once())
->method('matches')->with($request)
->will($this->returnValue($matches));
->willReturn($matches);
return $requestMatcher;
}
@@ -12,10 +12,11 @@
namespace Symfony\Component\Security\Http\Tests\Authentication;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
class DefaultAuthenticationFailureHandlerTest extends TestCase
{
@@ -34,25 +35,25 @@ class DefaultAuthenticationFailureHandlerTest extends TestCase
$this->session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$this->request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$this->request->expects($this->any())->method('getSession')->will($this->returnValue($this->session));
$this->exception = $this->getMockBuilder('Symfony\Component\Security\Core\Exception\AuthenticationException')->setMethods(array('getMessage'))->getMock();
$this->request->expects($this->any())->method('getSession')->willReturn($this->session);
$this->exception = $this->getMockBuilder('Symfony\Component\Security\Core\Exception\AuthenticationException')->setMethods(['getMessage'])->getMock();
}
public function testForward()
{
$options = array('failure_forward' => true);
$options = ['failure_forward' => true];
$subRequest = $this->getRequest();
$subRequest->attributes->expects($this->once())
->method('set')->with(Security::AUTHENTICATION_ERROR, $this->exception);
$this->httpUtils->expects($this->once())
->method('createRequest')->with($this->request, '/login')
->will($this->returnValue($subRequest));
->willReturn($subRequest);
$response = new Response();
$this->httpKernel->expects($this->once())
->method('handle')->with($subRequest, HttpKernelInterface::SUB_REQUEST)
->will($this->returnValue($response));
->willReturn($response);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
$result = $handler->onAuthenticationFailure($this->request, $this->exception);
@@ -62,12 +63,12 @@ class DefaultAuthenticationFailureHandlerTest extends TestCase
public function testRedirect()
{
$response = new Response();
$response = new RedirectResponse('/login');
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/login')
->will($this->returnValue($response));
->willReturn($response);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, [], $this->logger);
$result = $handler->onAuthenticationFailure($this->request, $this->exception);
$this->assertSame($response, $result);
@@ -78,13 +79,13 @@ class DefaultAuthenticationFailureHandlerTest extends TestCase
$this->session->expects($this->once())
->method('set')->with(Security::AUTHENTICATION_ERROR, $this->exception);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, [], $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testExceptionIsPassedInRequestOnForward()
{
$options = array('failure_forward' => true);
$options = ['failure_forward' => true];
$subRequest = $this->getRequest();
$subRequest->attributes->expects($this->once())
@@ -92,7 +93,7 @@ class DefaultAuthenticationFailureHandlerTest extends TestCase
$this->httpUtils->expects($this->once())
->method('createRequest')->with($this->request, '/login')
->will($this->returnValue($subRequest));
->willReturn($subRequest);
$this->session->expects($this->never())->method('set');
@@ -105,24 +106,24 @@ class DefaultAuthenticationFailureHandlerTest extends TestCase
$this->logger
->expects($this->once())
->method('debug')
->with('Authentication failure, redirect triggered.', array('failure_path' => '/login'));
->with('Authentication failure, redirect triggered.', ['failure_path' => '/login']);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, [], $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testForwardIsLogged()
{
$options = array('failure_forward' => true);
$options = ['failure_forward' => true];
$this->httpUtils->expects($this->once())
->method('createRequest')->with($this->request, '/login')
->will($this->returnValue($this->getRequest()));
->willReturn($this->getRequest());
$this->logger
->expects($this->once())
->method('debug')
->with('Authentication failure, forward triggered.', array('failure_path' => '/login'));
->with('Authentication failure, forward triggered.', ['failure_path' => '/login']);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
@@ -130,7 +131,7 @@ class DefaultAuthenticationFailureHandlerTest extends TestCase
public function testFailurePathCanBeOverwritten()
{
$options = array('failure_path' => '/auth/login');
$options = ['failure_path' => '/auth/login'];
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/auth/login');
@@ -143,12 +144,12 @@ class DefaultAuthenticationFailureHandlerTest extends TestCase
{
$this->request->expects($this->once())
->method('get')->with('_failure_path')
->will($this->returnValue('/auth/login'));
->willReturn('/auth/login');
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/auth/login');
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, [], $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
@@ -156,22 +157,22 @@ class DefaultAuthenticationFailureHandlerTest extends TestCase
{
$this->request->expects($this->once())
->method('get')->with('_failure_path')
->will($this->returnValue(array('value' => '/auth/login')));
->willReturn(['value' => '/auth/login']);
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/auth/login');
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array('failure_path_parameter' => '_failure_path[value]'), $this->logger);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, ['failure_path_parameter' => '_failure_path[value]'], $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testFailurePathParameterCanBeOverwritten()
{
$options = array('failure_path_parameter' => '_my_failure_path');
$options = ['failure_path_parameter' => '_my_failure_path'];
$this->request->expects($this->once())
->method('get')->with('_my_failure_path')
->will($this->returnValue('/auth/login'));
->willReturn('/auth/login');
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/auth/login');
@@ -24,7 +24,7 @@ class DefaultAuthenticationSuccessHandlerTest extends TestCase
public function testRequestRedirections(Request $request, $options, $redirectedUrl)
{
$urlGenerator = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock();
$urlGenerator->expects($this->any())->method('generate')->will($this->returnValue('http://localhost/login'));
$urlGenerator->expects($this->any())->method('generate')->willReturn('http://localhost/login');
$httpUtils = new HttpUtils($urlGenerator);
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$handler = new DefaultAuthenticationSuccessHandler($httpUtils, $options);
@@ -37,67 +37,77 @@ class DefaultAuthenticationSuccessHandlerTest extends TestCase
public function getRequestRedirections()
{
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$session->expects($this->once())->method('get')->with('_security.admin.target_path')->will($this->returnValue('/admin/dashboard'));
$session->expects($this->once())->method('get')->with('_security.admin.target_path')->willReturn('/admin/dashboard');
$session->expects($this->once())->method('remove')->with('_security.admin.target_path');
$requestWithSession = Request::create('/');
$requestWithSession->setSession($session);
return array(
'default' => array(
return [
'default' => [
Request::create('/'),
array(),
[],
'/',
),
'forced target path' => array(
],
'forced target path' => [
Request::create('/'),
array('always_use_default_target_path' => true, 'default_target_path' => '/dashboard'),
['always_use_default_target_path' => true, 'default_target_path' => '/dashboard'],
'/dashboard',
),
'target path as query string' => array(
],
'target path as query string' => [
Request::create('/?_target_path=/dashboard'),
array(),
[],
'/dashboard',
),
'target path name as query string is customized' => array(
],
'target path name as query string is customized' => [
Request::create('/?_my_target_path=/dashboard'),
array('target_path_parameter' => '_my_target_path'),
['target_path_parameter' => '_my_target_path'],
'/dashboard',
),
'target path name as query string is customized and nested' => array(
],
'target path name as query string is customized and nested' => [
Request::create('/?_target_path[value]=/dashboard'),
array('target_path_parameter' => '_target_path[value]'),
['target_path_parameter' => '_target_path[value]'],
'/dashboard',
),
'target path in session' => array(
],
'target path in session' => [
$requestWithSession,
array(),
[],
'/admin/dashboard',
),
'target path as referer' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/dashboard')),
array('use_referer' => true),
],
'target path as referer' => [
Request::create('/', 'GET', [], [], [], ['HTTP_REFERER' => 'http://localhost/dashboard']),
['use_referer' => true],
'/dashboard',
),
'target path as referer is ignored if not configured' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/dashboard')),
array(),
],
'target path as referer is ignored if not configured' => [
Request::create('/', 'GET', [], [], [], ['HTTP_REFERER' => 'http://localhost/dashboard']),
[],
'/',
),
'target path should be different than login URL' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/login')),
array('use_referer' => true, 'login_path' => '/login'),
],
'target path as referer when referer not set' => [
Request::create('/'),
['use_referer' => true],
'/',
),
'target path should be different than login URL (query string does not matter)' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/login?t=1&p=2')),
array('use_referer' => true, 'login_path' => '/login'),
],
'target path as referer when referer is ?' => [
Request::create('/', 'GET', [], [], [], ['HTTP_REFERER' => '?']),
['use_referer' => true],
'/',
),
'target path should be different than login URL (login_path as a route)' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/login?t=1&p=2')),
array('use_referer' => true, 'login_path' => 'login_route'),
],
'target path should be different than login URL' => [
Request::create('/', 'GET', [], [], [], ['HTTP_REFERER' => 'http://localhost/login']),
['use_referer' => true, 'login_path' => '/login'],
'/',
),
);
],
'target path should be different than login URL (query string does not matter)' => [
Request::create('/', 'GET', [], [], [], ['HTTP_REFERER' => 'http://localhost/login?t=1&p=2']),
['use_referer' => true, 'login_path' => '/login'],
'/',
],
'target path should be different than login URL (login_path as a route)' => [
Request::create('/', 'GET', [], [], [], ['HTTP_REFERER' => 'http://localhost/login?t=1&p=2']),
['use_referer' => true, 'login_path' => 'login_route'],
'/',
],
];
}
}
@@ -53,7 +53,7 @@ class SimpleAuthenticationHandlerTest extends TestCase
$this->successHandler->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->will($this->returnValue($this->response));
->willReturn($this->response);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationSuccess($this->request, $this->token);
@@ -70,7 +70,7 @@ class SimpleAuthenticationHandlerTest extends TestCase
$authenticator->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->will($this->returnValue($this->response));
->willReturn($this->response);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationSuccess($this->request, $this->token);
@@ -78,12 +78,10 @@ class SimpleAuthenticationHandlerTest extends TestCase
$this->assertSame($this->response, $result);
}
/**
* @expectedException \UnexpectedValueException
* @expectedExceptionMessage onAuthenticationSuccess method must return null to use the default success handler, or a Response object
*/
public function testOnAuthenticationSuccessThrowsAnExceptionIfNonResponseIsReturned()
{
$this->expectException('UnexpectedValueException');
$this->expectExceptionMessage('onAuthenticationSuccess()" method must return null to use the default success handler, or a Response object');
$this->successHandler->expects($this->never())
->method('onAuthenticationSuccess');
@@ -91,7 +89,7 @@ class SimpleAuthenticationHandlerTest extends TestCase
$authenticator->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->will($this->returnValue(new \stdClass()));
->willReturn(new \stdClass());
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$handler->onAuthenticationSuccess($this->request, $this->token);
@@ -102,13 +100,13 @@ class SimpleAuthenticationHandlerTest extends TestCase
$this->successHandler->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->will($this->returnValue($this->response));
->willReturn($this->response);
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestSuccessHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->will($this->returnValue(null));
->willReturn(null);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationSuccess($this->request, $this->token);
@@ -123,7 +121,7 @@ class SimpleAuthenticationHandlerTest extends TestCase
$this->failureHandler->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->will($this->returnValue($this->response));
->willReturn($this->response);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationFailure($this->request, $this->authenticationException);
@@ -140,7 +138,7 @@ class SimpleAuthenticationHandlerTest extends TestCase
$authenticator->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->will($this->returnValue($this->response));
->willReturn($this->response);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationFailure($this->request, $this->authenticationException);
@@ -148,12 +146,10 @@ class SimpleAuthenticationHandlerTest extends TestCase
$this->assertSame($this->response, $result);
}
/**
* @expectedException \UnexpectedValueException
* @expectedExceptionMessage onAuthenticationFailure method must return null to use the default failure handler, or a Response object
*/
public function testOnAuthenticationFailureThrowsAnExceptionIfNonResponseIsReturned()
{
$this->expectException('UnexpectedValueException');
$this->expectExceptionMessage('onAuthenticationFailure()" method must return null to use the default failure handler, or a Response object');
$this->failureHandler->expects($this->never())
->method('onAuthenticationFailure');
@@ -161,7 +157,7 @@ class SimpleAuthenticationHandlerTest extends TestCase
$authenticator->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->will($this->returnValue(new \stdClass()));
->willReturn(new \stdClass());
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$handler->onAuthenticationFailure($this->request, $this->authenticationException);
@@ -172,13 +168,13 @@ class SimpleAuthenticationHandlerTest extends TestCase
$this->failureHandler->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->will($this->returnValue($this->response));
->willReturn($this->response);
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestFailureHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->will($this->returnValue(null));
->willReturn(null);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationFailure($this->request, $this->authenticationException);
@@ -12,8 +12,8 @@
namespace Symfony\Component\Security\Http\Tests\EntryPoint;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\EntryPoint\BasicAuthenticationEntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\BasicAuthenticationEntryPoint;
class BasicAuthenticationEntryPointTest extends TestCase
{
@@ -12,10 +12,13 @@
namespace Symfony\Component\Security\Http\Tests\EntryPoint;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\EntryPoint\DigestAuthenticationEntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\NonceExpiredException;
use Symfony\Component\Security\Http\EntryPoint\DigestAuthenticationEntryPoint;
/**
* @group legacy
*/
class DigestAuthenticationEntryPointTest extends TestCase
{
public function testStart()
@@ -28,7 +31,7 @@ class DigestAuthenticationEntryPointTest extends TestCase
$response = $entryPoint->start($request, $authenticationException);
$this->assertEquals(401, $response->getStatusCode());
$this->assertRegExp('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}"$/', $response->headers->get('WWW-Authenticate'));
$this->assertMatchesRegularExpression('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}"$/', $response->headers->get('WWW-Authenticate'));
}
public function testStartWithNoException()
@@ -39,7 +42,7 @@ class DigestAuthenticationEntryPointTest extends TestCase
$response = $entryPoint->start($request);
$this->assertEquals(401, $response->getStatusCode());
$this->assertRegExp('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}"$/', $response->headers->get('WWW-Authenticate'));
$this->assertMatchesRegularExpression('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}"$/', $response->headers->get('WWW-Authenticate'));
}
public function testStartWithNonceExpiredException()
@@ -52,6 +55,6 @@ class DigestAuthenticationEntryPointTest extends TestCase
$response = $entryPoint->start($request, $nonceExpiredException);
$this->assertEquals(401, $response->getStatusCode());
$this->assertRegExp('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}", stale="true"$/', $response->headers->get('WWW-Authenticate'));
$this->assertMatchesRegularExpression('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}", stale="true"$/', $response->headers->get('WWW-Authenticate'));
}
}
@@ -12,16 +12,17 @@
namespace Symfony\Component\Security\Http\Tests\EntryPoint;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\EntryPoint\FormAuthenticationEntryPoint;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Http\EntryPoint\FormAuthenticationEntryPoint;
class FormAuthenticationEntryPointTest extends TestCase
{
public function testStart()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$response = new Response();
$response = new RedirectResponse('/the/login/path');
$httpKernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
@@ -29,7 +30,7 @@ class FormAuthenticationEntryPointTest extends TestCase
->expects($this->once())
->method('createRedirectResponse')
->with($this->equalTo($request), $this->equalTo('/the/login/path'))
->will($this->returnValue($response))
->willReturn($response)
;
$entryPoint = new FormAuthenticationEntryPoint($httpKernel, $httpUtils, '/the/login/path', false);
@@ -48,7 +49,7 @@ class FormAuthenticationEntryPointTest extends TestCase
->expects($this->once())
->method('createRequest')
->with($this->equalTo($request), $this->equalTo('/the/login/path'))
->will($this->returnValue($subRequest))
->willReturn($subRequest)
;
$httpKernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
@@ -56,7 +57,7 @@ class FormAuthenticationEntryPointTest extends TestCase
->expects($this->once())
->method('handle')
->with($this->equalTo($subRequest), $this->equalTo(HttpKernelInterface::SUB_REQUEST))
->will($this->returnValue($response))
->willReturn($response)
;
$entryPoint = new FormAuthenticationEntryPoint($httpKernel, $httpUtils, '/the/login/path', true);
@@ -64,6 +65,6 @@ class FormAuthenticationEntryPointTest extends TestCase
$entryPointResponse = $entryPoint->start($request);
$this->assertEquals($response, $entryPointResponse);
$this->assertEquals(401, $entryPointResponse->headers->get('X-Status-Code'));
$this->assertEquals(401, $entryPointResponse->getStatusCode());
}
}
@@ -12,8 +12,8 @@
namespace Symfony\Component\Security\Http\Tests\EntryPoint;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\EntryPoint\RetryAuthenticationEntryPoint;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\EntryPoint\RetryAuthenticationEntryPoint;
class RetryAuthenticationEntryPointTest extends TestCase
{
@@ -32,34 +32,34 @@ class RetryAuthenticationEntryPointTest extends TestCase
public function dataForStart()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
return array(array());
return [[]];
}
return array(
array(
return [
[
80,
443,
Request::create('http://localhost/foo/bar?baz=bat'),
'https://localhost/foo/bar?baz=bat',
),
array(
],
[
80,
443,
Request::create('https://localhost/foo/bar?baz=bat'),
'http://localhost/foo/bar?baz=bat',
),
array(
],
[
80,
123,
Request::create('http://localhost/foo/bar?baz=bat'),
'https://localhost:123/foo/bar?baz=bat',
),
array(
],
[
8080,
443,
Request::create('https://localhost/foo/bar?baz=bat'),
'http://localhost:8080/foo/bar?baz=bat',
),
);
],
];
}
}
@@ -21,9 +21,9 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
{
public function testHandleWithValidValues()
{
$userCredentials = array('TheUser', 'TheCredentials');
$userCredentials = ['TheUser', 'TheCredentials'];
$request = new Request(array(), array(), array(), array(), array(), array());
$request = new Request([], [], [], [], [], []);
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
@@ -31,7 +31,7 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$tokenStorage
->expects($this->once())
@@ -44,24 +44,24 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
->will($this->returnValue($token))
->willReturn($token)
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', [
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
]);
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
->willReturn($userCredentials);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -69,15 +69,15 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
public function testHandleWhenAuthenticationFails()
{
$userCredentials = array('TheUser', 'TheCredentials');
$userCredentials = ['TheUser', 'TheCredentials'];
$request = new Request(array(), array(), array(), array(), array(), array());
$request = new Request([], [], [], [], [], []);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$tokenStorage
->expects($this->never())
@@ -90,24 +90,24 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
->will($this->throwException($exception))
->willThrowException($exception)
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', [
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
]);
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
->willReturn($userCredentials);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -115,17 +115,17 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
public function testHandleWhenAuthenticationFailsWithDifferentToken()
{
$userCredentials = array('TheUser', 'TheCredentials');
$userCredentials = ['TheUser', 'TheCredentials'];
$token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', array('ROLE_FOO'));
$token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', ['ROLE_FOO']);
$request = new Request(array(), array(), array(), array(), array(), array());
$request = new Request([], [], [], [], [], []);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
->willReturn($token)
;
$tokenStorage
->expects($this->never())
@@ -138,24 +138,24 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
->will($this->throwException($exception))
->willThrowException($exception)
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', [
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
]);
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
->willReturn($userCredentials);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -163,17 +163,17 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
public function testHandleWithASimilarAuthenticatedToken()
{
$userCredentials = array('TheUser', 'TheCredentials');
$userCredentials = ['TheUser', 'TheCredentials'];
$request = new Request(array(), array(), array(), array(), array(), array());
$request = new Request([], [], [], [], [], []);
$token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));
$token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', ['ROLE_FOO']);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
->willReturn($token)
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
@@ -182,21 +182,21 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
->method('authenticate')
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', [
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
]);
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
->willReturn($userCredentials);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -204,17 +204,17 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
public function testHandleWithAnInvalidSimilarToken()
{
$userCredentials = array('TheUser', 'TheCredentials');
$userCredentials = ['TheUser', 'TheCredentials'];
$request = new Request(array(), array(), array(), array(), array(), array());
$request = new Request([], [], [], [], [], []);
$token = new PreAuthenticatedToken('AnotherUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));
$token = new PreAuthenticatedToken('AnotherUser', 'TheCredentials', 'TheProviderKey', ['ROLE_FOO']);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
->willReturn($token)
;
$tokenStorage
->expects($this->once())
@@ -228,24 +228,24 @@ class AbstractPreAuthenticatedListenerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
->will($this->throwException($exception))
->willThrowException($exception)
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', [
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
]);
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
->willReturn($userCredentials);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -16,11 +16,9 @@ use Symfony\Component\Security\Http\Firewall\AccessListener;
class AccessListenerTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
*/
public function testHandleWhenTheAccessDecisionManagerDecidesToRefuseAccess()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AccessDeniedException');
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
@@ -28,29 +26,29 @@ class AccessListenerTest extends TestCase
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array('foo' => 'bar'), null)))
->willReturn([['foo' => 'bar'], null])
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->any())
->method('isAuthenticated')
->will($this->returnValue(true))
->willReturn(true)
;
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
->willReturn($token)
;
$accessDecisionManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock();
$accessDecisionManager
->expects($this->once())
->method('decide')
->with($this->equalTo($token), $this->equalTo(array('foo' => 'bar')), $this->equalTo($request))
->will($this->returnValue(false))
->with($this->equalTo($token), $this->equalTo(['foo' => 'bar']), $this->equalTo($request))
->willReturn(false)
;
$listener = new AccessListener(
@@ -64,7 +62,7 @@ class AccessListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -79,21 +77,21 @@ class AccessListenerTest extends TestCase
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array('foo' => 'bar'), null)))
->willReturn([['foo' => 'bar'], null])
;
$notAuthenticatedToken = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$notAuthenticatedToken
->expects($this->any())
->method('isAuthenticated')
->will($this->returnValue(false))
->willReturn(false)
;
$authenticatedToken = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$authenticatedToken
->expects($this->any())
->method('isAuthenticated')
->will($this->returnValue(true))
->willReturn(true)
;
$authManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
@@ -101,14 +99,14 @@ class AccessListenerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->equalTo($notAuthenticatedToken))
->will($this->returnValue($authenticatedToken))
->willReturn($authenticatedToken)
;
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($notAuthenticatedToken))
->willReturn($notAuthenticatedToken)
;
$tokenStorage
->expects($this->once())
@@ -120,8 +118,8 @@ class AccessListenerTest extends TestCase
$accessDecisionManager
->expects($this->once())
->method('decide')
->with($this->equalTo($authenticatedToken), $this->equalTo(array('foo' => 'bar')), $this->equalTo($request))
->will($this->returnValue(true))
->with($this->equalTo($authenticatedToken), $this->equalTo(['foo' => 'bar']), $this->equalTo($request))
->willReturn(true)
;
$listener = new AccessListener(
@@ -135,7 +133,7 @@ class AccessListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -150,7 +148,7 @@ class AccessListenerTest extends TestCase
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(null, null)))
->willReturn([null, null])
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
@@ -163,7 +161,7 @@ class AccessListenerTest extends TestCase
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
->willReturn($token)
;
$listener = new AccessListener(
@@ -177,22 +175,20 @@ class AccessListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testHandleWhenTheSecurityTokenStorageHasNoToken()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException');
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$listener = new AccessListener(
@@ -23,7 +23,7 @@ class AnonymousAuthenticationListenerTest extends TestCase
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock())
;
$tokenStorage
->expects($this->never())
@@ -46,10 +46,10 @@ class AnonymousAuthenticationListenerTest extends TestCase
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$anonymousToken = new AnonymousToken('TheSecret', 'anon.', array());
$anonymousToken = new AnonymousToken('TheSecret', 'anon.', []);
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
@@ -58,7 +58,7 @@ class AnonymousAuthenticationListenerTest extends TestCase
->with($this->callback(function ($token) {
return 'TheSecret' === $token->getSecret();
}))
->will($this->returnValue($anonymousToken))
->willReturn($anonymousToken)
;
$tokenStorage
@@ -13,20 +13,20 @@ namespace Symfony\Component\Security\Http\Tests\Firewall;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
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 TestCase
{
public function testHandleWithValidUsernameAndPasswordServerParameters()
{
$request = new Request(array(), array(), array(), array(), array(), array(
$request = new Request([], [], [], [], [], [
'PHP_AUTH_USER' => 'TheUsername',
'PHP_AUTH_PW' => 'ThePassword',
));
]);
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
@@ -34,7 +34,7 @@ class BasicAuthenticationListenerTest extends TestCase
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$tokenStorage
->expects($this->once())
@@ -47,7 +47,7 @@ class BasicAuthenticationListenerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken'))
->will($this->returnValue($token))
->willReturn($token)
;
$listener = new BasicAuthenticationListener(
@@ -61,7 +61,7 @@ class BasicAuthenticationListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -69,18 +69,16 @@ class BasicAuthenticationListenerTest extends TestCase
public function testHandleWhenAuthenticationFails()
{
$request = new Request(array(), array(), array(), array(), array(), array(
$request = new Request([], [], [], [], [], [
'PHP_AUTH_USER' => 'TheUsername',
'PHP_AUTH_PW' => 'ThePassword',
));
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
]);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$tokenStorage
->expects($this->never())
@@ -94,12 +92,12 @@ class BasicAuthenticationListenerTest extends TestCase
->expects($this->any())
->method('start')
->with($this->equalTo($request), $this->isInstanceOf('Symfony\Component\Security\Core\Exception\AuthenticationException'))
->will($this->returnValue($response))
->willReturn($response)
;
$listener = new BasicAuthenticationListener(
$tokenStorage,
new AuthenticationProviderManager(array($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock())),
new AuthenticationProviderManager([$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock()]),
'TheProviderKey',
$authenticationEntryPoint
);
@@ -108,7 +106,7 @@ class BasicAuthenticationListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$event
->expects($this->once())
@@ -140,7 +138,7 @@ class BasicAuthenticationListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -148,15 +146,15 @@ class BasicAuthenticationListenerTest extends TestCase
public function testHandleWithASimilarAuthenticatedToken()
{
$request = new Request(array(), array(), array(), array(), array(), array('PHP_AUTH_USER' => 'TheUsername'));
$request = new Request([], [], [], [], [], ['PHP_AUTH_USER' => 'TheUsername']);
$token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', array('ROLE_FOO'));
$token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', ['ROLE_FOO']);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
->willReturn($token)
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
@@ -176,18 +174,16 @@ class BasicAuthenticationListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage $providerKey must not be empty
*/
public function testItRequiresProviderKey()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('$providerKey must not be empty');
new BasicAuthenticationListener(
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(),
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
@@ -198,18 +194,18 @@ class BasicAuthenticationListenerTest extends TestCase
public function testHandleWithADifferentAuthenticatedToken()
{
$request = new Request(array(), array(), array(), array(), array(), array(
$request = new Request([], [], [], [], [], [
'PHP_AUTH_USER' => 'TheUsername',
'PHP_AUTH_PW' => 'ThePassword',
));
]);
$token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));
$token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', ['ROLE_FOO']);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
->willReturn($token)
;
$tokenStorage
->expects($this->never())
@@ -223,12 +219,12 @@ class BasicAuthenticationListenerTest extends TestCase
->expects($this->any())
->method('start')
->with($this->equalTo($request), $this->isInstanceOf('Symfony\Component\Security\Core\Exception\AuthenticationException'))
->will($this->returnValue($response))
->willReturn($response)
;
$listener = new BasicAuthenticationListener(
$tokenStorage,
new AuthenticationProviderManager(array($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock())),
new AuthenticationProviderManager([$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock()]),
'TheProviderKey',
$authenticationEntryPoint
);
@@ -237,7 +233,7 @@ class BasicAuthenticationListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$event
->expects($this->once())
@@ -12,8 +12,8 @@
namespace Symfony\Component\Security\Http\Tests\Firewall;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\Firewall\ChannelListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Firewall\ChannelListener;
class ChannelListenerTest extends TestCase
{
@@ -23,7 +23,7 @@ class ChannelListenerTest extends TestCase
$request
->expects($this->any())
->method('isSecure')
->will($this->returnValue(false))
->willReturn(false)
;
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
@@ -31,7 +31,7 @@ class ChannelListenerTest extends TestCase
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), 'http')))
->willReturn([[], 'http'])
;
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
@@ -44,7 +44,7 @@ class ChannelListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$event
->expects($this->never())
@@ -61,7 +61,7 @@ class ChannelListenerTest extends TestCase
$request
->expects($this->any())
->method('isSecure')
->will($this->returnValue(true))
->willReturn(true)
;
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
@@ -69,7 +69,7 @@ class ChannelListenerTest extends TestCase
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), 'https')))
->willReturn([[], 'https'])
;
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
@@ -82,7 +82,7 @@ class ChannelListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$event
->expects($this->never())
@@ -99,7 +99,7 @@ class ChannelListenerTest extends TestCase
$request
->expects($this->any())
->method('isSecure')
->will($this->returnValue(false))
->willReturn(false)
;
$response = new Response();
@@ -109,7 +109,7 @@ class ChannelListenerTest extends TestCase
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), 'https')))
->willReturn([[], 'https'])
;
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
@@ -117,14 +117,14 @@ class ChannelListenerTest extends TestCase
->expects($this->once())
->method('start')
->with($this->equalTo($request))
->will($this->returnValue($response))
->willReturn($response)
;
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$event
->expects($this->once())
@@ -142,7 +142,7 @@ class ChannelListenerTest extends TestCase
$request
->expects($this->any())
->method('isSecure')
->will($this->returnValue(true))
->willReturn(true)
;
$response = new Response();
@@ -152,7 +152,7 @@ class ChannelListenerTest extends TestCase
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), 'http')))
->willReturn([[], 'http'])
;
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
@@ -160,14 +160,14 @@ class ChannelListenerTest extends TestCase
->expects($this->once())
->method('start')
->with($this->equalTo($request))
->will($this->returnValue($response))
->willReturn($response)
;
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$event
->expects($this->once())
@@ -12,6 +12,7 @@
namespace Symfony\Component\Security\Http\Tests\Firewall;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
@@ -30,34 +31,26 @@ use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Firewall\ContextListener;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
class ContextListenerTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage $contextKey must not be empty
*/
public function testItRequiresContextKey()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('$contextKey must not be empty');
new ContextListener(
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(),
array(),
[],
''
);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage User provider "stdClass" must implement "Symfony\Component\Security\Core\User\UserProviderInterface
*/
public function testUserProvidersNeedToImplementAnInterface()
{
new ContextListener(
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(),
array(new \stdClass()),
'key123'
);
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('User provider "stdClass" must implement "Symfony\Component\Security\Core\User\UserProviderInterface');
$this->handleEventWithPreviousSession(new TokenStorage(), [new \stdClass()]);
}
public function testOnKernelResponseWillAddSession()
@@ -116,7 +109,7 @@ class ContextListenerTest extends TestCase
new Response()
);
$listener = new ContextListener($tokenStorage, array(), 'session', null, new EventDispatcher());
$listener = new ContextListener($tokenStorage, [], 'session', null, new EventDispatcher());
$listener->onKernelResponse($event);
$this->assertTrue($session->isStarted());
@@ -135,7 +128,7 @@ class ContextListenerTest extends TestCase
new Response()
);
$listener = new ContextListener(new TokenStorage(), array(), 'session', null, new EventDispatcher());
$listener = new ContextListener(new TokenStorage(), [], 'session', null, new EventDispatcher());
$listener->onKernelResponse($event);
$this->assertFalse($session->isStarted());
@@ -155,32 +148,34 @@ class ContextListenerTest extends TestCase
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($request));
->willReturn($request);
$request->expects($this->any())
->method('hasPreviousSession')
->will($this->returnValue(true));
->willReturn(true);
$request->expects($this->any())
->method('getSession')
->will($this->returnValue($session));
->willReturn($session);
$session->expects($this->any())
->method('get')
->with('_security_key123')
->will($this->returnValue($token));
->willReturn($token);
$tokenStorage->expects($this->once())
->method('setToken')
->with(null);
$listener = new ContextListener($tokenStorage, array(), 'key123');
$listener = new ContextListener($tokenStorage, [], 'key123');
$listener->handle($event);
}
public function provideInvalidToken()
{
return array(
array(serialize(new \__PHP_Incomplete_Class())),
array(serialize(null)),
array(null),
);
return [
['foo'],
['O:8:"NotFound":0:{}'],
[serialize(new \__PHP_Incomplete_Class())],
[serialize(null)],
[null],
];
}
public function testHandleAddsKernelResponseListener()
@@ -191,18 +186,18 @@ class ContextListenerTest extends TestCase
->disableOriginalConstructor()
->getMock();
$listener = new ContextListener($tokenStorage, array(), 'key123', null, $dispatcher);
$listener = new ContextListener($tokenStorage, [], 'key123', null, $dispatcher);
$event->expects($this->any())
->method('isMasterRequest')
->will($this->returnValue(true));
->willReturn(true);
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock()));
->willReturn($this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock());
$dispatcher->expects($this->once())
->method('addListener')
->with(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
->with(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']);
$listener->handle($event);
}
@@ -215,23 +210,23 @@ class ContextListenerTest extends TestCase
->disableOriginalConstructor()
->getMock();
$listener = new ContextListener($tokenStorage, array(), 'key123', null, $dispatcher);
$listener = new ContextListener($tokenStorage, [], 'key123', null, $dispatcher);
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$request->expects($this->any())
->method('hasSession')
->will($this->returnValue(true));
->willReturn(true);
$event->expects($this->any())
->method('isMasterRequest')
->will($this->returnValue(true));
->willReturn(true);
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($request));
->willReturn($request);
$dispatcher->expects($this->once())
->method('removeListener')
->with(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
->with(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']);
$listener->onKernelResponse($event);
}
@@ -239,25 +234,69 @@ class ContextListenerTest extends TestCase
public function testHandleRemovesTokenIfNoPreviousSessionWasFound()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$request->expects($this->any())->method('hasPreviousSession')->will($this->returnValue(false));
$request->expects($this->any())->method('hasPreviousSession')->willReturn(false);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
->disableOriginalConstructor()
->getMock();
$event->expects($this->any())->method('getRequest')->will($this->returnValue($request));
$event->expects($this->any())->method('getRequest')->willReturn($request);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage->expects($this->once())->method('setToken')->with(null);
$listener = new ContextListener($tokenStorage, array(), 'key123');
$listener = new ContextListener($tokenStorage, [], 'key123');
$listener->handle($event);
}
/**
* @group legacy
* @expectedDeprecation Refreshing a deauthenticated user is deprecated as of 3.4 and will trigger a logout in 4.0.
*/
public function testIfTokenIsDeauthenticatedTriggersDeprecations()
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$this->handleEventWithPreviousSession($tokenStorage, [new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)]);
$this->assertSame($refreshedUser, $tokenStorage->getToken()->getUser());
}
public function testIfTokenIsDeauthenticated()
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$this->handleEventWithPreviousSession($tokenStorage, [new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)], null, true);
$this->assertNull($tokenStorage->getToken());
}
public function testIfTokenIsNotDeauthenticated()
{
$tokenStorage = new TokenStorage();
$badRefreshedUser = new User('foobar', 'baz');
$goodRefreshedUser = new User('foobar', 'bar');
$this->handleEventWithPreviousSession($tokenStorage, [new SupportingUserProvider($badRefreshedUser), new SupportingUserProvider($goodRefreshedUser)], $goodRefreshedUser, true);
$this->assertSame($goodRefreshedUser, $tokenStorage->getToken()->getUser());
}
public function testRememberMeGetsCanceledIfTokenIsDeauthenticated()
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$rememberMeServices = $this->createMock(RememberMeServicesInterface::class);
$rememberMeServices->expects($this->once())->method('loginFail');
$this->handleEventWithPreviousSession($tokenStorage, [new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)], null, true, $rememberMeServices);
$this->assertNull($tokenStorage->getToken());
}
public function testTryAllUserProvidersUntilASupportingUserProviderIsFound()
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$this->handleEventWithPreviousSession($tokenStorage, array(new NotSupportingUserProvider(), new SupportingUserProvider($refreshedUser)));
$this->handleEventWithPreviousSession($tokenStorage, [new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)], $refreshedUser);
$this->assertSame($refreshedUser, $tokenStorage->getToken()->getUser());
}
@@ -266,7 +305,7 @@ class ContextListenerTest extends TestCase
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$this->handleEventWithPreviousSession($tokenStorage, array(new SupportingUserProvider(), new SupportingUserProvider($refreshedUser)));
$this->handleEventWithPreviousSession($tokenStorage, [new SupportingUserProvider(), new SupportingUserProvider($refreshedUser)], $refreshedUser);
$this->assertSame($refreshedUser, $tokenStorage->getToken()->getUser());
}
@@ -274,24 +313,31 @@ class ContextListenerTest extends TestCase
public function testTokenIsSetToNullIfNoUserWasLoadedByTheRegisteredUserProviders()
{
$tokenStorage = new TokenStorage();
$this->handleEventWithPreviousSession($tokenStorage, array(new NotSupportingUserProvider(), new SupportingUserProvider()));
$this->handleEventWithPreviousSession($tokenStorage, [new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider()]);
$this->assertNull($tokenStorage->getToken());
}
/**
* @expectedException \RuntimeException
*/
public function testRuntimeExceptionIsThrownIfNoSupportingUserProviderWasRegistered()
{
$this->handleEventWithPreviousSession(new TokenStorage(), array(new NotSupportingUserProvider(), new NotSupportingUserProvider()));
$this->expectException('RuntimeException');
$this->handleEventWithPreviousSession(new TokenStorage(), [new NotSupportingUserProvider(false), new NotSupportingUserProvider(true)]);
}
public function testAcceptsProvidersAsTraversable()
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$this->handleEventWithPreviousSession($tokenStorage, new \ArrayObject([new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)]), $refreshedUser);
$this->assertSame($refreshedUser, $tokenStorage->getToken()->getUser());
}
protected function runSessionOnKernelResponse($newToken, $original = null)
{
$session = new Session(new MockArraySessionStorage());
if ($original !== null) {
if (null !== $original) {
$session->set('_security_session', $original);
}
@@ -309,28 +355,42 @@ class ContextListenerTest extends TestCase
new Response()
);
$listener = new ContextListener($tokenStorage, array(), 'session', null, new EventDispatcher());
$listener = new ContextListener($tokenStorage, [], 'session', null, new EventDispatcher());
$listener->onKernelResponse($event);
return $session;
}
private function handleEventWithPreviousSession(TokenStorageInterface $tokenStorage, array $userProviders)
private function handleEventWithPreviousSession(TokenStorageInterface $tokenStorage, $userProviders, UserInterface $user = null, $logoutOnUserChange = false, RememberMeServicesInterface $rememberMeServices = null)
{
$user = $user ?: new User('foo', 'bar');
$session = new Session(new MockArraySessionStorage());
$session->set('_security_context_key', serialize(new UsernamePasswordToken(new User('foo', 'bar'), '', 'context_key')));
$session->set('_security_context_key', serialize(new UsernamePasswordToken($user, '', 'context_key', ['ROLE_USER'])));
$request = new Request();
$request->setSession($session);
$request->cookies->set('MOCKSESSID', true);
$listener = new ContextListener($tokenStorage, $userProviders, 'context_key');
$listener->setLogoutOnUserChange($logoutOnUserChange);
if ($rememberMeServices) {
$listener->setRememberMeServices($rememberMeServices);
}
$listener->handle(new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST));
}
}
class NotSupportingUserProvider implements UserProviderInterface
{
/** @var bool */
private $throwsUnsupportedException;
public function __construct($throwsUnsupportedException)
{
$this->throwsUnsupportedException = $throwsUnsupportedException;
}
public function loadUserByUsername($username)
{
throw new UsernameNotFoundException();
@@ -338,7 +398,11 @@ class NotSupportingUserProvider implements UserProviderInterface
public function refreshUser(UserInterface $user)
{
throw new UnsupportedUserException();
if ($this->throwsUnsupportedException) {
throw new UnsupportedUserException();
}
return $user;
}
public function supportsClass($class)
@@ -8,6 +8,9 @@ use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\EntryPoint\DigestAuthenticationEntryPoint;
use Symfony\Component\Security\Http\Firewall\DigestAuthenticationListener;
/**
* @group legacy
*/
class DigestAuthenticationListenerTest extends TestCase
{
public function testHandleWithValidDigest()
@@ -31,7 +34,7 @@ class DigestAuthenticationListenerTest extends TestCase
'response="'.$serverDigest.'"'
;
$request = new Request(array(), array(), array(), array(), array(), array('PHP_AUTH_DIGEST' => $digestData));
$request = new Request([], [], [], [], [], ['PHP_AUTH_DIGEST' => $digestData]);
$entryPoint = new DigestAuthenticationEntryPoint($realm, $secret);
@@ -44,7 +47,7 @@ class DigestAuthenticationListenerTest extends TestCase
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$tokenStorage
->expects($this->once())
@@ -61,7 +64,7 @@ class DigestAuthenticationListenerTest extends TestCase
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -14,6 +14,9 @@ namespace Symfony\Component\Security\Http\Tests\Firewall;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\Firewall\DigestData;
/**
* @group legacy
*/
class DigestDataTest extends TestCase
{
public function testGetResponse()
@@ -15,11 +15,13 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\LogoutException;
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Firewall\ExceptionListener;
@@ -30,7 +32,7 @@ class ExceptionListenerTest extends TestCase
/**
* @dataProvider getAuthenticationExceptionProvider
*/
public function testAuthenticationExceptionWithoutEntryPoint(\Exception $exception, \Exception $eventException = null)
public function testAuthenticationExceptionWithoutEntryPoint(\Exception $exception, \Exception $eventException)
{
$event = $this->createEvent($exception);
@@ -38,46 +40,54 @@ class ExceptionListenerTest extends TestCase
$listener->onKernelException($event);
$this->assertNull($event->getResponse());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getException());
$this->assertEquals($eventException, $event->getException());
}
/**
* @dataProvider getAuthenticationExceptionProvider
*/
public function testAuthenticationExceptionWithEntryPoint(\Exception $exception, \Exception $eventException = null)
public function testAuthenticationExceptionWithEntryPoint(\Exception $exception)
{
$event = $this->createEvent($exception = new AuthenticationException());
$event = $this->createEvent($exception);
$listener = $this->createExceptionListener(null, null, null, $this->createEntryPoint());
$response = new Response('Forbidden', 403);
$listener = $this->createExceptionListener(null, null, null, $this->createEntryPoint($response));
$listener->onKernelException($event);
$this->assertEquals('OK', $event->getResponse()->getContent());
$this->assertTrue($event->isAllowingCustomResponseCode());
$this->assertEquals('Forbidden', $event->getResponse()->getContent());
$this->assertEquals(403, $event->getResponse()->getStatusCode());
$this->assertSame($exception, $event->getException());
}
public function getAuthenticationExceptionProvider()
{
return array(
array(new AuthenticationException()),
array(new \LogicException('random', 0, $e = new AuthenticationException()), $e),
array(new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AuthenticationException())), $e),
array(new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AccessDeniedException())), $e),
array(new AuthenticationException('random', 0, new \LogicException())),
);
return [
[$e = new AuthenticationException(), new HttpException(Response::HTTP_UNAUTHORIZED, '', $e, [], 0)],
[new \LogicException('random', 0, $e = new AuthenticationException()), new HttpException(Response::HTTP_UNAUTHORIZED, '', $e, [], 0)],
[new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AuthenticationException())), new HttpException(Response::HTTP_UNAUTHORIZED, 'embed', $e, [], 0)],
[new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AccessDeniedException())), new HttpException(Response::HTTP_UNAUTHORIZED, 'embed', $e, [], 0)],
[$e = new AuthenticationException('random', 0, new \LogicException()), new HttpException(Response::HTTP_UNAUTHORIZED, 'random', $e, [], 0)],
];
}
/**
* @group legacy
*/
public function testExceptionWhenEntryPointReturnsBadValue()
{
$event = $this->createEvent(new AuthenticationException());
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$entryPoint->expects($this->once())->method('start')->will($this->returnValue('NOT A RESPONSE'));
$entryPoint->expects($this->once())->method('start')->willReturn('NOT A RESPONSE');
$listener = $this->createExceptionListener(null, null, null, $entryPoint);
$listener->onKernelException($event);
// the exception has been replaced by our LogicException
$this->assertInstanceOf('LogicException', $event->getException());
$this->assertStringEndsWith('start() method must return a Response object (string returned)', $event->getException()->getMessage());
$this->assertStringEndsWith('start()" method must return a Response object ("string" returned).', $event->getException()->getMessage());
}
/**
@@ -100,17 +110,20 @@ class ExceptionListenerTest extends TestCase
public function testAccessDeniedExceptionFullFledgedAndWithoutAccessDeniedHandlerAndWithErrorPage(\Exception $exception, \Exception $eventException = null)
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel->expects($this->once())->method('handle')->will($this->returnValue(new Response('error')));
$kernel->expects($this->once())->method('handle')->willReturn(new Response('Unauthorized', 401));
$event = $this->createEvent($exception, $kernel);
$httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
$httpUtils->expects($this->once())->method('createRequest')->will($this->returnValue(Request::create('/error')));
$httpUtils->expects($this->once())->method('createRequest')->willReturn(Request::create('/error'));
$listener = $this->createExceptionListener(null, $this->createTrustResolver(true), $httpUtils, null, '/error');
$listener->onKernelException($event);
$this->assertEquals('error', $event->getResponse()->getContent());
$this->assertTrue($event->isAllowingCustomResponseCode());
$this->assertEquals('Unauthorized', $event->getResponse()->getContent());
$this->assertEquals(401, $event->getResponse()->getStatusCode());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
}
@@ -122,7 +135,7 @@ class ExceptionListenerTest extends TestCase
$event = $this->createEvent($exception);
$accessDeniedHandler = $this->getMockBuilder('Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface')->getMock();
$accessDeniedHandler->expects($this->once())->method('handle')->will($this->returnValue(new Response('error')));
$accessDeniedHandler->expects($this->once())->method('handle')->willReturn(new Response('error'));
$listener = $this->createExceptionListener(null, $this->createTrustResolver(true), null, null, null, $accessDeniedHandler);
$listener->onKernelException($event);
@@ -139,7 +152,7 @@ class ExceptionListenerTest extends TestCase
$event = $this->createEvent($exception);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage->expects($this->once())->method('getToken')->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$tokenStorage->expects($this->once())->method('getToken')->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$listener = $this->createExceptionListener($tokenStorage, $this->createTrustResolver(false), null, $this->createEntryPoint());
$listener->onKernelException($event);
@@ -148,21 +161,32 @@ class ExceptionListenerTest extends TestCase
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
}
public function getAccessDeniedExceptionProvider()
public function testLogoutException()
{
return array(
array(new AccessDeniedException()),
array(new \LogicException('random', 0, $e = new AccessDeniedException()), $e),
array(new \LogicException('random', 0, $e = new AccessDeniedException('embed', new AccessDeniedException())), $e),
array(new \LogicException('random', 0, $e = new AccessDeniedException('embed', new AuthenticationException())), $e),
array(new AccessDeniedException('random', new \LogicException())),
);
$event = $this->createEvent(new LogoutException('Invalid CSRF.'));
$listener = $this->createExceptionListener();
$listener->onKernelException($event);
$this->assertEquals('Invalid CSRF.', $event->getException()->getMessage());
$this->assertEquals(403, $event->getException()->getStatusCode());
}
private function createEntryPoint()
public function getAccessDeniedExceptionProvider()
{
return [
[new AccessDeniedException()],
[new \LogicException('random', 0, $e = new AccessDeniedException()), $e],
[new \LogicException('random', 0, $e = new AccessDeniedException('embed', new AccessDeniedException())), $e],
[new \LogicException('random', 0, $e = new AccessDeniedException('embed', new AuthenticationException())), $e],
[new AccessDeniedException('random', new \LogicException())],
];
}
private function createEntryPoint(Response $response = null)
{
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$entryPoint->expects($this->once())->method('start')->will($this->returnValue(new Response('OK')));
$entryPoint->expects($this->once())->method('start')->willReturn($response ?: new Response('OK'));
return $entryPoint;
}
@@ -170,7 +194,7 @@ class ExceptionListenerTest extends TestCase
private function createTrustResolver($fullFledged)
{
$trustResolver = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface')->getMock();
$trustResolver->expects($this->once())->method('isFullFledged')->will($this->returnValue($fullFledged));
$trustResolver->expects($this->once())->method('isFullFledged')->willReturn($fullFledged);
return $trustResolver;
}
@@ -20,7 +20,7 @@ class LogoutListenerTest extends TestCase
{
public function testHandleUnmatchedPath()
{
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener();
list($listener, , $httpUtils, $options) = $this->getListener();
list($event, $request) = $this->getGetResponseEvent();
@@ -30,7 +30,7 @@ class LogoutListenerTest extends TestCase
$httpUtils->expects($this->once())
->method('checkRequestPath')
->with($request, $options['logout_path'])
->will($this->returnValue(false));
->willReturn(false);
$listener->handle($event);
}
@@ -49,20 +49,20 @@ class LogoutListenerTest extends TestCase
$httpUtils->expects($this->once())
->method('checkRequestPath')
->with($request, $options['logout_path'])
->will($this->returnValue(true));
->willReturn(true);
$tokenManager->expects($this->once())
->method('isTokenValid')
->will($this->returnValue(true));
->willReturn(true);
$successHandler->expects($this->once())
->method('onLogoutSuccess')
->with($request)
->will($this->returnValue($response = new Response()));
->willReturn($response = new Response());
$tokenStorage->expects($this->once())
->method('getToken')
->will($this->returnValue($token = $this->getToken()));
->willReturn($token = $this->getToken());
$handler = $this->getHandler();
$handler->expects($this->once())
@@ -93,16 +93,16 @@ class LogoutListenerTest extends TestCase
$httpUtils->expects($this->once())
->method('checkRequestPath')
->with($request, $options['logout_path'])
->will($this->returnValue(true));
->willReturn(true);
$successHandler->expects($this->once())
->method('onLogoutSuccess')
->with($request)
->will($this->returnValue($response = new Response()));
->willReturn($response = new Response());
$tokenStorage->expects($this->once())
->method('getToken')
->will($this->returnValue($token = $this->getToken()));
->willReturn($token = $this->getToken());
$handler = $this->getHandler();
$handler->expects($this->once())
@@ -123,37 +123,36 @@ class LogoutListenerTest extends TestCase
}
/**
* @expectedException \RuntimeException
* @group legacy
*/
public function testSuccessHandlerReturnsNonResponse()
{
$this->expectException('RuntimeException');
$successHandler = $this->getSuccessHandler();
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener($successHandler);
list($listener, , $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));
->willReturn(true);
$successHandler->expects($this->once())
->method('onLogoutSuccess')
->with($request)
->will($this->returnValue(null));
->willReturn(null);
$listener->handle($event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\LogoutException
*/
public function testCsrfValidationFails()
{
$this->expectException('Symfony\Component\Security\Core\Exception\LogoutException');
$tokenManager = $this->getTokenManager();
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener(null, $tokenManager);
list($listener, , $httpUtils, $options) = $this->getListener(null, $tokenManager);
list($event, $request) = $this->getGetResponseEvent();
@@ -162,11 +161,11 @@ class LogoutListenerTest extends TestCase
$httpUtils->expects($this->once())
->method('checkRequestPath')
->with($request, $options['logout_path'])
->will($this->returnValue(true));
->willReturn(true);
$tokenManager->expects($this->once())
->method('isTokenValid')
->will($this->returnValue(false));
->willReturn(false);
$listener->handle($event);
}
@@ -189,9 +188,9 @@ class LogoutListenerTest extends TestCase
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($request = new Request()));
->willReturn($request = new Request());
return array($event, $request);
return [$event, $request];
}
private function getHandler()
@@ -212,16 +211,16 @@ class LogoutListenerTest extends TestCase
$tokenStorage = $this->getTokenStorage(),
$httpUtils = $this->getHttpUtils(),
$successHandler ?: $this->getSuccessHandler(),
$options = array(
$options = [
'csrf_parameter' => '_csrf_token',
'csrf_token_id' => 'logout',
'logout_path' => '/logout',
'target_url' => '/',
),
],
$tokenManager
);
return array($listener, $tokenStorage, $httpUtils, $options);
return [$listener, $tokenStorage, $httpUtils, $options];
}
private function getSuccessHandler()
@@ -12,9 +12,9 @@
namespace Symfony\Component\Security\Http\Tests\Firewall;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Firewall\RememberMeListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\SecurityEvents;
class RememberMeListenerTest extends TestCase
@@ -26,7 +26,7 @@ class RememberMeListenerTest extends TestCase
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock())
;
$tokenStorage
@@ -44,20 +44,20 @@ class RememberMeListenerTest extends TestCase
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue(null))
->willReturn(null)
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue(new Request()))
->willReturn(new Request())
;
$this->assertNull($listener->handle($event));
@@ -66,59 +66,59 @@ class RememberMeListenerTest extends TestCase
public function testOnCoreSecurityIgnoresAuthenticationExceptionThrownByAuthenticationManagerImplementation()
{
list($listener, $tokenStorage, $service, $manager) = $this->getListener();
$request = new Request();
$exception = new AuthenticationException('Authentication failed.');
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock())
;
$service
->expects($this->once())
->method('loginFail')
->with($request, $exception)
;
$exception = new AuthenticationException('Authentication failed.');
$manager
->expects($this->once())
->method('authenticate')
->will($this->throwException($exception))
->willThrowException($exception)
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue(new Request()))
->willReturn($request)
;
$listener->handle($event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationException
* @expectedExceptionMessage Authentication failed.
*/
public function testOnCoreSecurityIgnoresAuthenticationOptionallyRethrowsExceptionThrownAuthenticationManagerImplementation()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException');
$this->expectExceptionMessage('Authentication failed.');
list($listener, $tokenStorage, $service, $manager) = $this->getListener(false, false);
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock())
;
$service
@@ -130,14 +130,51 @@ class RememberMeListenerTest extends TestCase
$manager
->expects($this->once())
->method('authenticate')
->will($this->throwException($exception))
->willThrowException($exception)
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue(new Request()))
->willReturn(new Request())
;
$listener->handle($event);
}
public function testOnCoreSecurityAuthenticationExceptionDuringAutoLoginTriggersLoginFail()
{
list($listener, $tokenStorage, $service, $manager) = $this->getListener();
$tokenStorage
->expects($this->once())
->method('getToken')
->willReturn(null)
;
$exception = new AuthenticationException('Authentication failed.');
$service
->expects($this->once())
->method('autoLogin')
->willThrowException($exception)
;
$service
->expects($this->once())
->method('loginFail')
;
$manager
->expects($this->never())
->method('authenticate')
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->willReturn(new Request())
;
$listener->handle($event);
@@ -150,14 +187,14 @@ class RememberMeListenerTest extends TestCase
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($token))
->willReturn($token)
;
$tokenStorage
@@ -169,14 +206,14 @@ class RememberMeListenerTest extends TestCase
$manager
->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
->willReturn($token)
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue(new Request()))
->willReturn(new Request())
;
$listener->handle($event);
@@ -184,19 +221,19 @@ class RememberMeListenerTest extends TestCase
public function testSessionStrategy()
{
list($listener, $tokenStorage, $service, $manager, , $dispatcher, $sessionStrategy) = $this->getListener(false, true, true);
list($listener, $tokenStorage, $service, $manager, , , $sessionStrategy) = $this->getListener(false, true, true);
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($token))
->willReturn($token)
;
$tokenStorage
@@ -208,40 +245,40 @@ class RememberMeListenerTest extends TestCase
$manager
->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
->willReturn($token)
;
$session = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$session
->expects($this->once())
->method('isStarted')
->will($this->returnValue(true))
->willReturn(true)
;
$request = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Request')->getMock();
$request
->expects($this->once())
->method('hasSession')
->will($this->returnValue(true))
->willReturn(true)
;
$request
->expects($this->once())
->method('getSession')
->will($this->returnValue($session))
->willReturn($session)
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$sessionStrategy
->expects($this->once())
->method('onAuthentication')
->will($this->returnValue(null))
->willReturn(null)
;
$listener->handle($event);
@@ -249,19 +286,19 @@ class RememberMeListenerTest extends TestCase
public function testSessionIsMigratedByDefault()
{
list($listener, $tokenStorage, $service, $manager, , $dispatcher, $sessionStrategy) = $this->getListener(false, true, false);
list($listener, $tokenStorage, $service, $manager) = $this->getListener(false, true, false);
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($token))
->willReturn($token)
;
$tokenStorage
@@ -273,14 +310,14 @@ class RememberMeListenerTest extends TestCase
$manager
->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
->willReturn($token)
;
$session = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$session
->expects($this->once())
->method('isStarted')
->will($this->returnValue(true))
->willReturn(true)
;
$session
->expects($this->once())
@@ -291,20 +328,20 @@ class RememberMeListenerTest extends TestCase
$request
->expects($this->any())
->method('hasSession')
->will($this->returnValue(true))
->willReturn(true)
;
$request
->expects($this->any())
->method('getSession')
->will($this->returnValue($session))
->willReturn($session)
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
@@ -317,14 +354,14 @@ class RememberMeListenerTest extends TestCase
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
->willReturn(null)
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($token))
->willReturn($token)
;
$tokenStorage
@@ -336,7 +373,7 @@ class RememberMeListenerTest extends TestCase
$manager
->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
->willReturn($token)
;
$event = $this->getGetResponseEvent();
@@ -344,7 +381,7 @@ class RememberMeListenerTest extends TestCase
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$dispatcher
@@ -381,7 +418,7 @@ class RememberMeListenerTest extends TestCase
$sessionStrategy = ($withSessionStrategy ? $this->getSessionStrategy() : null)
);
return array($listener, $tokenStorage, $service, $manager, $logger, $dispatcher, $sessionStrategy);
return [$listener, $tokenStorage, $service, $manager, $logger, $dispatcher, $sessionStrategy];
}
protected function getLogger()
@@ -19,11 +19,11 @@ class RemoteUserAuthenticationListenerTest extends TestCase
{
public function testGetPreAuthenticatedData()
{
$serverVars = array(
$serverVars = [
'REMOTE_USER' => 'TheUser',
);
];
$request = new Request(array(), array(), array(), array(), array(), $serverVars);
$request = new Request([], [], [], [], [], $serverVars);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
@@ -38,16 +38,14 @@ class RemoteUserAuthenticationListenerTest extends TestCase
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$this->assertSame($result, array('TheUser', null));
$result = $method->invokeArgs($listener, [$request]);
$this->assertSame($result, ['TheUser', null]);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testGetPreAuthenticatedDataNoUser()
{
$request = new Request(array(), array(), array(), array(), array(), array());
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$request = new Request([], [], [], [], [], []);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
@@ -62,16 +60,16 @@ class RemoteUserAuthenticationListenerTest extends TestCase
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$method->invokeArgs($listener, [$request]);
}
public function testGetPreAuthenticatedDataWithDifferentKeys()
{
$userCredentials = array('TheUser', null);
$userCredentials = ['TheUser', null];
$request = new Request(array(), array(), array(), array(), array(), array(
$request = new Request([], [], [], [], [], [
'TheUserKey' => 'TheUser',
));
]);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
@@ -86,7 +84,7 @@ class RemoteUserAuthenticationListenerTest extends TestCase
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$result = $method->invokeArgs($listener, [$request]);
$this->assertSame($result, $userCredentials);
}
}
@@ -40,7 +40,7 @@ class SimplePreAuthenticationListenerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->equalTo($this->token))
->will($this->returnValue($this->token))
->willReturn($this->token)
;
$simpleAuthenticator = $this->getMockBuilder('Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface')->getMock();
@@ -48,7 +48,7 @@ class SimplePreAuthenticationListenerTest extends TestCase
->expects($this->once())
->method('createToken')
->with($this->equalTo($this->request), $this->equalTo('secured_area'))
->will($this->returnValue($this->token))
->willReturn($this->token)
;
$loginEvent = new InteractiveLoginEvent($this->request, $this->token);
@@ -72,7 +72,7 @@ class SimplePreAuthenticationListenerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->equalTo($this->token))
->will($this->throwException($exception))
->willThrowException($exception)
;
$this->tokenStorage->expects($this->once())
@@ -85,7 +85,7 @@ class SimplePreAuthenticationListenerTest extends TestCase
->expects($this->once())
->method('createToken')
->with($this->equalTo($this->request), $this->equalTo('secured_area'))
->will($this->returnValue($this->token))
->willReturn($this->token)
;
$listener = new SimplePreAuthenticationListener($this->tokenStorage, $this->authenticationManager, 'secured_area', $simpleAuthenticator, $this->logger, $this->dispatcher);
@@ -102,13 +102,13 @@ class SimplePreAuthenticationListenerTest extends TestCase
$this->dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$this->request = new Request(array(), array(), array(), array(), array(), array());
$this->request = new Request([], [], [], [], [], []);
$this->event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$this->event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($this->request))
->willReturn($this->request)
;
$this->logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
@@ -47,12 +47,10 @@ class SwitchUserListenerTest extends TestCase
$this->event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $this->request, HttpKernelInterface::MASTER_REQUEST);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage $providerKey must not be empty
*/
public function testProviderKeyIsRequired()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('$providerKey must not be empty');
new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, '', $this->accessDecisionManager);
}
@@ -65,26 +63,22 @@ class SwitchUserListenerTest extends TestCase
$this->assertNull($this->tokenStorage->getToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testExitUserThrowsAuthenticationExceptionIfNoCurrentToken()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException');
$this->tokenStorage->setToken(null);
$this->request->query->set('_switch_user', '_exit');
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testExitUserThrowsAuthenticationExceptionIfOriginalTokenCannotBeFound()
{
$token = new UsernamePasswordToken('username', '', 'key', array('ROLE_FOO'));
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException');
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', '_exit');
$this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
@@ -92,15 +86,15 @@ class SwitchUserListenerTest extends TestCase
public function testExitUserUpdatesToken()
{
$originalToken = new UsernamePasswordToken('username', '', 'key', array());
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', array(new SwitchUserRole('ROLE_PREVIOUS', $originalToken))));
$originalToken = new UsernamePasswordToken('username', '', 'key', []);
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', [new SwitchUserRole('ROLE_PREVIOUS', $originalToken)]));
$this->request->query->set('_switch_user', '_exit');
$this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
$this->assertSame(array(), $this->request->query->all());
$this->assertSame([], $this->request->query->all());
$this->assertSame('', $this->request->server->get('QUERY_STRING'));
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $this->event->getResponse());
$this->assertSame($this->request->getUri(), $this->event->getResponse()->getTargetUrl());
@@ -118,8 +112,8 @@ class SwitchUserListenerTest extends TestCase
->with($originalUser)
->willReturn($refreshedUser);
$originalToken = new UsernamePasswordToken($originalUser, '', 'key');
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', array(new SwitchUserRole('ROLE_PREVIOUS', $originalToken))));
$this->request->query->set('_switch_user', '_exit');
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', [new SwitchUserRole('ROLE_PREVIOUS', $originalToken)]));
$this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher
@@ -142,8 +136,8 @@ class SwitchUserListenerTest extends TestCase
->expects($this->never())
->method('refreshUser');
$originalToken = new UsernamePasswordToken($originalUser, '', 'key');
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', array(new SwitchUserRole('ROLE_PREVIOUS', $originalToken))));
$this->request->query->set('_switch_user', '_exit');
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', [new SwitchUserRole('ROLE_PREVIOUS', $originalToken)]));
$this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher
@@ -155,19 +149,17 @@ class SwitchUserListenerTest extends TestCase
$listener->handle($this->event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
*/
public function testSwitchUserIsDisallowed()
{
$token = new UsernamePasswordToken('username', '', 'key', array('ROLE_FOO'));
$this->expectException('Symfony\Component\Security\Core\Exception\AccessDeniedException');
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', 'kuba');
$this->accessDecisionManager->expects($this->once())
->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
->will($this->returnValue(false));
->method('decide')->with($token, ['ROLE_ALLOWED_TO_SWITCH'])
->willReturn(false);
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
@@ -175,49 +167,105 @@ class SwitchUserListenerTest extends TestCase
public function testSwitchUser()
{
$token = new UsernamePasswordToken('username', '', 'key', array('ROLE_FOO'));
$user = new User('username', 'password', array());
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$user = new User('username', 'password', []);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', 'kuba');
$this->accessDecisionManager->expects($this->once())
->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
->will($this->returnValue(true));
->method('decide')->with($token, ['ROLE_ALLOWED_TO_SWITCH'])
->willReturn(true);
$this->userProvider->expects($this->once())
->method('loadUserByUsername')->with('kuba')
->will($this->returnValue($user));
->willReturn($user);
$this->userChecker->expects($this->once())
->method('checkPostAuth')->with($user);
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
$this->assertSame(array(), $this->request->query->all());
$this->assertSame([], $this->request->query->all());
$this->assertSame('', $this->request->server->get('QUERY_STRING'));
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $this->tokenStorage->getToken());
}
public function testSwitchUserAlreadySwitched()
{
$originalToken = new UsernamePasswordToken('original', null, 'key', ['ROLE_FOO']);
$alreadySwitchedToken = new UsernamePasswordToken('switched_1', null, 'key', [new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $originalToken)]);
$tokenStorage = new TokenStorage();
$tokenStorage->setToken($alreadySwitchedToken);
$targetUser = new User('kuba', 'password', ['ROLE_FOO', 'ROLE_BAR']);
$this->request->query->set('_switch_user', 'kuba');
$this->accessDecisionManager->expects($this->once())
->method('decide')->with($originalToken, ['ROLE_ALLOWED_TO_SWITCH'])
->willReturn(true);
$this->userProvider->expects($this->once())
->method('loadUserByUsername')
->with('kuba')
->willReturn($targetUser);
$this->userChecker->expects($this->once())
->method('checkPostAuth')->with($targetUser);
$listener = new SwitchUserListener($tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager, null, '_switch_user', 'ROLE_ALLOWED_TO_SWITCH', null, false);
$listener->handle($this->event);
$this->assertSame([], $this->request->query->all());
$this->assertSame('', $this->request->server->get('QUERY_STRING'));
$this->assertSame('kuba', $tokenStorage->getToken()->getUsername());
$this->assertSame($originalToken, $tokenStorage->getToken()->getRoles()[2]->getSource());
}
public function testSwitchUserWorksWithFalsyUsernames()
{
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$user = new User('username', 'password', []);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', '0');
$this->accessDecisionManager->expects($this->once())
->method('decide')->with($token, ['ROLE_ALLOWED_TO_SWITCH'])
->willReturn(true);
$this->userProvider->expects($this->once())
->method('loadUserByUsername')->with('0')
->willReturn($user);
$this->userChecker->expects($this->once())
->method('checkPostAuth')->with($user);
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
$this->assertSame([], $this->request->query->all());
$this->assertSame('', $this->request->server->get('QUERY_STRING'));
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $this->tokenStorage->getToken());
}
public function testSwitchUserKeepsOtherQueryStringParameters()
{
$token = new UsernamePasswordToken('username', '', 'key', array('ROLE_FOO'));
$user = new User('username', 'password', array());
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$user = new User('username', 'password', []);
$this->tokenStorage->setToken($token);
$this->request->query->replace(array(
$this->request->query->replace([
'_switch_user' => 'kuba',
'page' => 3,
'section' => 2,
));
]);
$this->accessDecisionManager->expects($this->once())
->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
->will($this->returnValue(true));
->method('decide')->with($token, ['ROLE_ALLOWED_TO_SWITCH'])
->willReturn(true);
$this->userProvider->expects($this->once())
->method('loadUserByUsername')->with('kuba')
->will($this->returnValue($user));
->willReturn($user);
$this->userChecker->expects($this->once())
->method('checkPostAuth')->with($user);
@@ -227,4 +275,77 @@ class SwitchUserListenerTest extends TestCase
$this->assertSame('page=3&section=2', $this->request->server->get('QUERY_STRING'));
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $this->tokenStorage->getToken());
}
public function testSwitchUserWithReplacedToken()
{
$user = new User('username', 'password', []);
$token = new UsernamePasswordToken($user, '', 'provider123', ['ROLE_FOO']);
$user = new User('replaced', 'password', []);
$replacedToken = new UsernamePasswordToken($user, '', 'provider123', ['ROLE_BAR']);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', 'kuba');
$this->accessDecisionManager->expects($this->any())
->method('decide')->with($token, ['ROLE_ALLOWED_TO_SWITCH'])
->willReturn(true);
$this->userProvider->expects($this->any())
->method('loadUserByUsername')->with('kuba')
->willReturn($user);
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher
->expects($this->once())
->method('dispatch')
->with(SecurityEvents::SWITCH_USER,
$this->callback(function (SwitchUserEvent $event) use ($replacedToken, $user) {
if ($user !== $event->getTargetUser()) {
return false;
}
$event->setToken($replacedToken);
return true;
}));
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager, null, '_switch_user', 'ROLE_ALLOWED_TO_SWITCH', $dispatcher);
$listener->handle($this->event);
$this->assertSame($replacedToken, $this->tokenStorage->getToken());
}
public function testSwitchUserThrowsAuthenticationExceptionIfNoCurrentToken()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException');
$this->tokenStorage->setToken(null);
$this->request->query->set('_switch_user', 'username');
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
}
public function testSwitchUserStateless()
{
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$user = new User('username', 'password', []);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', 'kuba');
$this->accessDecisionManager->expects($this->once())
->method('decide')->with($token, ['ROLE_ALLOWED_TO_SWITCH'])
->willReturn(true);
$this->userProvider->expects($this->once())
->method('loadUserByUsername')->with('kuba')
->willReturn($user);
$this->userChecker->expects($this->once())
->method('checkPostAuth')->with($user);
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager, null, '_switch_user', 'ROLE_ALLOWED_TO_SWITCH', null, true);
$listener->handle($this->event);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $this->tokenStorage->getToken());
$this->assertFalse($this->event->hasResponse());
}
}
@@ -9,13 +9,21 @@
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Tests\Http\Firewall;
namespace Symfony\Component\Security\Http\Tests\Firewall;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy;
class UsernamePasswordFormAuthenticationListenerTest extends TestCase
{
@@ -24,28 +32,32 @@ class UsernamePasswordFormAuthenticationListenerTest extends TestCase
*/
public function testHandleWhenUsernameLength($username, $ok)
{
$request = Request::create('/login_check', 'POST', array('_username' => $username));
$request = Request::create('/login_check', 'POST', ['_username' => $username]);
$request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock());
$httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
$httpUtils
->expects($this->any())
->method('checkRequestPath')
->will($this->returnValue(true))
->willReturn(true)
;
$httpUtils
->method('createRedirectResponse')
->willReturn(new RedirectResponse('/hello'))
;
$failureHandler = $this->getMockBuilder('Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface')->getMock();
$failureHandler
->expects($ok ? $this->never() : $this->once())
->method('onAuthenticationFailure')
->will($this->returnValue(new Response()))
->willReturn(new Response())
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager')->disableOriginalConstructor()->getMock();
$authenticationManager
->expects($ok ? $this->once() : $this->never())
->method('authenticate')
->will($this->returnValue(new Response()))
->willReturnArgument(0)
;
$listener = new UsernamePasswordFormAuthenticationListener(
@@ -54,26 +66,138 @@ class UsernamePasswordFormAuthenticationListenerTest extends TestCase
$this->getMockBuilder('Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface')->getMock(),
$httpUtils,
'TheProviderKey',
$this->getMockBuilder('Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface')->getMock(),
new DefaultAuthenticationSuccessHandler($httpUtils),
$failureHandler,
array('require_previous_session' => false)
['require_previous_session' => false]
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
->willReturn($request)
;
$listener->handle($event);
}
/**
* @dataProvider postOnlyDataProvider
*/
public function testHandleNonStringUsernameWithArray($postOnly)
{
$this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException');
$this->expectExceptionMessage('The key "_username" must be a string, "array" given.');
$request = Request::create('/login_check', 'POST', ['_username' => []]);
$request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock());
$listener = new UsernamePasswordFormAuthenticationListener(
new TokenStorage(),
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE),
$httpUtils = new HttpUtils(),
'foo',
new DefaultAuthenticationSuccessHandler($httpUtils),
new DefaultAuthenticationFailureHandler($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $httpUtils),
['require_previous_session' => false, 'post_only' => $postOnly]
);
$event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST);
$listener->handle($event);
}
/**
* @dataProvider postOnlyDataProvider
*/
public function testHandleNonStringUsernameWithInt($postOnly)
{
$this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException');
$this->expectExceptionMessage('The key "_username" must be a string, "integer" given.');
$request = Request::create('/login_check', 'POST', ['_username' => 42]);
$request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock());
$listener = new UsernamePasswordFormAuthenticationListener(
new TokenStorage(),
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE),
$httpUtils = new HttpUtils(),
'foo',
new DefaultAuthenticationSuccessHandler($httpUtils),
new DefaultAuthenticationFailureHandler($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $httpUtils),
['require_previous_session' => false, 'post_only' => $postOnly]
);
$event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST);
$listener->handle($event);
}
/**
* @dataProvider postOnlyDataProvider
*/
public function testHandleNonStringUsernameWithObject($postOnly)
{
$this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException');
$this->expectExceptionMessage('The key "_username" must be a string, "object" given.');
$request = Request::create('/login_check', 'POST', ['_username' => new \stdClass()]);
$request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock());
$listener = new UsernamePasswordFormAuthenticationListener(
new TokenStorage(),
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE),
$httpUtils = new HttpUtils(),
'foo',
new DefaultAuthenticationSuccessHandler($httpUtils),
new DefaultAuthenticationFailureHandler($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $httpUtils),
['require_previous_session' => false, 'post_only' => $postOnly]
);
$event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST);
$listener->handle($event);
}
/**
* @dataProvider postOnlyDataProvider
*/
public function testHandleNonStringUsernameWith__toString($postOnly)
{
$usernameClass = $this->getMockBuilder(DummyUserClass::class)->getMock();
$usernameClass
->expects($this->atLeastOnce())
->method('__toString')
->willReturn('someUsername');
$request = Request::create('/login_check', 'POST', ['_username' => $usernameClass]);
$request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock());
$listener = new UsernamePasswordFormAuthenticationListener(
new TokenStorage(),
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE),
$httpUtils = new HttpUtils(),
'foo',
new DefaultAuthenticationSuccessHandler($httpUtils),
new DefaultAuthenticationFailureHandler($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $httpUtils),
['require_previous_session' => false, 'post_only' => $postOnly]
);
$event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST);
$listener->handle($event);
}
public function postOnlyDataProvider()
{
return [
[true],
[false],
];
}
public function getUsernameForLength()
{
return array(
array(str_repeat('x', Security::MAX_USERNAME_LENGTH + 1), false),
array(str_repeat('x', Security::MAX_USERNAME_LENGTH - 1), true),
);
return [
[str_repeat('x', Security::MAX_USERNAME_LENGTH + 1), false],
[str_repeat('x', Security::MAX_USERNAME_LENGTH - 1), true],
];
}
}
class DummyUserClass
{
public function __toString()
{
return '';
}
}
@@ -22,7 +22,7 @@ class X509AuthenticationListenerTest extends TestCase
*/
public function testGetPreAuthenticatedData($user, $credentials)
{
$serverVars = array();
$serverVars = [];
if ('' !== $user) {
$serverVars['SSL_CLIENT_S_DN_Email'] = $user;
}
@@ -30,7 +30,7 @@ class X509AuthenticationListenerTest extends TestCase
$serverVars['SSL_CLIENT_S_DN'] = $credentials;
}
$request = new Request(array(), array(), array(), array(), array(), $serverVars);
$request = new Request([], [], [], [], [], $serverVars);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
@@ -41,25 +41,24 @@ class X509AuthenticationListenerTest extends TestCase
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$this->assertSame($result, array($user, $credentials));
$result = $method->invokeArgs($listener, [$request]);
$this->assertSame($result, [$user, $credentials]);
}
public static function dataProviderGetPreAuthenticatedData()
{
return array(
'validValues' => array('TheUser', 'TheCredentials'),
'noCredentials' => array('TheUser', ''),
);
return [
'validValues' => ['TheUser', 'TheCredentials'],
'noCredentials' => ['TheUser', ''],
];
}
/**
* @dataProvider dataProviderGetPreAuthenticatedDataNoUser
*/
public function testGetPreAuthenticatedDataNoUser($emailAddress)
public function testGetPreAuthenticatedDataNoUser($emailAddress, $credentials)
{
$credentials = 'CN=Sample certificate DN/emailAddress='.$emailAddress;
$request = new Request(array(), array(), array(), array(), array(), array('SSL_CLIENT_S_DN' => $credentials));
$request = new Request([], [], [], [], [], ['SSL_CLIENT_S_DN' => $credentials]);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
@@ -70,24 +69,25 @@ class X509AuthenticationListenerTest extends TestCase
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$this->assertSame($result, array($emailAddress, $credentials));
$result = $method->invokeArgs($listener, [$request]);
$this->assertSame($result, [$emailAddress, $credentials]);
}
public static function dataProviderGetPreAuthenticatedDataNoUser()
{
return array(
'basicEmailAddress' => array('cert@example.com'),
'emailAddressWithPlusSign' => array('cert+something@example.com'),
);
yield ['cert@example.com', 'CN=Sample certificate DN/emailAddress=cert@example.com'];
yield ['cert+something@example.com', 'CN=Sample certificate DN/emailAddress=cert+something@example.com'];
yield ['cert@example.com', 'CN=Sample certificate DN,emailAddress=cert@example.com'];
yield ['cert+something@example.com', 'CN=Sample certificate DN,emailAddress=cert+something@example.com'];
yield ['cert+something@example.com', 'emailAddress=cert+something@example.com,CN=Sample certificate DN'];
yield ['cert+something@example.com', 'emailAddress=cert+something@example.com'];
yield ['firstname.lastname@mycompany.co.uk', 'emailAddress=firstname.lastname@mycompany.co.uk,CN=Firstname.Lastname,OU=london,OU=company design and engineering,OU=Issuer London,OU=Roaming,OU=Interactive,OU=Users,OU=Standard,OU=Business,DC=england,DC=core,DC=company,DC=co,DC=uk'];
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testGetPreAuthenticatedDataNoData()
{
$request = new Request(array(), array(), array(), array(), array(), array());
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$request = new Request([], [], [], [], [], []);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
@@ -98,17 +98,17 @@ class X509AuthenticationListenerTest extends TestCase
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$method->invokeArgs($listener, [$request]);
}
public function testGetPreAuthenticatedDataWithDifferentKeys()
{
$userCredentials = array('TheUser', 'TheCredentials');
$userCredentials = ['TheUser', 'TheCredentials'];
$request = new Request(array(), array(), array(), array(), array(), array(
$request = new Request([], [], [], [], [], [
'TheUserKey' => 'TheUser',
'TheCredentialsKey' => 'TheCredentials',
));
]);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
@@ -118,7 +118,7 @@ class X509AuthenticationListenerTest extends TestCase
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$result = $method->invokeArgs($listener, [$request]);
$this->assertSame($result, $userCredentials);
}
}
+15 -15
View File
@@ -12,8 +12,8 @@
namespace Symfony\Component\Security\Http\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\FirewallMap;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\FirewallMap;
class FirewallMapTest extends TestCase
{
@@ -28,22 +28,22 @@ class FirewallMapTest extends TestCase
->expects($this->once())
->method('matches')
->with($this->equalTo($request))
->will($this->returnValue(false))
->willReturn(false)
;
$map->add($notMatchingMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
$map->add($notMatchingMatcher, [$this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()]);
$matchingMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcher')->getMock();
$matchingMatcher
->expects($this->once())
->method('matches')
->with($this->equalTo($request))
->will($this->returnValue(true))
->willReturn(true)
;
$theListener = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock();
$theException = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ExceptionListener')->disableOriginalConstructor()->getMock();
$map->add($matchingMatcher, array($theListener), $theException);
$map->add($matchingMatcher, [$theListener], $theException);
$tooLateMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcher')->getMock();
$tooLateMatcher
@@ -51,11 +51,11 @@ class FirewallMapTest extends TestCase
->method('matches')
;
$map->add($tooLateMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
$map->add($tooLateMatcher, [$this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()]);
list($listeners, $exception) = $map->getListeners($request);
$this->assertEquals(array($theListener), $listeners);
$this->assertEquals([$theListener], $listeners);
$this->assertEquals($theException, $exception);
}
@@ -70,15 +70,15 @@ class FirewallMapTest extends TestCase
->expects($this->once())
->method('matches')
->with($this->equalTo($request))
->will($this->returnValue(false))
->willReturn(false)
;
$map->add($notMatchingMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
$map->add($notMatchingMatcher, [$this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()]);
$theListener = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock();
$theException = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ExceptionListener')->disableOriginalConstructor()->getMock();
$map->add(null, array($theListener), $theException);
$map->add(null, [$theListener], $theException);
$tooLateMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcher')->getMock();
$tooLateMatcher
@@ -86,11 +86,11 @@ class FirewallMapTest extends TestCase
->method('matches')
;
$map->add($tooLateMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
$map->add($tooLateMatcher, [$this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()]);
list($listeners, $exception) = $map->getListeners($request);
$this->assertEquals(array($theListener), $listeners);
$this->assertEquals([$theListener], $listeners);
$this->assertEquals($theException, $exception);
}
@@ -105,14 +105,14 @@ class FirewallMapTest extends TestCase
->expects($this->once())
->method('matches')
->with($this->equalTo($request))
->will($this->returnValue(false))
->willReturn(false)
;
$map->add($notMatchingMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
$map->add($notMatchingMatcher, [$this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()]);
list($listeners, $exception) = $map->getListeners($request);
$this->assertEquals(array(), $listeners);
$this->assertEquals([], $listeners);
$this->assertNull($exception);
}
}
+6 -9
View File
@@ -12,7 +12,6 @@
namespace Symfony\Component\Security\Http\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Http\Firewall;
@@ -37,7 +36,7 @@ class FirewallTest extends TestCase
->expects($this->once())
->method('getListeners')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), $listener)))
->willReturn([[], $listener])
;
$event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST);
@@ -48,8 +47,6 @@ class FirewallTest extends TestCase
public function testOnKernelRequestStopsWhenThereIsAResponse()
{
$response = new Response();
$first = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock();
$first
->expects($this->once())
@@ -66,22 +63,22 @@ class FirewallTest extends TestCase
$map
->expects($this->once())
->method('getListeners')
->will($this->returnValue(array(array($first, $second), null)))
->willReturn([[$first, $second], null])
;
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
->setMethods(array('hasResponse'))
->setConstructorArgs(array(
->setMethods(['hasResponse'])
->setConstructorArgs([
$this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(),
$this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock(),
HttpKernelInterface::MASTER_REQUEST,
))
])
->getMock()
;
$event
->expects($this->once())
->method('hasResponse')
->will($this->returnValue(true))
->willReturn(true)
;
$firewall = new Firewall($map, $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock());
+48 -31
View File
@@ -15,8 +15,8 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\HttpUtils;
class HttpUtilsTest extends TestCase
@@ -54,14 +54,28 @@ class HttpUtilsTest extends TestCase
$this->assertTrue($response->isRedirect('http://localhost/blog'));
}
public function testCreateRedirectResponseWithBadRequestsDomain()
/**
* @dataProvider badRequestDomainUrls
*/
public function testCreateRedirectResponseWithBadRequestsDomain($url)
{
$utils = new HttpUtils($this->getUrlGenerator(), null, '#^https?://%s$#i');
$response = $utils->createRedirectResponse($this->getRequest(), 'http://pirate.net/foo');
$response = $utils->createRedirectResponse($this->getRequest(), $url);
$this->assertTrue($response->isRedirect('http://localhost/'));
}
public function badRequestDomainUrls()
{
return [
['http://pirate.net/foo'],
['http:\\\\pirate.net/foo'],
['http:/\\pirate.net/foo'],
['http:\\/pirate.net/foo'],
['http://////pirate.net/foo'],
];
}
public function testCreateRedirectResponseWithProtocolRelativeTarget()
{
$utils = new HttpUtils($this->getUrlGenerator(), null, '#^https?://%s$#i');
@@ -77,13 +91,13 @@ class HttpUtilsTest extends TestCase
$urlGenerator
->expects($this->any())
->method('generate')
->with('foobar', array(), UrlGeneratorInterface::ABSOLUTE_URL)
->will($this->returnValue('http://localhost/foo/bar'))
->with('foobar', [], UrlGeneratorInterface::ABSOLUTE_URL)
->willReturn('http://localhost/foo/bar')
;
$urlGenerator
->expects($this->any())
->method('getContext')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock())
;
$response = $utils->createRedirectResponse($this->getRequest(), 'foobar');
@@ -111,12 +125,12 @@ class HttpUtilsTest extends TestCase
$urlGenerator
->expects($this->once())
->method('generate')
->will($this->returnValue('/foo/bar'))
->willReturn('/foo/bar')
;
$urlGenerator
->expects($this->any())
->method('getContext')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock())
;
$subRequest = $utils->createRequest($this->getRequest(), 'foobar');
@@ -159,11 +173,11 @@ class HttpUtilsTest extends TestCase
public function provideSecurityContextAttributes()
{
return array(
array(Security::AUTHENTICATION_ERROR),
array(Security::ACCESS_DENIED_ERROR),
array(Security::LAST_USERNAME),
);
return [
[Security::AUTHENTICATION_ERROR],
[Security::ACCESS_DENIED_ERROR],
[Security::LAST_USERNAME],
];
}
public function testCheckRequestPath()
@@ -186,7 +200,7 @@ class HttpUtilsTest extends TestCase
->expects($this->any())
->method('match')
->with('/')
->will($this->throwException(new ResourceNotFoundException()))
->willThrowException(new ResourceNotFoundException())
;
$utils = new HttpUtils(null, $urlMatcher);
@@ -201,7 +215,7 @@ class HttpUtilsTest extends TestCase
->expects($this->any())
->method('matchRequest')
->with($request)
->will($this->throwException(new MethodNotAllowedException(array())))
->willThrowException(new MethodNotAllowedException([]))
;
$utils = new HttpUtils(null, $urlMatcher);
@@ -215,7 +229,7 @@ class HttpUtilsTest extends TestCase
->expects($this->any())
->method('match')
->with('/foo/bar')
->will($this->returnValue(array('_route' => 'foobar')))
->willReturn(['_route' => 'foobar'])
;
$utils = new HttpUtils(null, $urlMatcher);
@@ -230,23 +244,21 @@ class HttpUtilsTest extends TestCase
->expects($this->any())
->method('matchRequest')
->with($request)
->will($this->returnValue(array('_route' => 'foobar')))
->willReturn(['_route' => 'foobar'])
;
$utils = new HttpUtils(null, $urlMatcher);
$this->assertTrue($utils->checkRequestPath($request, 'foobar'));
}
/**
* @expectedException \RuntimeException
*/
public function testCheckRequestPathWithUrlMatcherLoadingException()
{
$this->expectException('RuntimeException');
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')->getMock();
$urlMatcher
->expects($this->any())
->method('match')
->will($this->throwException(new \RuntimeException()))
->willThrowException(new \RuntimeException())
;
$utils = new HttpUtils(null, $urlMatcher);
@@ -259,19 +271,17 @@ class HttpUtilsTest extends TestCase
$urlMatcher
->expects($this->any())
->method('match')
->willReturn(array('_controller' => 'PathController'))
->willReturn(['_controller' => 'PathController'])
;
$utils = new HttpUtils(null, $urlMatcher);
$this->assertFalse($utils->checkRequestPath($this->getRequest(), 'path/index.html'));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Matcher must either implement UrlMatcherInterface or RequestMatcherInterface
*/
public function testUrlMatcher()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface');
new HttpUtils($this->getUrlGenerator(), new \stdClass());
}
@@ -284,12 +294,19 @@ class HttpUtilsTest extends TestCase
$this->assertEquals('/foo/bar', $utils->generateUri(new Request(), 'route_name'));
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage You must provide a UrlGeneratorInterface instance to be able to use routes.
*/
public function testGenerateUriPreservesFragment()
{
$utils = new HttpUtils($this->getUrlGenerator('/foo/bar?param=value#fragment'));
$this->assertEquals('/foo/bar#fragment', $utils->generateUri(new Request(), 'route_name'));
$utils = new HttpUtils($this->getUrlGenerator('/foo/bar#fragment'));
$this->assertEquals('/foo/bar#fragment', $utils->generateUri(new Request(), 'route_name'));
}
public function testUrlGeneratorIsRequiredToGenerateUrl()
{
$this->expectException('LogicException');
$this->expectExceptionMessage('You must provide a UrlGeneratorInterface instance to be able to use routes.');
$utils = new HttpUtils();
$utils->generateUri(new Request(), 'route_name');
}
@@ -300,7 +317,7 @@ class HttpUtilsTest extends TestCase
$urlGenerator
->expects($this->any())
->method('generate')
->will($this->returnValue($generatedUrl))
->willReturn($generatedUrl)
;
return $urlGenerator;
@@ -12,9 +12,10 @@
namespace Symfony\Component\Security\Http\Tests\Logout;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Logout\CookieClearingLogoutHandler;
class CookieClearingLogoutHandlerTest extends TestCase
@@ -25,7 +26,7 @@ class CookieClearingLogoutHandlerTest extends TestCase
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$handler = new CookieClearingLogoutHandler(array('foo' => array('path' => '/foo', 'domain' => 'foo.foo'), 'foo2' => array('path' => null, 'domain' => null)));
$handler = new CookieClearingLogoutHandler(['foo' => ['path' => '/foo', 'domain' => 'foo.foo', 'secure' => true, 'samesite' => Cookie::SAMESITE_STRICT], 'foo2' => ['path' => null, 'domain' => null]]);
$cookies = $response->headers->getCookies();
$this->assertCount(0, $cookies);
@@ -39,12 +40,16 @@ class CookieClearingLogoutHandlerTest extends TestCase
$this->assertEquals('foo', $cookie->getName());
$this->assertEquals('/foo', $cookie->getPath());
$this->assertEquals('foo.foo', $cookie->getDomain());
$this->assertEquals(Cookie::SAMESITE_STRICT, $cookie->getSameSite());
$this->assertTrue($cookie->isSecure());
$this->assertTrue($cookie->isCleared());
$cookie = $cookies['']['/']['foo2'];
$this->assertStringStartsWith('foo2', $cookie->getName());
$this->assertEquals('/', $cookie->getPath());
$this->assertNull($cookie->getDomain());
$this->assertNull($cookie->getSameSite());
$this->assertFalse($cookie->isSecure());
$this->assertTrue($cookie->isCleared());
}
}
@@ -12,7 +12,7 @@
namespace Symfony\Component\Security\Http\Tests\Logout;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Logout\DefaultLogoutSuccessHandler;
class DefaultLogoutSuccessHandlerTest extends TestCase
@@ -20,13 +20,13 @@ class DefaultLogoutSuccessHandlerTest extends TestCase
public function testLogout()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$response = new Response();
$response = new RedirectResponse('/dashboard');
$httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
$httpUtils->expects($this->once())
->method('createRedirectResponse')
->with($request, '/dashboard')
->will($this->returnValue($response));
->willReturn($response);
$handler = new DefaultLogoutSuccessHandler($httpUtils, '/dashboard');
$result = $handler->onLogoutSuccess($request);
@@ -28,7 +28,7 @@ class SessionLogoutHandlerTest extends TestCase
$request
->expects($this->once())
->method('getSession')
->will($this->returnValue($session))
->willReturn($session)
;
$session
@@ -12,16 +12,16 @@
namespace Symfony\Component\Security\Http\Tests\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\RememberMe\AbstractRememberMeServices;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
class AbstractRememberMeServicesTest extends TestCase
{
public function testGetRememberMeParameter()
{
$service = $this->getService(null, array('remember_me_parameter' => 'foo'));
$service = $this->getService(null, ['remember_me_parameter' => 'foo']);
$this->assertEquals('foo', $service->getRememberMeParameter());
}
@@ -34,24 +34,36 @@ class AbstractRememberMeServicesTest extends TestCase
public function testAutoLoginReturnsNullWhenNoCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]);
$this->assertNull($service->autoLogin(new Request()));
}
public function testAutoLoginReturnsNullAfterLoginFail()
{
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]);
$request = new Request();
$request->cookies->set('foo', 'foo');
$service->loginFail($request);
$this->assertNull($service->autoLogin($request));
}
/**
* @expectedException \RuntimeException
* @group legacy
*/
public function testAutoLoginThrowsExceptionWhenImplementationDoesNotReturnUserInterface()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$this->expectException('RuntimeException');
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]);
$request = new Request();
$request->cookies->set('foo', 'foo');
$service
->expects($this->once())
->method('processAutoLoginCookie')
->will($this->returnValue(null))
->willReturn(null)
;
$service->autoLogin($request);
@@ -59,7 +71,7 @@ class AbstractRememberMeServicesTest extends TestCase
public function testAutoLogin()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]);
$request = new Request();
$request->cookies->set('foo', 'foo');
@@ -67,13 +79,13 @@ class AbstractRememberMeServicesTest extends TestCase
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array()))
->willReturn([])
;
$service
->expects($this->once())
->method('processAutoLoginCookie')
->will($this->returnValue($user))
->willReturn($user)
;
$returnedToken = $service->autoLogin($request);
@@ -105,15 +117,15 @@ class AbstractRememberMeServicesTest extends TestCase
public function provideOptionsForLogout()
{
return array(
array(array('name' => 'foo', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => true)),
array(array('name' => 'foo', 'path' => '/bar', 'domain' => 'baz.com', 'secure' => true, 'httponly' => false)),
);
return [
[['name' => 'foo', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => true]],
[['name' => 'foo', 'path' => '/bar', 'domain' => 'baz.com', 'secure' => true, 'httponly' => false]],
];
}
public function testLoginFail()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]);
$request = new Request();
$service->loginFail($request);
@@ -123,15 +135,14 @@ class AbstractRememberMeServicesTest extends TestCase
public function testLoginSuccessIsNotProcessedWhenTokenDoesNotContainUserInterfaceImplementation()
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null]);
$request = new Request();
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$service
@@ -146,7 +157,7 @@ class AbstractRememberMeServicesTest extends TestCase
public function testLoginSuccessIsNotProcessedWhenRememberMeIsNotRequested()
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo', 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo', 'path' => null, 'domain' => null]);
$request = new Request();
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
@@ -154,13 +165,13 @@ class AbstractRememberMeServicesTest extends TestCase
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue($account))
->willReturn($account)
;
$service
->expects($this->never())
->method('onLoginSuccess')
->will($this->returnValue(null))
->willReturn(null)
;
$this->assertFalse($request->request->has('foo'));
@@ -170,7 +181,7 @@ class AbstractRememberMeServicesTest extends TestCase
public function testLoginSuccessWhenRememberMeAlwaysIsTrue()
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null]);
$request = new Request();
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
@@ -178,13 +189,13 @@ class AbstractRememberMeServicesTest extends TestCase
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue($account))
->willReturn($account)
;
$service
->expects($this->once())
->method('onLoginSuccess')
->will($this->returnValue(null))
->willReturn(null)
;
$service->loginSuccess($request, $response, $token);
@@ -195,23 +206,23 @@ class AbstractRememberMeServicesTest extends TestCase
*/
public function testLoginSuccessWhenRememberMeParameterWithPathIsPositive($value)
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo[bar]', 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo[bar]', 'path' => null, 'domain' => null]);
$request = new Request();
$request->request->set('foo', array('bar' => $value));
$request->request->set('foo', ['bar' => $value]);
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue($account))
->willReturn($account)
;
$service
->expects($this->once())
->method('onLoginSuccess')
->will($this->returnValue(true))
->willReturn(true)
;
$service->loginSuccess($request, $response, $token);
@@ -222,7 +233,7 @@ class AbstractRememberMeServicesTest extends TestCase
*/
public function testLoginSuccessWhenRememberMeParameterIsPositive($value)
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo', 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo', 'path' => null, 'domain' => null]);
$request = new Request();
$request->request->set('foo', $value);
@@ -232,13 +243,13 @@ class AbstractRememberMeServicesTest extends TestCase
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue($account))
->willReturn($account)
;
$service
->expects($this->once())
->method('onLoginSuccess')
->will($this->returnValue(true))
->willReturn(true)
;
$service->loginSuccess($request, $response, $token);
@@ -246,48 +257,46 @@ class AbstractRememberMeServicesTest extends TestCase
public function getPositiveRememberMeParameterValues()
{
return array(
array('true'),
array('1'),
array('on'),
array('yes'),
array(true),
);
return [
['true'],
['1'],
['on'],
['yes'],
[true],
];
}
public function testEncodeCookieAndDecodeCookieAreInvertible()
{
$cookieParts = array('aa', 'bb', 'cc');
$cookieParts = ['aa', 'bb', 'cc'];
$service = $this->getService();
$encoded = $this->callProtected($service, 'encodeCookie', array($cookieParts));
$this->assertInternalType('string', $encoded);
$encoded = $this->callProtected($service, 'encodeCookie', [$cookieParts]);
$this->assertIsString($encoded);
$decoded = $this->callProtected($service, 'decodeCookie', array($encoded));
$decoded = $this->callProtected($service, 'decodeCookie', [$encoded]);
$this->assertSame($cookieParts, $decoded);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage cookie delimiter
*/
public function testThereShouldBeNoCookieDelimiterInCookieParts()
{
$cookieParts = array('aa', 'b'.AbstractRememberMeServices::COOKIE_DELIMITER.'b', 'cc');
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('cookie delimiter');
$cookieParts = ['aa', 'b'.AbstractRememberMeServices::COOKIE_DELIMITER.'b', 'cc'];
$service = $this->getService();
$this->callProtected($service, 'encodeCookie', array($cookieParts));
$this->callProtected($service, 'encodeCookie', [$cookieParts]);
}
protected function getService($userProvider = null, $options = array(), $logger = null)
protected function getService($userProvider = null, $options = [], $logger = null)
{
if (null === $userProvider) {
$userProvider = $this->getProvider();
}
return $this->getMockForAbstractClass('Symfony\Component\Security\Http\RememberMe\AbstractRememberMeServices', array(
array($userProvider), 'foosecret', 'fookey', $options, $logger,
));
return $this->getMockForAbstractClass('Symfony\Component\Security\Http\RememberMe\AbstractRememberMeServices', [
[$userProvider], 'foosecret', 'fookey', $options, $logger,
]);
}
protected function getProvider()
@@ -296,7 +305,7 @@ class AbstractRememberMeServicesTest extends TestCase
$provider
->expects($this->any())
->method('supportsClass')
->will($this->returnValue(true))
->willReturn(true)
;
return $provider;
@@ -304,7 +313,7 @@ class AbstractRememberMeServicesTest extends TestCase
private function callProtected($object, $method, array $args)
{
$reflection = new \ReflectionClass(get_class($object));
$reflection = new \ReflectionClass(\get_class($object));
$reflectionMethod = $reflection->getMethod($method);
$reflectionMethod->setAccessible(true);
@@ -12,15 +12,16 @@
namespace Symfony\Component\Security\Http\Tests\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\Security\Core\Exception\CookieTheftException;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
class PersistentTokenBasedRememberMeServicesTest extends TestCase
{
@@ -35,14 +36,14 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testAutoLoginReturnsNullWhenNoCookie()
{
$service = $this->getService(null, array('name' => 'foo'));
$service = $this->getService(null, ['name' => 'foo']);
$this->assertNull($service->autoLogin(new Request()));
}
public function testAutoLoginThrowsExceptionOnInvalidCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo']);
$request = new Request();
$request->request->set('foo', 'true');
$request->cookies->set('foo', 'foo');
@@ -53,19 +54,19 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testAutoLoginThrowsExceptionOnNonExistentToken()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo']);
$request = new Request();
$request->request->set('foo', 'true');
$request->cookies->set('foo', $this->encodeCookie(array(
$request->cookies->set('foo', $this->encodeCookie([
$series = 'fooseries',
$tokenValue = 'foovalue',
)));
]));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->will($this->throwException(new TokenNotFoundException('Token not found.')))
->willThrowException(new TokenNotFoundException('Token not found.'))
;
$service->setTokenProvider($tokenProvider);
@@ -76,22 +77,22 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testAutoLoginReturnsNullOnNonExistentUser()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600, 'secure' => false, 'httponly' => false));
$service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600, 'secure' => false, 'httponly' => false]);
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue']));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->will($this->returnValue(new PersistentToken('fooclass', 'fooname', 'fooseries', 'foovalue', new \DateTime())))
->willReturn(new PersistentToken('fooclass', 'fooname', 'fooseries', 'foovalue', new \DateTime()))
;
$service->setTokenProvider($tokenProvider);
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new UsernameNotFoundException('user not found')))
->willThrowException(new UsernameNotFoundException('user not found'))
;
$this->assertNull($service->autoLogin($request));
@@ -101,9 +102,9 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testAutoLoginThrowsExceptionOnStolenCookieAndRemovesItFromThePersistentBackend()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true));
$service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true]);
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue']));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$service->setTokenProvider($tokenProvider);
@@ -111,14 +112,14 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->will($this->returnValue(new PersistentToken('fooclass', 'foouser', 'fooseries', 'anotherFooValue', new \DateTime())))
->willReturn(new PersistentToken('fooclass', 'foouser', 'fooseries', 'anotherFooValue', new \DateTime()))
;
$tokenProvider
->expects($this->once())
->method('deleteTokenBySeries')
->with($this->equalTo('fooseries'))
->will($this->returnValue(null))
->willReturn(null)
;
try {
@@ -132,16 +133,16 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testAutoLoginDoesNotAcceptAnExpiredCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600]);
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue']));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->with($this->equalTo('fooseries'))
->will($this->returnValue(new PersistentToken('fooclass', 'username', 'fooseries', 'foovalue', new \DateTime('yesterday'))))
->willReturn(new PersistentToken('fooclass', 'username', 'fooseries', 'foovalue', new \DateTime('yesterday')))
;
$service->setTokenProvider($tokenProvider);
@@ -155,7 +156,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
->willReturn(['ROLE_FOO'])
;
$userProvider = $this->getProvider();
@@ -163,19 +164,19 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foouser'))
->will($this->returnValue($user))
->willReturn($user)
;
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'secure' => false, 'httponly' => false, 'always_remember_me' => true, 'lifetime' => 3600));
$service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'secure' => false, 'httponly' => false, 'always_remember_me' => true, 'lifetime' => 3600]);
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue']));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->with($this->equalTo('fooseries'))
->will($this->returnValue(new PersistentToken('fooclass', 'foouser', 'fooseries', 'foovalue', new \DateTime())))
->willReturn(new PersistentToken('fooclass', 'foouser', 'fooseries', 'foovalue', new \DateTime()))
;
$service->setTokenProvider($tokenProvider);
@@ -189,9 +190,9 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testLogout()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo', 'secure' => true, 'httponly' => false));
$service = $this->getService(null, ['name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo', 'secure' => true, 'httponly' => false]);
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue']));
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
@@ -200,7 +201,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
->expects($this->once())
->method('deleteTokenBySeries')
->with($this->equalTo('fooseries'))
->will($this->returnValue(null))
->willReturn(null)
;
$service->setTokenProvider($tokenProvider);
@@ -216,7 +217,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testLogoutSimplyIgnoresNonSetRequestCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]);
$request = new Request();
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
@@ -238,7 +239,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testLogoutSimplyIgnoresInvalidCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]);
$request = new Request();
$request->cookies->set('foo', 'somefoovalue');
$response = new Response();
@@ -258,7 +259,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testLoginFail()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]);
$request = new Request();
$this->assertFalse($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
@@ -268,7 +269,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
public function testLoginSuccessSetsCookieWhenLoggedInWithNonRememberMeTokenInterfaceImplementation()
{
$service = $this->getService(null, array('name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'lifetime' => 3600, 'always_remember_me' => true));
$service = $this->getService(null, ['name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'samesite' => Cookie::SAMESITE_STRICT, 'lifetime' => 3600, 'always_remember_me' => true]);
$request = new Request();
$response = new Response();
@@ -276,13 +277,13 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
$account
->expects($this->once())
->method('getUsername')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->any())
->method('getUser')
->will($this->returnValue($account))
->willReturn($account)
;
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
@@ -305,6 +306,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
$this->assertTrue($cookie->getExpiresTime() > time() + 3590 && $cookie->getExpiresTime() < time() + 3610);
$this->assertEquals('myfoodomain.foo', $cookie->getDomain());
$this->assertEquals('/foo/path', $cookie->getPath());
$this->assertSame(Cookie::SAMESITE_STRICT, $cookie->getSameSite());
}
protected function encodeCookie(array $parts)
@@ -316,13 +318,13 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
return $r->invoke($service, $parts);
}
protected function getService($userProvider = null, $options = array(), $logger = null)
protected function getService($userProvider = null, $options = [], $logger = null)
{
if (null === $userProvider) {
$userProvider = $this->getProvider();
}
return new PersistentTokenBasedRememberMeServices(array($userProvider), 'foosecret', 'fookey', $options, $logger);
return new PersistentTokenBasedRememberMeServices([$userProvider], 'foosecret', 'fookey', $options, $logger);
}
protected function getProvider()
@@ -331,7 +333,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase
$provider
->expects($this->any())
->method('supportsClass')
->will($this->returnValue(true))
->willReturn(true)
;
return $provider;
@@ -12,13 +12,13 @@
namespace Symfony\Component\Security\Http\Tests\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Http\RememberMe\ResponseListener;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Http\RememberMe\ResponseListener;
class ResponseListenerTest extends TestCase
{
@@ -26,9 +26,9 @@ class ResponseListenerTest extends TestCase
{
$cookie = new Cookie('rememberme');
$request = $this->getRequest(array(
$request = $this->getRequest([
RememberMeServicesInterface::COOKIE_ATTR_NAME => $cookie,
));
]);
$response = $this->getResponse();
$response->headers->expects($this->once())->method('setCookie')->with($cookie);
@@ -41,9 +41,9 @@ class ResponseListenerTest extends TestCase
{
$cookie = new Cookie('rememberme');
$request = $this->getRequest(array(
$request = $this->getRequest([
RememberMeServicesInterface::COOKIE_ATTR_NAME => $cookie,
));
]);
$response = $this->getResponse();
$response->headers->expects($this->never())->method('setCookie');
@@ -65,12 +65,10 @@ class ResponseListenerTest extends TestCase
public function testItSubscribesToTheOnKernelResponseEvent()
{
$listener = new ResponseListener();
$this->assertSame(array(KernelEvents::RESPONSE => 'onKernelResponse'), ResponseListener::getSubscribedEvents());
$this->assertSame([KernelEvents::RESPONSE => 'onKernelResponse'], ResponseListener::getSubscribedEvents());
}
private function getRequest(array $attributes = array())
private function getRequest(array $attributes = [])
{
$request = new Request();
@@ -95,9 +93,9 @@ class ResponseListenerTest extends TestCase
->disableOriginalConstructor()
->getMock();
$event->expects($this->any())->method('getRequest')->will($this->returnValue($request));
$event->expects($this->any())->method('isMasterRequest')->will($this->returnValue($type === HttpKernelInterface::MASTER_REQUEST));
$event->expects($this->any())->method('getResponse')->will($this->returnValue($response));
$event->expects($this->any())->method('getRequest')->willReturn($request);
$event->expects($this->any())->method('isMasterRequest')->willReturn(HttpKernelInterface::MASTER_REQUEST === $type);
$event->expects($this->any())->method('getResponse')->willReturn($response);
return $event;
}
@@ -12,25 +12,26 @@
namespace Symfony\Component\Security\Http\Tests\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices;
class TokenBasedRememberMeServicesTest extends TestCase
{
public function testAutoLoginReturnsNullWhenNoCookie()
{
$service = $this->getService(null, array('name' => 'foo'));
$service = $this->getService(null, ['name' => 'foo']);
$this->assertNull($service->autoLogin(new Request()));
}
public function testAutoLoginThrowsExceptionOnInvalidCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo']);
$request = new Request();
$request->request->set('foo', 'true');
$request->cookies->set('foo', 'foo');
@@ -42,14 +43,14 @@ class TokenBasedRememberMeServicesTest extends TestCase
public function testAutoLoginThrowsExceptionOnNonExistentUser()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
$service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600]);
$request = new Request();
$request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time() + 3600, 'foopass'));
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new UsernameNotFoundException('user not found')))
->willThrowException(new UsernameNotFoundException('user not found'))
;
$this->assertNull($service->autoLogin($request));
@@ -59,7 +60,7 @@ class TokenBasedRememberMeServicesTest extends TestCase
public function testAutoLoginDoesNotAcceptCookieWithInvalidHash()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
$service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600]);
$request = new Request();
$request->cookies->set('foo', base64_encode('class:'.base64_encode('foouser').':123456789:fooHash'));
@@ -67,14 +68,14 @@ class TokenBasedRememberMeServicesTest extends TestCase
$user
->expects($this->once())
->method('getPassword')
->will($this->returnValue('foopass'))
->willReturn('foopass')
;
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foouser'))
->will($this->returnValue($user))
->willReturn($user)
;
$this->assertNull($service->autoLogin($request));
@@ -84,7 +85,7 @@ class TokenBasedRememberMeServicesTest extends TestCase
public function testAutoLoginDoesNotAcceptAnExpiredCookie()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
$service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600]);
$request = new Request();
$request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time() - 1, 'foopass'));
@@ -92,14 +93,14 @@ class TokenBasedRememberMeServicesTest extends TestCase
$user
->expects($this->once())
->method('getPassword')
->will($this->returnValue('foopass'))
->willReturn('foopass')
;
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foouser'))
->will($this->returnValue($user))
->willReturn($user)
;
$this->assertNull($service->autoLogin($request));
@@ -117,12 +118,12 @@ class TokenBasedRememberMeServicesTest extends TestCase
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
->willReturn(['ROLE_FOO'])
;
$user
->expects($this->once())
->method('getPassword')
->will($this->returnValue('foopass'))
->willReturn('foopass')
;
$userProvider = $this->getProvider();
@@ -130,10 +131,10 @@ class TokenBasedRememberMeServicesTest extends TestCase
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo($username))
->will($this->returnValue($user))
->willReturn($user)
;
$service = $this->getService($userProvider, array('name' => 'foo', 'always_remember_me' => true, 'lifetime' => 3600));
$service = $this->getService($userProvider, ['name' => 'foo', 'always_remember_me' => true, 'lifetime' => 3600]);
$request = new Request();
$request->cookies->set('foo', $this->getCookie('fooclass', $username, time() + 3600, 'foopass'));
@@ -146,15 +147,15 @@ class TokenBasedRememberMeServicesTest extends TestCase
public function provideUsernamesForAutoLogin()
{
return array(
array('foouser', 'Simple username'),
array('foo'.TokenBasedRememberMeServices::COOKIE_DELIMITER.'user', 'Username might contain the delimiter'),
);
return [
['foouser', 'Simple username'],
['foo'.TokenBasedRememberMeServices::COOKIE_DELIMITER.'user', 'Username might contain the delimiter'],
];
}
public function testLogout()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'secure' => true, 'httponly' => false));
$service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'secure' => true, 'httponly' => false]);
$request = new Request();
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
@@ -171,7 +172,7 @@ class TokenBasedRememberMeServicesTest extends TestCase
public function testLoginFail()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo'));
$service = $this->getService(null, ['name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo']);
$request = new Request();
$service->loginFail($request);
@@ -184,14 +185,14 @@ class TokenBasedRememberMeServicesTest extends TestCase
public function testLoginSuccessIgnoresTokensWhichDoNotContainAnUserInterfaceImplementation()
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null));
$service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null]);
$request = new Request();
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$cookies = $response->headers->getCookies();
@@ -205,7 +206,7 @@ class TokenBasedRememberMeServicesTest extends TestCase
public function testLoginSuccess()
{
$service = $this->getService(null, array('name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'lifetime' => 3600, 'always_remember_me' => true));
$service = $this->getService(null, ['name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'samesite' => Cookie::SAMESITE_STRICT, 'lifetime' => 3600, 'always_remember_me' => true]);
$request = new Request();
$response = new Response();
@@ -214,17 +215,17 @@ class TokenBasedRememberMeServicesTest extends TestCase
$user
->expects($this->once())
->method('getPassword')
->will($this->returnValue('foopass'))
->willReturn('foopass')
;
$user
->expects($this->once())
->method('getUsername')
->will($this->returnValue('foouser'))
->willReturn('foouser')
;
$token
->expects($this->atLeastOnce())
->method('getUser')
->will($this->returnValue($user))
->willReturn($user)
;
$cookies = $response->headers->getCookies();
@@ -240,6 +241,7 @@ class TokenBasedRememberMeServicesTest extends TestCase
$this->assertTrue($cookie->getExpiresTime() > time() + 3590 && $cookie->getExpiresTime() < time() + 3610);
$this->assertEquals('myfoodomain.foo', $cookie->getDomain());
$this->assertEquals('/foo/path', $cookie->getPath());
$this->assertSame(Cookie::SAMESITE_STRICT, $cookie->getSameSite());
}
protected function getCookie($class, $username, $expires, $password)
@@ -260,13 +262,13 @@ class TokenBasedRememberMeServicesTest extends TestCase
return $r->invoke($service, $parts);
}
protected function getService($userProvider = null, $options = array(), $logger = null)
protected function getService($userProvider = null, $options = [], $logger = null)
{
if (null === $userProvider) {
$userProvider = $this->getProvider();
}
$service = new TokenBasedRememberMeServices(array($userProvider), 'foosecret', 'fookey', $options, $logger);
$service = new TokenBasedRememberMeServices([$userProvider], 'foosecret', 'fookey', $options, $logger);
return $service;
}
@@ -277,7 +279,7 @@ class TokenBasedRememberMeServicesTest extends TestCase
$provider
->expects($this->any())
->method('supportsClass')
->will($this->returnValue(true))
->willReturn(true)
;
return $provider;
@@ -25,12 +25,10 @@ class SessionAuthenticationStrategyTest extends TestCase
$strategy->onAuthentication($request, $this->getToken());
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Invalid session authentication strategy "foo"
*/
public function testUnsupportedStrategy()
{
$this->expectException('RuntimeException');
$this->expectExceptionMessage('Invalid session authentication strategy "foo"');
$request = $this->getRequest();
$request->expects($this->never())->method('getSession');
@@ -61,7 +59,7 @@ class SessionAuthenticationStrategyTest extends TestCase
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
if (null !== $session) {
$request->expects($this->any())->method('getSession')->will($this->returnValue($session));
$request->expects($this->any())->method('getSession')->willReturn($session);
}
return $request;