DigestAuthenticateTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. <?php
  2. /**
  3. * DigestAuthenticateTest file
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  13. * @link https://cakephp.org CakePHP(tm) Project
  14. * @since 2.0.0
  15. * @license https://opensource.org/licenses/mit-license.php MIT License
  16. */
  17. namespace Cake\Test\TestCase\Auth;
  18. use Cake\Auth\DigestAuthenticate;
  19. use Cake\Controller\ComponentRegistry;
  20. use Cake\Core\Configure;
  21. use Cake\Http\Exception\UnauthorizedException;
  22. use Cake\Http\Response;
  23. use Cake\Http\ServerRequest;
  24. use Cake\I18n\Time;
  25. use Cake\ORM\Entity;
  26. use Cake\TestSuite\TestCase;
  27. use Cake\Utility\Security;
  28. /**
  29. * Entity for testing with hidden fields.
  30. */
  31. class ProtectedUser extends Entity
  32. {
  33. protected $_hidden = ['password'];
  34. }
  35. /**
  36. * Test case for DigestAuthentication
  37. */
  38. class DigestAuthenticateTest extends TestCase
  39. {
  40. /**
  41. * Fixtures
  42. *
  43. * @var array
  44. */
  45. public $fixtures = ['core.AuthUsers', 'core.Users'];
  46. /**
  47. * setup
  48. *
  49. * @return void
  50. */
  51. public function setUp()
  52. {
  53. parent::setUp();
  54. $this->Collection = $this->getMockBuilder(ComponentRegistry::class)->getMock();
  55. $this->auth = new DigestAuthenticate($this->Collection, [
  56. 'realm' => 'localhost',
  57. 'nonce' => 123,
  58. 'opaque' => '123abc',
  59. 'secret' => Security::getSalt(),
  60. 'passwordHasher' => 'ShouldNeverTryToUsePasswordHasher',
  61. ]);
  62. $password = DigestAuthenticate::password('mariano', 'cake', 'localhost');
  63. $User = $this->getTableLocator()->get('Users');
  64. $User->updateAll(['password' => $password], []);
  65. $this->response = $this->getMockBuilder(Response::class)->getMock();
  66. }
  67. /**
  68. * test applying settings in the constructor
  69. *
  70. * @return void
  71. */
  72. public function testConstructor()
  73. {
  74. $object = new DigestAuthenticate($this->Collection, [
  75. 'userModel' => 'AuthUser',
  76. 'fields' => ['username' => 'user', 'password' => 'pass'],
  77. 'nonce' => 123456,
  78. ]);
  79. $this->assertEquals('AuthUser', $object->getConfig('userModel'));
  80. $this->assertEquals(['username' => 'user', 'password' => 'pass'], $object->getConfig('fields'));
  81. $this->assertEquals(123456, $object->getConfig('nonce'));
  82. $this->assertEquals(env('SERVER_NAME'), $object->getConfig('realm'));
  83. }
  84. /**
  85. * test the authenticate method
  86. *
  87. * @return void
  88. */
  89. public function testAuthenticateNoData()
  90. {
  91. $request = new ServerRequest('posts/index');
  92. $this->response->expects($this->never())
  93. ->method('header');
  94. $this->assertFalse($this->auth->getUser($request, $this->response));
  95. }
  96. /**
  97. * test the authenticate method
  98. *
  99. * @return void
  100. */
  101. public function testAuthenticateWrongUsername()
  102. {
  103. $request = new ServerRequest(['url' => 'posts/index']);
  104. $data = [
  105. 'username' => 'incorrect_user',
  106. 'realm' => 'localhost',
  107. 'nonce' => $this->generateNonce(),
  108. 'uri' => '/dir/index.html',
  109. 'qop' => 'auth',
  110. 'nc' => 0000001,
  111. 'cnonce' => '0a4f113b',
  112. ];
  113. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  114. $request = $request->withEnv('PHP_AUTH_DIGEST', $this->digestHeader($data));
  115. $this->assertFalse($this->auth->authenticate($request, new Response()));
  116. $this->expectException(UnauthorizedException::class);
  117. $this->expectExceptionCode(401);
  118. $this->auth->unauthenticated($request, $this->response);
  119. }
  120. /**
  121. * test that challenge headers are sent when no credentials are found.
  122. *
  123. * @return void
  124. */
  125. public function testAuthenticateChallenge()
  126. {
  127. $request = new ServerRequest([
  128. 'url' => 'posts/index',
  129. 'environment' => ['REQUEST_METHOD' => 'GET'],
  130. ]);
  131. try {
  132. $this->auth->unauthenticated($request, $this->response);
  133. } catch (UnauthorizedException $e) {
  134. }
  135. $this->assertNotEmpty($e);
  136. $header = $e->responseHeader();
  137. $this->assertRegexp(
  138. '/^Digest realm="localhost",qop="auth",nonce="[a-zA-Z0-9=]+",opaque="123abc"$/',
  139. $header['WWW-Authenticate']
  140. );
  141. }
  142. /**
  143. * test that challenge headers include stale when the nonce is stale
  144. *
  145. * @return void
  146. */
  147. public function testAuthenticateChallengeIncludesStaleAttributeOnStaleNonce()
  148. {
  149. $request = new ServerRequest([
  150. 'url' => 'posts/index',
  151. 'environment' => ['REQUEST_METHOD' => 'GET'],
  152. ]);
  153. $data = [
  154. 'uri' => '/dir/index.html',
  155. 'nonce' => $this->generateNonce(null, 5, strtotime('-10 minutes')),
  156. 'nc' => 1,
  157. 'cnonce' => '123',
  158. 'qop' => 'auth',
  159. ];
  160. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  161. $request = $request->withEnv('PHP_AUTH_DIGEST', $this->digestHeader($data));
  162. try {
  163. $this->auth->unauthenticated($request, $this->response);
  164. } catch (UnauthorizedException $e) {
  165. }
  166. $this->assertNotEmpty($e);
  167. $header = $e->responseHeader()['WWW-Authenticate'];
  168. $this->assertContains('stale=true', $header);
  169. }
  170. /**
  171. * Test that authentication fails when a nonce is stale
  172. *
  173. * @return void
  174. */
  175. public function testAuthenticateFailsOnStaleNonce()
  176. {
  177. $request = new ServerRequest([
  178. 'url' => 'posts/index',
  179. 'environment' => ['REQUEST_METHOD' => 'GET'],
  180. ]);
  181. $data = [
  182. 'uri' => '/dir/index.html',
  183. 'nonce' => $this->generateNonce(null, 5, strtotime('-10 minutes')),
  184. 'nc' => 1,
  185. 'cnonce' => '123',
  186. 'qop' => 'auth',
  187. ];
  188. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  189. $request = $request->withEnv('PHP_AUTH_DIGEST', $this->digestHeader($data));
  190. $result = $this->auth->authenticate($request, $this->response);
  191. $this->assertFalse($result, 'Stale nonce should fail');
  192. }
  193. /**
  194. * Test that nonces are required.
  195. *
  196. * @return void
  197. */
  198. public function testAuthenticateValidUsernamePasswordNoNonce()
  199. {
  200. $request = new ServerRequest([
  201. 'url' => 'posts/index',
  202. 'environment' => ['REQUEST_METHOD' => 'GET'],
  203. ]);
  204. $data = [
  205. 'username' => 'mariano',
  206. 'realm' => 'localhos',
  207. 'uri' => '/dir/index.html',
  208. 'nonce' => '',
  209. 'nc' => 1,
  210. 'cnonce' => '123',
  211. 'qop' => 'auth',
  212. ];
  213. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  214. $request = $request->withEnv('PHP_AUTH_DIGEST', $this->digestHeader($data));
  215. $result = $this->auth->authenticate($request, $this->response);
  216. $this->assertFalse($result, 'Empty nonce should fail');
  217. }
  218. /**
  219. * test authenticate success
  220. *
  221. * @return void
  222. */
  223. public function testAuthenticateSuccess()
  224. {
  225. $request = new ServerRequest([
  226. 'url' => 'posts/index',
  227. 'environment' => ['REQUEST_METHOD' => 'GET'],
  228. ]);
  229. $data = [
  230. 'uri' => '/dir/index.html',
  231. 'nonce' => $this->generateNonce(),
  232. 'nc' => 1,
  233. 'cnonce' => '123',
  234. 'qop' => 'auth',
  235. ];
  236. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  237. $request = $request->withEnv('PHP_AUTH_DIGEST', $this->digestHeader($data));
  238. $result = $this->auth->authenticate($request, $this->response);
  239. $expected = [
  240. 'id' => 1,
  241. 'username' => 'mariano',
  242. 'created' => new Time('2007-03-17 01:16:23'),
  243. 'updated' => new Time('2007-03-17 01:18:31'),
  244. ];
  245. $this->assertEquals($expected, $result);
  246. }
  247. /**
  248. * test authenticate success even when digest 'password' is a hidden field.
  249. *
  250. * @return void
  251. */
  252. public function testAuthenticateSuccessHiddenPasswordField()
  253. {
  254. $User = $this->getTableLocator()->get('Users');
  255. $User->setEntityClass(ProtectedUser::class);
  256. $request = new ServerRequest([
  257. 'url' => 'posts/index',
  258. 'environment' => ['REQUEST_METHOD' => 'GET'],
  259. ]);
  260. $data = [
  261. 'uri' => '/dir/index.html',
  262. 'nonce' => $this->generateNonce(),
  263. 'nc' => 1,
  264. 'cnonce' => '123',
  265. 'qop' => 'auth',
  266. ];
  267. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  268. $request = $request->withEnv('PHP_AUTH_DIGEST', $this->digestHeader($data));
  269. $result = $this->auth->authenticate($request, $this->response);
  270. $expected = [
  271. 'id' => 1,
  272. 'username' => 'mariano',
  273. 'created' => new Time('2007-03-17 01:16:23'),
  274. 'updated' => new Time('2007-03-17 01:18:31'),
  275. ];
  276. $this->assertEquals($expected, $result);
  277. }
  278. /**
  279. * test authenticate success
  280. *
  281. * @return void
  282. */
  283. public function testAuthenticateSuccessSimulatedRequestMethod()
  284. {
  285. $request = new ServerRequest([
  286. 'url' => 'posts/index',
  287. 'post' => ['_method' => 'PUT'],
  288. 'environment' => ['REQUEST_METHOD' => 'GET'],
  289. ]);
  290. $data = [
  291. 'username' => 'mariano',
  292. 'uri' => '/dir/index.html',
  293. 'nonce' => $this->generateNonce(),
  294. 'nc' => 1,
  295. 'cnonce' => '123',
  296. 'qop' => 'auth',
  297. ];
  298. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  299. $request = $request->withEnv('PHP_AUTH_DIGEST', $this->digestHeader($data));
  300. $result = $this->auth->authenticate($request, $this->response);
  301. $expected = [
  302. 'id' => 1,
  303. 'username' => 'mariano',
  304. 'created' => new Time('2007-03-17 01:16:23'),
  305. 'updated' => new Time('2007-03-17 01:18:31'),
  306. ];
  307. $this->assertEquals($expected, $result);
  308. }
  309. /**
  310. * test scope failure.
  311. *
  312. * @return void
  313. */
  314. public function testAuthenticateFailReChallenge()
  315. {
  316. $this->expectException(\Cake\Http\Exception\UnauthorizedException::class);
  317. $this->expectExceptionCode(401);
  318. $this->auth->setConfig('scope.username', 'nate');
  319. $request = new ServerRequest([
  320. 'url' => 'posts/index',
  321. 'environment' => ['REQUEST_METHOD' => 'GET'],
  322. ]);
  323. $data = [
  324. 'username' => 'invalid',
  325. 'uri' => '/dir/index.html',
  326. 'nonce' => $this->generateNonce(),
  327. 'nc' => 1,
  328. 'cnonce' => '123',
  329. 'qop' => 'auth',
  330. ];
  331. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  332. $request = $request->withEnv('PHP_AUTH_DIGEST', $this->digestHeader($data));
  333. $this->auth->unauthenticated($request, $this->response);
  334. }
  335. /**
  336. * testLoginHeaders method
  337. *
  338. * @return void
  339. */
  340. public function testLoginHeaders()
  341. {
  342. $request = new ServerRequest([
  343. 'environment' => ['SERVER_NAME' => 'localhost'],
  344. ]);
  345. $this->auth = new DigestAuthenticate($this->Collection, [
  346. 'realm' => 'localhost',
  347. ]);
  348. $result = $this->auth->loginHeaders($request);
  349. $this->assertRegexp(
  350. '/^Digest realm="localhost",qop="auth",nonce="[a-zA-Z0-9=]+",opaque="[a-f0-9]+"$/',
  351. $result['WWW-Authenticate']
  352. );
  353. }
  354. /**
  355. * testParseDigestAuthData method
  356. *
  357. * @return void
  358. */
  359. public function testParseAuthData()
  360. {
  361. $digest = <<<DIGEST
  362. Digest username="Mufasa",
  363. realm="testrealm@host.com",
  364. nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
  365. uri="/dir/index.html?query=string&value=some%20value",
  366. qop=auth,
  367. nc=00000001,
  368. cnonce="0a4f113b",
  369. response="6629fae49393a05397450978507c4ef1",
  370. opaque="5ccc069c403ebaf9f0171e9517f40e41"
  371. DIGEST;
  372. $expected = [
  373. 'username' => 'Mufasa',
  374. 'realm' => 'testrealm@host.com',
  375. 'nonce' => 'dcd98b7102dd2f0e8b11d0f600bfb0c093',
  376. 'uri' => '/dir/index.html?query=string&value=some%20value',
  377. 'qop' => 'auth',
  378. 'nc' => '00000001',
  379. 'cnonce' => '0a4f113b',
  380. 'response' => '6629fae49393a05397450978507c4ef1',
  381. 'opaque' => '5ccc069c403ebaf9f0171e9517f40e41',
  382. ];
  383. $result = $this->auth->parseAuthData($digest);
  384. $this->assertSame($expected, $result);
  385. $result = $this->auth->parseAuthData('');
  386. $this->assertNull($result);
  387. }
  388. /**
  389. * Test parsing a full URI. While not part of the spec some mobile clients will do it wrong.
  390. *
  391. * @return void
  392. */
  393. public function testParseAuthDataFullUri()
  394. {
  395. $digest = <<<DIGEST
  396. Digest username="admin",
  397. realm="192.168.0.2",
  398. nonce="53a7f9b83f61b",
  399. uri="http://192.168.0.2/pvcollection/sites/pull/HFD%200001.json#fragment",
  400. qop=auth,
  401. nc=00000001,
  402. cnonce="b85ff144e496e6e18d1c73020566ea3b",
  403. response="5894f5d9cd41d012bac09eeb89d2ddf2",
  404. opaque="6f65e91667cf98dd13464deaf2739fde"
  405. DIGEST;
  406. $expected = 'http://192.168.0.2/pvcollection/sites/pull/HFD%200001.json#fragment';
  407. $result = $this->auth->parseAuthData($digest);
  408. $this->assertSame($expected, $result['uri']);
  409. }
  410. /**
  411. * test parsing digest information with email addresses
  412. *
  413. * @return void
  414. */
  415. public function testParseAuthEmailAddress()
  416. {
  417. $digest = <<<DIGEST
  418. Digest username="mark@example.com",
  419. realm="testrealm@host.com",
  420. nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
  421. uri="/dir/index.html",
  422. qop=auth,
  423. nc=00000001,
  424. cnonce="0a4f113b",
  425. response="6629fae49393a05397450978507c4ef1",
  426. opaque="5ccc069c403ebaf9f0171e9517f40e41"
  427. DIGEST;
  428. $expected = [
  429. 'username' => 'mark@example.com',
  430. 'realm' => 'testrealm@host.com',
  431. 'nonce' => 'dcd98b7102dd2f0e8b11d0f600bfb0c093',
  432. 'uri' => '/dir/index.html',
  433. 'qop' => 'auth',
  434. 'nc' => '00000001',
  435. 'cnonce' => '0a4f113b',
  436. 'response' => '6629fae49393a05397450978507c4ef1',
  437. 'opaque' => '5ccc069c403ebaf9f0171e9517f40e41',
  438. ];
  439. $result = $this->auth->parseAuthData($digest);
  440. $this->assertSame($expected, $result);
  441. }
  442. /**
  443. * test password hashing
  444. *
  445. * @return void
  446. */
  447. public function testPassword()
  448. {
  449. $result = DigestAuthenticate::password('mark', 'password', 'localhost');
  450. $expected = md5('mark:localhost:password');
  451. $this->assertEquals($expected, $result);
  452. }
  453. /**
  454. * Generate a nonce for testing.
  455. *
  456. * @param string $secret The secret to use.
  457. * @param int $expires Time to live
  458. * @return string
  459. */
  460. protected function generateNonce($secret = null, $expires = 300, $time = null)
  461. {
  462. $secret = $secret ?: Configure::read('Security.salt');
  463. $time = $time ?: microtime(true);
  464. $expiryTime = $time + $expires;
  465. $signatureValue = hash_hmac('sha256', $expiryTime . ':' . $secret, $secret);
  466. $nonceValue = $expiryTime . ':' . $signatureValue;
  467. return base64_encode($nonceValue);
  468. }
  469. /**
  470. * Create a digest header string from an array of data.
  471. *
  472. * @param array $data the data to convert into a header.
  473. * @return string
  474. */
  475. protected function digestHeader($data)
  476. {
  477. $data += [
  478. 'username' => 'mariano',
  479. 'realm' => 'localhost',
  480. 'opaque' => '123abc',
  481. ];
  482. $digest = <<<DIGEST
  483. Digest username="{$data['username']}",
  484. realm="{$data['realm']}",
  485. nonce="{$data['nonce']}",
  486. uri="{$data['uri']}",
  487. qop={$data['qop']},
  488. nc={$data['nc']},
  489. cnonce="{$data['cnonce']}",
  490. response="{$data['response']}",
  491. opaque="{$data['opaque']}"
  492. DIGEST;
  493. return $digest;
  494. }
  495. }