DigestAuthenticateTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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\Response;
  22. use Cake\Http\ServerRequest;
  23. use Cake\I18n\Time;
  24. use Cake\Network\Exception\UnauthorizedException;
  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->config('userModel'));
  78. $this->assertEquals(['username' => 'user', 'password' => 'pass'], $object->config('fields'));
  79. $this->assertEquals(123456, $object->config('nonce'));
  80. $this->assertEquals(env('SERVER_NAME'), $object->config('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. * @expectedException \Cake\Network\Exception\UnauthorizedException
  98. * @expectedExceptionCode 401
  99. * @return void
  100. */
  101. public function testAuthenticateWrongUsername()
  102. {
  103. $request = new ServerRequest('posts/index');
  104. $request->addParams(['pass' => []]);
  105. $data = [
  106. 'username' => 'incorrect_user',
  107. 'realm' => 'localhost',
  108. 'nonce' => $this->generateNonce(),
  109. 'uri' => '/dir/index.html',
  110. 'qop' => 'auth',
  111. 'nc' => 0000001,
  112. 'cnonce' => '0a4f113b'
  113. ];
  114. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  115. $request->env('PHP_AUTH_DIGEST', $this->digestHeader($data));
  116. $this->auth->unauthenticated($request, $this->response);
  117. }
  118. /**
  119. * test that challenge headers are sent when no credentials are found.
  120. *
  121. * @return void
  122. */
  123. public function testAuthenticateChallenge()
  124. {
  125. $request = new ServerRequest([
  126. 'url' => 'posts/index',
  127. 'environment' => ['REQUEST_METHOD' => 'GET']
  128. ]);
  129. $request->addParams(['pass' => []]);
  130. try {
  131. $this->auth->unauthenticated($request, $this->response);
  132. } catch (UnauthorizedException $e) {
  133. }
  134. $this->assertNotEmpty($e);
  135. $header = $e->responseHeader()[0];
  136. $this->assertRegexp(
  137. '/^WWW\-Authenticate: Digest realm="localhost",qop="auth",nonce="[a-zA-Z0-9=]+",opaque="123abc"$/',
  138. $e->responseHeader()[0]
  139. );
  140. }
  141. /**
  142. * test that challenge headers include stale when the nonce is stale
  143. *
  144. * @return void
  145. */
  146. public function testAuthenticateChallengeIncludesStaleAttributeOnStaleNonce()
  147. {
  148. $request = new ServerRequest([
  149. 'url' => 'posts/index',
  150. 'environment' => ['REQUEST_METHOD' => 'GET']
  151. ]);
  152. $request->addParams(['pass' => []]);
  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->env('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()[0];
  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. $request->addParams(['pass' => []]);
  182. $data = [
  183. 'uri' => '/dir/index.html',
  184. 'nonce' => $this->generateNonce(null, 5, strtotime('-10 minutes')),
  185. 'nc' => 1,
  186. 'cnonce' => '123',
  187. 'qop' => 'auth',
  188. ];
  189. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  190. $request->env('PHP_AUTH_DIGEST', $this->digestHeader($data));
  191. $result = $this->auth->authenticate($request, $this->response);
  192. $this->assertFalse($result, 'Stale nonce should fail');
  193. }
  194. /**
  195. * Test that nonces are required.
  196. *
  197. * @return void
  198. */
  199. public function testAuthenticateValidUsernamePasswordNoNonce()
  200. {
  201. $request = new ServerRequest([
  202. 'url' => 'posts/index',
  203. 'environment' => ['REQUEST_METHOD' => 'GET']
  204. ]);
  205. $request->addParams(['pass' => []]);
  206. $data = [
  207. 'username' => 'mariano',
  208. 'realm' => 'localhos',
  209. 'uri' => '/dir/index.html',
  210. 'nonce' => '',
  211. 'nc' => 1,
  212. 'cnonce' => '123',
  213. 'qop' => 'auth',
  214. ];
  215. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  216. $request->env('PHP_AUTH_DIGEST', $this->digestHeader($data));
  217. $result = $this->auth->authenticate($request, $this->response);
  218. $this->assertFalse($result, 'Empty nonce should fail');
  219. }
  220. /**
  221. * test authenticate success
  222. *
  223. * @return void
  224. */
  225. public function testAuthenticateSuccess()
  226. {
  227. $request = new ServerRequest([
  228. 'url' => 'posts/index',
  229. 'environment' => ['REQUEST_METHOD' => 'GET']
  230. ]);
  231. $request->addParams(['pass' => []]);
  232. $data = [
  233. 'uri' => '/dir/index.html',
  234. 'nonce' => $this->generateNonce(),
  235. 'nc' => 1,
  236. 'cnonce' => '123',
  237. 'qop' => 'auth',
  238. ];
  239. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  240. $request->env('PHP_AUTH_DIGEST', $this->digestHeader($data));
  241. $result = $this->auth->authenticate($request, $this->response);
  242. $expected = [
  243. 'id' => 1,
  244. 'username' => 'mariano',
  245. 'created' => new Time('2007-03-17 01:16:23'),
  246. 'updated' => new Time('2007-03-17 01:18:31')
  247. ];
  248. $this->assertEquals($expected, $result);
  249. }
  250. /**
  251. * test authenticate success even when digest 'password' is a hidden field.
  252. *
  253. * @return void
  254. */
  255. public function testAuthenticateSuccessHiddenPasswordField()
  256. {
  257. $User = TableRegistry::get('Users');
  258. $User->setEntityClass(ProtectedUser::class);
  259. $request = new ServerRequest([
  260. 'url' => 'posts/index',
  261. 'environment' => ['REQUEST_METHOD' => 'GET']
  262. ]);
  263. $request->addParams(['pass' => []]);
  264. $data = [
  265. 'uri' => '/dir/index.html',
  266. 'nonce' => $this->generateNonce(),
  267. 'nc' => 1,
  268. 'cnonce' => '123',
  269. 'qop' => 'auth',
  270. ];
  271. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  272. $request->env('PHP_AUTH_DIGEST', $this->digestHeader($data));
  273. $result = $this->auth->authenticate($request, $this->response);
  274. $expected = [
  275. 'id' => 1,
  276. 'username' => 'mariano',
  277. 'created' => new Time('2007-03-17 01:16:23'),
  278. 'updated' => new Time('2007-03-17 01:18:31')
  279. ];
  280. $this->assertEquals($expected, $result);
  281. }
  282. /**
  283. * test authenticate success
  284. *
  285. * @return void
  286. */
  287. public function testAuthenticateSuccessSimulatedRequestMethod()
  288. {
  289. $request = new ServerRequest([
  290. 'url' => 'posts/index',
  291. 'post' => ['_method' => 'PUT'],
  292. 'environment' => ['REQUEST_METHOD' => 'GET']
  293. ]);
  294. $request->addParams(['pass' => []]);
  295. $data = [
  296. 'username' => 'mariano',
  297. 'uri' => '/dir/index.html',
  298. 'nonce' => $this->generateNonce(),
  299. 'nc' => 1,
  300. 'cnonce' => '123',
  301. 'qop' => 'auth',
  302. ];
  303. $data['response'] = $this->auth->generateResponseHash($data, '09faa9931501bf30f0d4253fa7763022', 'GET');
  304. $request->env('PHP_AUTH_DIGEST', $this->digestHeader($data));
  305. $result = $this->auth->authenticate($request, $this->response);
  306. $expected = [
  307. 'id' => 1,
  308. 'username' => 'mariano',
  309. 'created' => new Time('2007-03-17 01:16:23'),
  310. 'updated' => new Time('2007-03-17 01:18:31')
  311. ];
  312. $this->assertEquals($expected, $result);
  313. }
  314. /**
  315. * test scope failure.
  316. *
  317. * @expectedException \Cake\Network\Exception\UnauthorizedException
  318. * @expectedExceptionCode 401
  319. * @return void
  320. */
  321. public function testAuthenticateFailReChallenge()
  322. {
  323. $this->auth->config('scope.username', 'nate');
  324. $request = new ServerRequest([
  325. 'url' => 'posts/index',
  326. 'environment' => ['REQUEST_METHOD' => 'GET']
  327. ]);
  328. $request->addParams(['pass' => []]);
  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->env('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. '/^WWW\-Authenticate: Digest realm="localhost",qop="auth",nonce="[a-zA-Z0-9=]+",opaque="[a-f0-9]+"$/',
  357. $result
  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 ?: Configure::read('Security.salt');
  469. $time = $time ?: microtime(true);
  470. $expiryTime = $time + $expires;
  471. $signatureValue = hash_hmac('sha1', $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="mariano",
  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. }