PersistentTokenBasedRememberMeServicesTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Security\Http\Tests\RememberMe;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  15. use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
  16. use Symfony\Component\Security\Core\Exception\CookieTheftException;
  17. use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
  18. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  19. use Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices;
  20. use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
  21. class PersistentTokenBasedRememberMeServicesTest extends TestCase
  22. {
  23. public static function setUpBeforeClass()
  24. {
  25. try {
  26. random_bytes(1);
  27. } catch (\Exception $e) {
  28. self::markTestSkipped($e->getMessage());
  29. }
  30. }
  31. public function testAutoLoginReturnsNullWhenNoCookie()
  32. {
  33. $service = $this->getService(null, array('name' => 'foo'));
  34. $this->assertNull($service->autoLogin(new Request()));
  35. }
  36. public function testAutoLoginThrowsExceptionOnInvalidCookie()
  37. {
  38. $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
  39. $request = new Request();
  40. $request->request->set('foo', 'true');
  41. $request->cookies->set('foo', 'foo');
  42. $this->assertNull($service->autoLogin($request));
  43. $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
  44. }
  45. public function testAutoLoginThrowsExceptionOnNonExistentToken()
  46. {
  47. $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
  48. $request = new Request();
  49. $request->request->set('foo', 'true');
  50. $request->cookies->set('foo', $this->encodeCookie(array(
  51. $series = 'fooseries',
  52. $tokenValue = 'foovalue',
  53. )));
  54. $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
  55. $tokenProvider
  56. ->expects($this->once())
  57. ->method('loadTokenBySeries')
  58. ->will($this->throwException(new TokenNotFoundException('Token not found.')))
  59. ;
  60. $service->setTokenProvider($tokenProvider);
  61. $this->assertNull($service->autoLogin($request));
  62. $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
  63. }
  64. public function testAutoLoginReturnsNullOnNonExistentUser()
  65. {
  66. $userProvider = $this->getProvider();
  67. $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600, 'secure' => false, 'httponly' => false));
  68. $request = new Request();
  69. $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
  70. $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
  71. $tokenProvider
  72. ->expects($this->once())
  73. ->method('loadTokenBySeries')
  74. ->will($this->returnValue(new PersistentToken('fooclass', 'fooname', 'fooseries', 'foovalue', new \DateTime())))
  75. ;
  76. $service->setTokenProvider($tokenProvider);
  77. $userProvider
  78. ->expects($this->once())
  79. ->method('loadUserByUsername')
  80. ->will($this->throwException(new UsernameNotFoundException('user not found')))
  81. ;
  82. $this->assertNull($service->autoLogin($request));
  83. $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
  84. }
  85. public function testAutoLoginThrowsExceptionOnStolenCookieAndRemovesItFromThePersistentBackend()
  86. {
  87. $userProvider = $this->getProvider();
  88. $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true));
  89. $request = new Request();
  90. $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
  91. $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
  92. $service->setTokenProvider($tokenProvider);
  93. $tokenProvider
  94. ->expects($this->once())
  95. ->method('loadTokenBySeries')
  96. ->will($this->returnValue(new PersistentToken('fooclass', 'foouser', 'fooseries', 'anotherFooValue', new \DateTime())))
  97. ;
  98. $tokenProvider
  99. ->expects($this->once())
  100. ->method('deleteTokenBySeries')
  101. ->with($this->equalTo('fooseries'))
  102. ->will($this->returnValue(null))
  103. ;
  104. try {
  105. $service->autoLogin($request);
  106. $this->fail('Expected CookieTheftException was not thrown.');
  107. } catch (CookieTheftException $e) {
  108. }
  109. $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
  110. }
  111. public function testAutoLoginDoesNotAcceptAnExpiredCookie()
  112. {
  113. $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
  114. $request = new Request();
  115. $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
  116. $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
  117. $tokenProvider
  118. ->expects($this->once())
  119. ->method('loadTokenBySeries')
  120. ->with($this->equalTo('fooseries'))
  121. ->will($this->returnValue(new PersistentToken('fooclass', 'username', 'fooseries', 'foovalue', new \DateTime('yesterday'))))
  122. ;
  123. $service->setTokenProvider($tokenProvider);
  124. $this->assertNull($service->autoLogin($request));
  125. $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
  126. }
  127. public function testAutoLogin()
  128. {
  129. $user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
  130. $user
  131. ->expects($this->once())
  132. ->method('getRoles')
  133. ->will($this->returnValue(array('ROLE_FOO')))
  134. ;
  135. $userProvider = $this->getProvider();
  136. $userProvider
  137. ->expects($this->once())
  138. ->method('loadUserByUsername')
  139. ->with($this->equalTo('foouser'))
  140. ->will($this->returnValue($user))
  141. ;
  142. $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'secure' => false, 'httponly' => false, 'always_remember_me' => true, 'lifetime' => 3600));
  143. $request = new Request();
  144. $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
  145. $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
  146. $tokenProvider
  147. ->expects($this->once())
  148. ->method('loadTokenBySeries')
  149. ->with($this->equalTo('fooseries'))
  150. ->will($this->returnValue(new PersistentToken('fooclass', 'foouser', 'fooseries', 'foovalue', new \DateTime())))
  151. ;
  152. $service->setTokenProvider($tokenProvider);
  153. $returnedToken = $service->autoLogin($request);
  154. $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', $returnedToken);
  155. $this->assertSame($user, $returnedToken->getUser());
  156. $this->assertEquals('foosecret', $returnedToken->getSecret());
  157. $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
  158. }
  159. public function testLogout()
  160. {
  161. $service = $this->getService(null, array('name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo', 'secure' => true, 'httponly' => false));
  162. $request = new Request();
  163. $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
  164. $response = new Response();
  165. $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
  166. $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
  167. $tokenProvider
  168. ->expects($this->once())
  169. ->method('deleteTokenBySeries')
  170. ->with($this->equalTo('fooseries'))
  171. ->will($this->returnValue(null))
  172. ;
  173. $service->setTokenProvider($tokenProvider);
  174. $service->logout($request, $response, $token);
  175. $cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
  176. $this->assertTrue($cookie->isCleared());
  177. $this->assertEquals('/foo', $cookie->getPath());
  178. $this->assertEquals('foodomain.foo', $cookie->getDomain());
  179. $this->assertTrue($cookie->isSecure());
  180. $this->assertFalse($cookie->isHttpOnly());
  181. }
  182. public function testLogoutSimplyIgnoresNonSetRequestCookie()
  183. {
  184. $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
  185. $request = new Request();
  186. $response = new Response();
  187. $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
  188. $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
  189. $tokenProvider
  190. ->expects($this->never())
  191. ->method('deleteTokenBySeries')
  192. ;
  193. $service->setTokenProvider($tokenProvider);
  194. $service->logout($request, $response, $token);
  195. $cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
  196. $this->assertTrue($cookie->isCleared());
  197. $this->assertEquals('/', $cookie->getPath());
  198. $this->assertNull($cookie->getDomain());
  199. }
  200. public function testLogoutSimplyIgnoresInvalidCookie()
  201. {
  202. $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
  203. $request = new Request();
  204. $request->cookies->set('foo', 'somefoovalue');
  205. $response = new Response();
  206. $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
  207. $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
  208. $tokenProvider
  209. ->expects($this->never())
  210. ->method('deleteTokenBySeries')
  211. ;
  212. $service->setTokenProvider($tokenProvider);
  213. $service->logout($request, $response, $token);
  214. $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
  215. }
  216. public function testLoginFail()
  217. {
  218. $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
  219. $request = new Request();
  220. $this->assertFalse($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
  221. $service->loginFail($request);
  222. $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
  223. }
  224. public function testLoginSuccessSetsCookieWhenLoggedInWithNonRememberMeTokenInterfaceImplementation()
  225. {
  226. $service = $this->getService(null, array('name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'lifetime' => 3600, 'always_remember_me' => true));
  227. $request = new Request();
  228. $response = new Response();
  229. $account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
  230. $account
  231. ->expects($this->once())
  232. ->method('getUsername')
  233. ->will($this->returnValue('foo'))
  234. ;
  235. $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
  236. $token
  237. ->expects($this->any())
  238. ->method('getUser')
  239. ->will($this->returnValue($account))
  240. ;
  241. $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
  242. $tokenProvider
  243. ->expects($this->once())
  244. ->method('createNewToken')
  245. ;
  246. $service->setTokenProvider($tokenProvider);
  247. $cookies = $response->headers->getCookies();
  248. $this->assertCount(0, $cookies);
  249. $service->loginSuccess($request, $response, $token);
  250. $cookies = $response->headers->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
  251. $cookie = $cookies['myfoodomain.foo']['/foo/path']['foo'];
  252. $this->assertFalse($cookie->isCleared());
  253. $this->assertTrue($cookie->isSecure());
  254. $this->assertTrue($cookie->isHttpOnly());
  255. $this->assertTrue($cookie->getExpiresTime() > time() + 3590 && $cookie->getExpiresTime() < time() + 3610);
  256. $this->assertEquals('myfoodomain.foo', $cookie->getDomain());
  257. $this->assertEquals('/foo/path', $cookie->getPath());
  258. }
  259. protected function encodeCookie(array $parts)
  260. {
  261. $service = $this->getService();
  262. $r = new \ReflectionMethod($service, 'encodeCookie');
  263. $r->setAccessible(true);
  264. return $r->invoke($service, $parts);
  265. }
  266. protected function getService($userProvider = null, $options = array(), $logger = null)
  267. {
  268. if (null === $userProvider) {
  269. $userProvider = $this->getProvider();
  270. }
  271. return new PersistentTokenBasedRememberMeServices(array($userProvider), 'foosecret', 'fookey', $options, $logger);
  272. }
  273. protected function getProvider()
  274. {
  275. $provider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
  276. $provider
  277. ->expects($this->any())
  278. ->method('supportsClass')
  279. ->will($this->returnValue(true))
  280. ;
  281. return $provider;
  282. }
  283. }