PersistentLoginTest.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. namespace Elgg;
  3. class PersistentLoginTest extends \PHPUnit_Framework_TestCase {
  4. /**
  5. * @var \ElggSession
  6. */
  7. protected $session;
  8. /**
  9. * @var \PHPUnit_Framework_MockObject_MockObject
  10. */
  11. protected $dbMock;
  12. /**
  13. * @var \PHPUnit_Framework_MockObject_MockObject
  14. */
  15. protected $cryptoMock;
  16. /**
  17. * @var \Elgg\PersistentLoginService
  18. */
  19. protected $svc;
  20. /**
  21. * @var \PHPUnit_Framework_MockObject_MockObject
  22. */
  23. protected $user123;
  24. /**
  25. * @var \ElggCookie
  26. */
  27. protected $lastCookieSet;
  28. /**
  29. * @var string
  30. */
  31. protected $mockToken;
  32. /**
  33. * @var string
  34. */
  35. protected $mockHash;
  36. /**
  37. * @var int
  38. */
  39. protected $timeSlept;
  40. /**
  41. * @var int
  42. */
  43. protected $thirtyDaysAgo;
  44. function setUp() {
  45. $this->thirtyDaysAgo = strtotime("-30 days");
  46. $this->mockToken = 'z' . str_repeat('a', 31);
  47. $this->mockHash = md5($this->mockToken);
  48. $this->user123 = $this->getMockElggUser(123);
  49. $this->session = \ElggSession::getMock();
  50. // mock DB
  51. $this->dbMock = $this->getMockBuilder('\Elgg\Database')
  52. ->disableOriginalConstructor()
  53. ->getMock();
  54. // use addslashes as ->sanitizeString (my local CLI doesn't have MySQL)
  55. $this->dbMock->expects($this->any())
  56. ->method('sanitizeString')
  57. ->will($this->returnCallback(array($this, 'mock_sanitizeString')));
  58. $this->cryptoMock = $this->getMockBuilder('\ElggCrypto')->getMock();
  59. $this->cryptoMock->expects($this->any())
  60. ->method('getRandomString')
  61. ->will($this->returnValue(str_repeat('a', 31)));
  62. $this->svc = $this->getSvcWithCookie("");
  63. }
  64. function testLoginSavesHashAndPutsTokenInCookieAndSession() {
  65. $this->dbMock->expects($this->once())
  66. ->method('insertData')
  67. ->will($this->returnCallback(array($this, 'mock_insertData')));
  68. $this->svc->makeLoginPersistent($this->user123);
  69. $this->assertSame($this->mockToken, $this->lastCookieSet->value);
  70. $this->assertSame($this->mockToken, $this->session->get('code'));
  71. }
  72. function testRemoveDeletesHashAndDeletesTokenFromCookieAndSession() {
  73. $this->svc = $this->getSvcWithCookie($this->mockToken);
  74. $this->dbMock->expects($this->once())
  75. ->method('deleteData')
  76. ->will($this->returnCallback(array($this, 'mock_deleteData')));
  77. $this->svc->removePersistentLogin();
  78. $this->assertSame('', $this->lastCookieSet->value);
  79. $this->assertSame($this->thirtyDaysAgo, $this->lastCookieSet->expire);
  80. $this->assertNull($this->session->get('code'));
  81. }
  82. function testRemoveWithoutCookieCantDeleteHash() {
  83. $this->dbMock->expects($this->never())
  84. ->method('deleteData');
  85. $this->svc->removePersistentLogin();
  86. $this->assertSame('', $this->lastCookieSet->value);
  87. $this->assertSame($this->thirtyDaysAgo, $this->lastCookieSet->expire);
  88. $this->assertNull($this->session->get('code'));
  89. }
  90. function testGettingUserFromKnownHashReturnsUser() {
  91. $this->dbMock->expects($this->once())
  92. ->method('getDataRow')
  93. ->will($this->returnCallback(array($this, 'mock_getDataRow')));
  94. $user = $this->svc->getUserFromHash($this->mockHash);
  95. $this->assertSame($this->user123, $user);
  96. }
  97. function testGettingUserFromMissingHashReturnsNull() {
  98. $this->dbMock->expects($this->once())
  99. ->method('getDataRow')
  100. ->will($this->returnValue(array()));
  101. $user = $this->svc->getUserFromHash($this->mockHash);
  102. $this->assertNull($user);
  103. }
  104. function testGettingMissingUserFromKnownHashReturnsNull() {
  105. $this->dbMock->expects($this->once())
  106. ->method('getDataRow')
  107. ->will($this->returnValue((object)array('guid' => 234)));
  108. $user = $this->svc->getUserFromHash($this->mockHash);
  109. $this->assertNull($user);
  110. }
  111. function testChangingOwnPasswordDeletesAllHashesAndMakesPersistent() {
  112. $subject = $this->user123;
  113. $modifier = $this->user123;
  114. $this->dbMock->expects($this->exactly(2))
  115. ->method('deleteData');
  116. // Here we can't make an expectation on mock_deleteAll because one
  117. // of the calls deletes all, and another deletes only a single hash.
  118. // We'd have to fix mock_deleteAll to handle it.
  119. // @todo replace this with a real DB test
  120. $this->dbMock->expects($this->once())
  121. ->method('insertData')
  122. ->will($this->returnCallback(array($this, 'mock_insertData')));
  123. $this->svc = $this->getSvcWithCookie('notempty');
  124. $this->svc->handlePasswordChange($subject, $modifier);
  125. $this->assertSame($this->mockToken, $this->lastCookieSet->value);
  126. $this->assertSame($this->mockToken, $this->session->get('code'));
  127. }
  128. function testChangingOwnPasswordWithNoCookieDoesntMakePersistent() {
  129. $subject = $this->user123;
  130. $modifier = $this->user123;
  131. $this->dbMock->expects($this->once())
  132. ->method('deleteData')
  133. ->will($this->returnCallback(array($this, 'mock_deleteAll')));
  134. $this->dbMock->expects($this->never())
  135. ->method('insertData');
  136. $this->svc->handlePasswordChange($subject, $modifier);
  137. $this->assertNull($this->lastCookieSet);
  138. $this->assertNull($this->session->get('code'));
  139. }
  140. function testChangingSomeoneElsesPasswordDoesntMakePersistent() {
  141. $subject = $this->user123;
  142. $modifier = $this->getMockElggUser(234);
  143. $this->dbMock->expects($this->atLeastOnce())
  144. ->method('deleteData')
  145. ->will($this->returnCallback(array($this, 'mock_deleteAll')));
  146. $this->dbMock->expects($this->never())
  147. ->method('insertData');
  148. $this->svc->handlePasswordChange($subject, $modifier);
  149. $this->assertNull($this->lastCookieSet);
  150. $this->assertNull($this->session->get('code'));
  151. }
  152. function testGettingUserFromValidClientReturnsUser() {
  153. $this->dbMock->expects($this->once())
  154. ->method('getDataRow')
  155. ->will($this->returnValue((object)array('guid' => 123)));
  156. $this->svc = $this->getSvcWithCookie($this->mockToken);
  157. $user = $this->svc->bootSession();
  158. $this->assertSame($this->user123, $user);
  159. }
  160. function testGetPersistedUser_invalidModernToken() {
  161. $this->dbMock->expects($this->once())
  162. ->method('getDataRow')
  163. ->will($this->returnValue(array()));
  164. $this->svc = $this->getSvcWithCookie('z' . str_repeat('b', 31));
  165. $user = $this->svc->bootSession();
  166. $this->assertNull($this->timeSlept);
  167. $this->assertSame('', $this->lastCookieSet->value);
  168. $this->assertSame($this->thirtyDaysAgo, $this->lastCookieSet->expire);
  169. $this->assertNull($user);
  170. }
  171. function testBootSessionWithInvalidLegacyTokenCausesDelayAndFailure() {
  172. $this->dbMock->expects($this->once())
  173. ->method('getDataRow')
  174. ->will($this->returnValue(array()));
  175. $this->svc = $this->getSvcWithCookie(str_repeat('b', 32));
  176. $user = $this->svc->bootSession();
  177. $this->assertSame(1, $this->timeSlept);
  178. $this->assertSame('', $this->lastCookieSet->value);
  179. $this->assertSame($this->thirtyDaysAgo, $this->lastCookieSet->expire);
  180. $this->assertNull($user);
  181. }
  182. function testReplaceLegacyTokenWithNoCookieDoesNothing() {
  183. $this->svc = $this->getSvcWithCookie('');
  184. $this->dbMock->expects($this->never())
  185. ->method('deleteData');
  186. $this->svc->replaceLegacyToken($this->user123);
  187. $this->assertNull($this->lastCookieSet);
  188. $this->assertNull($this->session->get('code'));
  189. }
  190. function testModernTokenCookiesAreNotReplaced() {
  191. $this->dbMock->expects($this->never())
  192. ->method('deleteData');
  193. $this->svc->replaceLegacyToken($this->user123);
  194. $this->assertNull($this->lastCookieSet);
  195. $this->assertNull($this->session->get('code'));
  196. }
  197. function testLegacyCookiesAreReplacedInDbCookieAndSession() {
  198. $this->svc = $this->getSvcWithCookie(str_repeat('a', 32));
  199. $this->dbMock->expects($this->atLeastOnce())
  200. ->method('deleteData');
  201. $this->dbMock->expects($this->once())
  202. ->method('insertData');
  203. $this->svc->replaceLegacyToken($this->user123);
  204. $this->assertSame($this->mockToken, $this->lastCookieSet->value);
  205. $this->assertSame($this->mockToken, $this->session->get('code'));
  206. }
  207. // mock \ElggUser which will return the GUID on ->guid reads
  208. function getMockElggUser($guid) {
  209. $user = $this->getMockBuilder('\ElggUser')
  210. ->disableOriginalConstructor()
  211. ->getMock();
  212. $user->expects($this->any())
  213. ->method('__get')
  214. ->with('guid')
  215. ->will($this->returnValue((int)$guid));
  216. return $user;
  217. }
  218. function mock_get_user($guid) {
  219. if ((int)$guid === 123) {
  220. return $this->user123;
  221. }
  222. return null;
  223. }
  224. function mock_elgg_set_cookie(\ElggCookie $cookie) {
  225. $this->lastCookieSet = $cookie;
  226. }
  227. function mock_sleep($seconds) {
  228. $this->timeSlept = $seconds;
  229. }
  230. function mock_sanitizeString($string) {
  231. // no need for dependence on MySQL here
  232. return addslashes($string);
  233. }
  234. /**
  235. * @param string $cookie_token
  236. * @return \Elgg\PersistentLoginService
  237. */
  238. protected function getSvcWithCookie($cookie_token = '') {
  239. $cookie_config = array(
  240. 'lifetime' => 0,
  241. 'path' => '/',
  242. 'domain' => '',
  243. 'secure' => false,
  244. 'httponly' => false,
  245. 'name' => 'elggperm',
  246. 'expire' => time() + (30 * 86400),
  247. );
  248. $time = $this->thirtyDaysAgo + (30 * 86400);
  249. $svc = new \Elgg\PersistentLoginService(
  250. $this->dbMock, $this->session, $this->cryptoMock,
  251. $cookie_config, $cookie_token, $time);
  252. $svc->_callable_get_user = array($this, 'mock_get_user');
  253. $svc->_callable_generateToken = array($this, 'mock_generateToken');
  254. $svc->_callable_elgg_set_cookie = array($this, 'mock_elgg_set_cookie');
  255. $svc->_callable_sleep = array($this, 'mock_sleep');
  256. return $svc;
  257. }
  258. function mock_insertData($sql) {
  259. $this->assertContains("INSERT INTO users_remember_me_cookies", $sql);
  260. $this->assertContains("VALUES ('{$this->mockHash}', 123,", $sql);
  261. }
  262. function mock_deleteData($sql) {
  263. $pattern = "~DELETE FROM users_remember_me_cookies\\s+WHERE code = '{$this->mockHash}'~";
  264. $this->assertSame(1, preg_match($pattern, $sql));
  265. }
  266. function mock_getDataRow($sql) {
  267. $pattern = "~SELECT guid FROM users_remember_me_cookies\\s+WHERE code = '{$this->mockHash}'~";
  268. $this->assertSame(1, preg_match($pattern, $sql));
  269. return (object)array('guid' => 123);
  270. }
  271. function mock_deleteAll($sql) {
  272. $pattern = "~DELETE FROM users_remember_me_cookies\\s+WHERE guid = '123'+~";
  273. $this->assertSame(1, preg_match($pattern, $sql));
  274. }
  275. }