DigestAuthenticateTest.php 16 KB

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