DigestAuthenticateTest.php 16 KB

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