DigestAuthenticateTest.php 17 KB

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