DigestAuthenticateTest.php 17 KB

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