FormAuthenticateTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 2.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Auth;
  17. use Cake\Auth\FormAuthenticate;
  18. use Cake\Controller\ComponentRegistry;
  19. use Cake\Http\Response;
  20. use Cake\Http\ServerRequest;
  21. use Cake\I18n\FrozenTime;
  22. use Cake\ORM\Entity;
  23. use Cake\TestSuite\TestCase;
  24. use TestApp\Auth\CallCounterPasswordHasher;
  25. /**
  26. * Test case for FormAuthentication
  27. */
  28. class FormAuthenticateTest extends TestCase
  29. {
  30. /**
  31. * Fixtures
  32. *
  33. * @var array<string>
  34. */
  35. protected $fixtures = ['core.AuthUsers', 'core.Users'];
  36. /**
  37. * @var \Cake\Controller\ComponentRegistry
  38. */
  39. protected $collection;
  40. /**
  41. * @var \Cake\Auth\FormAuthenticate
  42. */
  43. protected $auth;
  44. /**
  45. * setup
  46. */
  47. public function setUp(): void
  48. {
  49. parent::setUp();
  50. $this->collection = new ComponentRegistry();
  51. $this->auth = new FormAuthenticate($this->collection, [
  52. 'userModel' => 'Users',
  53. ]);
  54. $password = password_hash('password', PASSWORD_DEFAULT);
  55. $this->getTableLocator()->clear();
  56. $Users = $this->getTableLocator()->get('Users');
  57. $Users->updateAll(['password' => $password], []);
  58. $AuthUsers = $this->getTableLocator()->get('AuthUsers', [
  59. 'className' => 'TestApp\Model\Table\AuthUsersTable',
  60. ]);
  61. $AuthUsers->updateAll(['password' => $password], []);
  62. }
  63. /**
  64. * test applying settings in the constructor
  65. */
  66. public function testConstructor(): void
  67. {
  68. $object = new FormAuthenticate($this->collection, [
  69. 'userModel' => 'AuthUsers',
  70. 'fields' => ['username' => 'user', 'password' => 'password'],
  71. ]);
  72. $this->assertSame('AuthUsers', $object->getConfig('userModel'));
  73. $this->assertEquals(['username' => 'user', 'password' => 'password'], $object->getConfig('fields'));
  74. }
  75. /**
  76. * test the authenticate method
  77. */
  78. public function testAuthenticateNoData(): void
  79. {
  80. $request = new ServerRequest([
  81. 'url' => 'posts/index',
  82. 'post' => [],
  83. ]);
  84. $this->assertFalse($this->auth->authenticate($request, new Response()));
  85. }
  86. /**
  87. * test the authenticate method
  88. */
  89. public function testAuthenticateNoUsername(): void
  90. {
  91. $request = new ServerRequest([
  92. 'url' => 'posts/index',
  93. 'post' => ['password' => 'foobar'],
  94. ]);
  95. $this->assertFalse($this->auth->authenticate($request, new Response()));
  96. }
  97. /**
  98. * test the authenticate method
  99. */
  100. public function testAuthenticateNoPassword(): void
  101. {
  102. $request = new ServerRequest([
  103. 'url' => 'posts/index',
  104. 'post' => ['username' => 'mariano'],
  105. ]);
  106. $this->assertFalse($this->auth->authenticate($request, new Response()));
  107. }
  108. /**
  109. * test authenticate password is false method
  110. */
  111. public function testAuthenticatePasswordIsFalse(): void
  112. {
  113. $request = new ServerRequest([
  114. 'url' => 'posts/index',
  115. 'post' => [
  116. 'username' => 'mariano',
  117. 'password' => null,
  118. ],
  119. ]);
  120. $this->assertFalse($this->auth->authenticate($request, new Response()));
  121. }
  122. /**
  123. * Test for password as empty string with _checkFields() call skipped
  124. * Refs https://github.com/cakephp/cakephp/pull/2441
  125. */
  126. public function testAuthenticatePasswordIsEmptyString(): void
  127. {
  128. $request = new ServerRequest([
  129. 'url' => 'posts/index',
  130. 'post' => [
  131. 'username' => 'mariano',
  132. 'password' => '',
  133. ],
  134. ]);
  135. $this->auth = $this->getMockBuilder(FormAuthenticate::class)
  136. ->onlyMethods(['_checkFields'])
  137. ->setConstructorArgs([
  138. $this->collection,
  139. ['userModel' => 'Users'],
  140. ])
  141. ->getMock();
  142. // Simulate that check for ensuring password is not empty is missing.
  143. $this->auth->expects($this->once())
  144. ->method('_checkFields')
  145. ->will($this->returnValue(true));
  146. $this->assertFalse($this->auth->authenticate($request, new Response()));
  147. }
  148. /**
  149. * test authenticate field is not string
  150. */
  151. public function testAuthenticateFieldsAreNotString(): void
  152. {
  153. $request = new ServerRequest([
  154. 'url' => 'posts/index',
  155. 'post' => [
  156. 'username' => ['mariano', 'phpnut'],
  157. 'password' => 'my password',
  158. ],
  159. ]);
  160. $this->assertFalse($this->auth->authenticate($request, new Response()));
  161. $request = new ServerRequest([
  162. 'url' => 'posts/index',
  163. 'post' => [
  164. 'username' => 'mariano',
  165. 'password' => ['password1', 'password2'],
  166. ],
  167. ]);
  168. $this->assertFalse($this->auth->authenticate($request, new Response()));
  169. }
  170. /**
  171. * test the authenticate method
  172. */
  173. public function testAuthenticateInjection(): void
  174. {
  175. $request = new ServerRequest([
  176. 'url' => 'posts/index',
  177. 'post' => [
  178. 'username' => '> 1',
  179. 'password' => "' OR 1 = 1",
  180. ],
  181. ]);
  182. $this->assertFalse($this->auth->authenticate($request, new Response()));
  183. }
  184. /**
  185. * test authenticate success
  186. */
  187. public function testAuthenticateSuccess(): void
  188. {
  189. $request = new ServerRequest([
  190. 'url' => 'posts/index',
  191. 'post' => [
  192. 'username' => 'mariano',
  193. 'password' => 'password',
  194. ],
  195. ]);
  196. $result = $this->auth->authenticate($request, new Response());
  197. $expected = [
  198. 'id' => 1,
  199. 'username' => 'mariano',
  200. 'created' => new FrozenTime('2007-03-17 01:16:23'),
  201. 'updated' => new FrozenTime('2007-03-17 01:18:31'),
  202. ];
  203. $this->assertEquals($expected, $result);
  204. }
  205. /**
  206. * Test that authenticate() includes virtual fields.
  207. */
  208. public function testAuthenticateIncludesVirtualFields(): void
  209. {
  210. $users = $this->getTableLocator()->get('Users');
  211. $users->setEntityClass('TestApp\Model\Entity\VirtualUser');
  212. $request = new ServerRequest([
  213. 'url' => 'posts/index',
  214. 'post' => [
  215. 'username' => 'mariano',
  216. 'password' => 'password',
  217. ],
  218. ]);
  219. $result = $this->auth->authenticate($request, new Response());
  220. $expected = [
  221. 'id' => 1,
  222. 'username' => 'mariano',
  223. 'bonus' => 'bonus',
  224. 'created' => new FrozenTime('2007-03-17 01:16:23'),
  225. 'updated' => new FrozenTime('2007-03-17 01:18:31'),
  226. ];
  227. $this->assertEquals($expected, $result);
  228. }
  229. /**
  230. * test a model in a plugin.
  231. */
  232. public function testPluginModel(): void
  233. {
  234. $this->loadPlugins(['TestPlugin']);
  235. $PluginModel = $this->getTableLocator()->get('TestPlugin.AuthUsers');
  236. $user['id'] = 1;
  237. $user['username'] = 'gwoo';
  238. $user['password'] = password_hash('cake', PASSWORD_BCRYPT);
  239. $PluginModel->save(new Entity($user));
  240. $this->auth->setConfig('userModel', 'TestPlugin.AuthUsers');
  241. $request = new ServerRequest([
  242. 'url' => 'posts/index',
  243. 'post' => [
  244. 'username' => 'gwoo',
  245. 'password' => 'cake',
  246. ],
  247. ]);
  248. $result = $this->auth->authenticate($request, new Response());
  249. $expected = [
  250. 'id' => 1,
  251. 'username' => 'gwoo',
  252. 'created' => new FrozenTime('2007-03-17 01:16:23'),
  253. 'updated' => new FrozenTime('2007-03-17 01:18:31'),
  254. ];
  255. $this->assertEquals($expected, $result);
  256. $this->clearPlugins();
  257. }
  258. /**
  259. * Test using custom finder
  260. */
  261. public function testFinder(): void
  262. {
  263. $request = new ServerRequest([
  264. 'url' => 'posts/index',
  265. 'post' => [
  266. 'username' => 'mariano',
  267. 'password' => 'password',
  268. ],
  269. ]);
  270. $this->auth->setConfig([
  271. 'userModel' => 'AuthUsers',
  272. 'finder' => 'auth',
  273. ]);
  274. $result = $this->auth->authenticate($request, new Response());
  275. $expected = [
  276. 'id' => 1,
  277. 'username' => 'mariano',
  278. ];
  279. $this->assertEquals($expected, $result, 'Result should not contain "created" and "modified" fields');
  280. $this->auth->setConfig([
  281. 'finder' => ['auth' => ['return_created' => true]],
  282. ]);
  283. $result = $this->auth->authenticate($request, new Response());
  284. $expected = [
  285. 'id' => 1,
  286. 'username' => 'mariano',
  287. 'created' => new FrozenTime('2007-03-17 01:16:23'),
  288. ];
  289. $this->assertEquals($expected, $result);
  290. }
  291. /**
  292. * Test using custom finder
  293. */
  294. public function testFinderOptions(): void
  295. {
  296. $request = new ServerRequest([
  297. 'url' => 'posts/index',
  298. 'post' => [
  299. 'username' => 'mariano',
  300. 'password' => 'password',
  301. ],
  302. ]);
  303. $this->auth->setConfig([
  304. 'userModel' => 'AuthUsers',
  305. 'finder' => 'username',
  306. ]);
  307. $result = $this->auth->authenticate($request, new Response());
  308. $expected = [
  309. 'id' => 1,
  310. 'username' => 'mariano',
  311. ];
  312. $this->assertEquals($expected, $result);
  313. $this->auth->setConfig([
  314. 'finder' => ['username' => ['username' => 'nate']],
  315. ]);
  316. $result = $this->auth->authenticate($request, new Response());
  317. $expected = [
  318. 'id' => 5,
  319. 'username' => 'nate',
  320. ];
  321. $this->assertEquals($expected, $result);
  322. }
  323. /**
  324. * test password hasher settings
  325. */
  326. public function testPasswordHasherSettings(): void
  327. {
  328. $this->auth->setConfig('passwordHasher', [
  329. 'className' => 'Default',
  330. 'hashType' => PASSWORD_BCRYPT,
  331. ]);
  332. $passwordHasher = $this->auth->passwordHasher();
  333. $result = $passwordHasher->getConfig();
  334. $this->assertSame(PASSWORD_BCRYPT, $result['hashType']);
  335. $hash = password_hash('mypass', PASSWORD_BCRYPT);
  336. $User = $this->getTableLocator()->get('Users');
  337. $User->updateAll(
  338. ['password' => $hash],
  339. ['username' => 'mariano']
  340. );
  341. $request = new ServerRequest([
  342. 'url' => 'posts/index',
  343. 'post' => [
  344. 'username' => 'mariano',
  345. 'password' => 'mypass',
  346. ],
  347. ]);
  348. $result = $this->auth->authenticate($request, new Response());
  349. $expected = [
  350. 'id' => 1,
  351. 'username' => 'mariano',
  352. 'created' => new FrozenTime('2007-03-17 01:16:23'),
  353. 'updated' => new FrozenTime('2007-03-17 01:18:31'),
  354. ];
  355. $this->assertEquals($expected, $result);
  356. $this->auth = new FormAuthenticate($this->collection, [
  357. 'fields' => ['username' => 'username', 'password' => 'password'],
  358. 'userModel' => 'Users',
  359. ]);
  360. $this->auth->setConfig('passwordHasher', [
  361. 'className' => 'Default',
  362. ]);
  363. $this->assertEquals($expected, $this->auth->authenticate($request, new Response()));
  364. $User->updateAll(
  365. ['password' => '$2y$10$/G9GBQDZhWUM4w/WLes3b.XBZSK1hGohs5dMi0vh/oen0l0a7DUyK'],
  366. ['username' => 'mariano']
  367. );
  368. $this->assertFalse($this->auth->authenticate($request, new Response()));
  369. }
  370. /**
  371. * Tests that using default means password don't need to be rehashed
  372. */
  373. public function testAuthenticateNoRehash(): void
  374. {
  375. $request = new ServerRequest([
  376. 'url' => 'posts/index',
  377. 'post' => [
  378. 'username' => 'mariano',
  379. 'password' => 'password',
  380. ],
  381. ]);
  382. $result = $this->auth->authenticate($request, new Response());
  383. $this->assertNotEmpty($result);
  384. $this->assertFalse($this->auth->needsPasswordRehash());
  385. }
  386. /**
  387. * Tests that not using the Default password hasher means that the password
  388. * needs to be rehashed
  389. */
  390. public function testAuthenticateRehash(): void
  391. {
  392. $this->auth = new FormAuthenticate($this->collection, [
  393. 'userModel' => 'Users',
  394. 'passwordHasher' => 'Weak',
  395. ]);
  396. $password = $this->auth->passwordHasher()->hash('password');
  397. $this->getTableLocator()->get('Users')->updateAll(['password' => $password], []);
  398. $request = new ServerRequest([
  399. 'url' => 'posts/index',
  400. 'post' => [
  401. 'username' => 'mariano',
  402. 'password' => 'password',
  403. ],
  404. ]);
  405. $result = $this->auth->authenticate($request, new Response());
  406. $this->assertNotEmpty($result);
  407. $this->assertTrue($this->auth->needsPasswordRehash());
  408. }
  409. /**
  410. * Tests that password hasher function is called exactly once in all cases.
  411. *
  412. * @dataProvider userList
  413. */
  414. public function testAuthenticateSingleHash(string $username, ?string $password): void
  415. {
  416. $this->auth = new FormAuthenticate($this->collection, [
  417. 'userModel' => 'Users',
  418. 'passwordHasher' => CallCounterPasswordHasher::class,
  419. ]);
  420. $this->getTableLocator()->get('Users')->updateAll(
  421. ['password' => $password],
  422. ['username' => $username]
  423. );
  424. $request = new ServerRequest([
  425. 'url' => 'posts/index',
  426. 'post' => [
  427. 'username' => $username,
  428. 'password' => 'anything',
  429. ],
  430. ]);
  431. $result = $this->auth->authenticate($request, new Response());
  432. $this->assertFalse($result);
  433. /** @var \TestApp\Auth\CallCounterPasswordHasher $passwordHasher */
  434. $passwordHasher = $this->auth->passwordHasher();
  435. $this->assertInstanceOf(CallCounterPasswordHasher::class, $passwordHasher);
  436. $this->assertSame(1, $passwordHasher->callCount);
  437. }
  438. public function userList(): array
  439. {
  440. return [
  441. ['notexist', ''],
  442. ['mariano', null],
  443. ['mariano', ''],
  444. ['mariano', 'somehash'],
  445. ];
  446. }
  447. }