DigestAuthenticateTest.php 16 KB

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