DigestAuthenticateTest.php 17 KB

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