DigestAuthenticateTest.php 15 KB

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