SecurityComponentTest.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Controller\Component;
  16. use Cake\Controller\Component\SecurityComponent;
  17. use Cake\Controller\Controller;
  18. use Cake\Controller\Exception\SecurityException;
  19. use Cake\Core\Configure;
  20. use Cake\Event\Event;
  21. use Cake\Network\Request;
  22. use Cake\Network\Session;
  23. use Cake\TestSuite\TestCase;
  24. use Cake\Utility\Security;
  25. /**
  26. * TestSecurityComponent
  27. *
  28. */
  29. class TestSecurityComponent extends SecurityComponent
  30. {
  31. /**
  32. * validatePost method
  33. *
  34. * @param Controller $controller
  35. * @return bool
  36. */
  37. public function validatePost(Controller $controller)
  38. {
  39. return $this->_validatePost($controller);
  40. }
  41. /**
  42. * authRequired method
  43. *
  44. * @param Controller $controller
  45. * @return bool
  46. */
  47. public function authRequired(Controller $controller)
  48. {
  49. return $this->_authRequired($controller);
  50. }
  51. }
  52. /**
  53. * SecurityTestController
  54. *
  55. */
  56. class SecurityTestController extends Controller
  57. {
  58. /**
  59. * components property
  60. *
  61. * @var array
  62. */
  63. public $components = [
  64. 'TestSecurity' => ['className' => 'Cake\Test\TestCase\Controller\Component\TestSecurityComponent']
  65. ];
  66. /**
  67. * failed property
  68. *
  69. * @var bool
  70. */
  71. public $failed = false;
  72. /**
  73. * Used for keeping track of headers in test
  74. *
  75. * @var array
  76. */
  77. public $testHeaders = [];
  78. /**
  79. * fail method
  80. *
  81. * @return void
  82. */
  83. public function fail()
  84. {
  85. $this->failed = true;
  86. }
  87. /**
  88. * redirect method
  89. *
  90. * @param string|array $url
  91. * @param mixed $status
  92. * @param mixed $exit
  93. * @return void
  94. */
  95. public function redirect($url, $status = null, $exit = true)
  96. {
  97. return $status;
  98. }
  99. /**
  100. * Convenience method for header()
  101. *
  102. * @param string $status
  103. * @return void
  104. */
  105. public function header($status)
  106. {
  107. $this->testHeaders[] = $status;
  108. }
  109. }
  110. /**
  111. * SecurityComponentTest class
  112. *
  113. * @property SecurityComponent Security
  114. * @property SecurityTestController Controller
  115. */
  116. class SecurityComponentTest extends TestCase
  117. {
  118. /**
  119. * Controller property
  120. *
  121. * @var SecurityTestController
  122. */
  123. public $Controller;
  124. /**
  125. * oldSalt property
  126. *
  127. * @var string
  128. */
  129. public $oldSalt;
  130. /**
  131. * setUp method
  132. *
  133. * @return void
  134. */
  135. public function setUp()
  136. {
  137. parent::setUp();
  138. $session = new Session();
  139. $request = $this->getMockBuilder('Cake\Network\Request')
  140. ->setMethods(['here'])
  141. ->setConstructorArgs(['posts/index'])
  142. ->getMock();
  143. $request->addParams(['controller' => 'posts', 'action' => 'index']);
  144. $request->session($session);
  145. $request->expects($this->any())
  146. ->method('here')
  147. ->will($this->returnValue('/articles/index'));
  148. $this->Controller = new SecurityTestController($request);
  149. $this->Controller->Security = $this->Controller->TestSecurity;
  150. $this->Controller->Security->config('blackHoleCallback', 'fail');
  151. $this->Security = $this->Controller->Security;
  152. $this->Security->session = $session;
  153. Security::salt('foo!');
  154. }
  155. /**
  156. * Tear-down method. Resets environment state.
  157. *
  158. * @return void
  159. */
  160. public function tearDown()
  161. {
  162. parent::tearDown();
  163. $this->Security->session->delete('_Token');
  164. unset($this->Controller->Security);
  165. unset($this->Controller->Component);
  166. unset($this->Controller);
  167. }
  168. public function validatePost($expectedException = null, $expectedExceptionMessage = null)
  169. {
  170. try {
  171. return $this->Controller->Security->validatePost($this->Controller);
  172. } catch (SecurityException $ex) {
  173. $this->assertInstanceOf('Cake\\Controller\\Exception\\' . $expectedException, $ex);
  174. $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
  175. return false;
  176. }
  177. }
  178. /**
  179. * Test that requests are still blackholed when controller has incorrect
  180. * visibility keyword in the blackhole callback
  181. *
  182. * @expectedException \Cake\Network\Exception\BadRequestException
  183. * @return void
  184. * @triggers Controller.startup $Controller, $this->Controller
  185. */
  186. public function testBlackholeWithBrokenCallback()
  187. {
  188. $request = new Request([
  189. 'url' => 'posts/index',
  190. 'session' => $this->Security->session
  191. ]);
  192. $request->addParams([
  193. 'controller' => 'posts',
  194. 'action' => 'index'
  195. ]);
  196. $Controller = new \TestApp\Controller\SomePagesController($request);
  197. $event = new Event('Controller.startup', $Controller, $this->Controller);
  198. $Security = new SecurityComponent($Controller->components());
  199. $Security->config('blackHoleCallback', '_fail');
  200. $Security->startup($event);
  201. $Security->blackHole($Controller, 'csrf');
  202. }
  203. /**
  204. * Ensure that directly requesting the blackholeCallback as the controller
  205. * action results in an exception.
  206. *
  207. * @return void
  208. * @triggers Controller.startup $this->Controller
  209. */
  210. public function testExceptionWhenActionIsBlackholeCallback()
  211. {
  212. $this->Controller->request->addParams([
  213. 'controller' => 'posts',
  214. 'action' => 'fail'
  215. ]);
  216. $event = new Event('Controller.startup', $this->Controller);
  217. $this->assertFalse($this->Controller->failed);
  218. $this->Controller->Security->startup($event);
  219. $this->assertTrue($this->Controller->failed, 'Request was blackholed.');
  220. }
  221. /**
  222. * test that initialize can set properties.
  223. *
  224. * @return void
  225. */
  226. public function testConstructorSettingProperties()
  227. {
  228. $settings = [
  229. 'requireSecure' => ['update_account'],
  230. 'validatePost' => false,
  231. ];
  232. $Security = new SecurityComponent($this->Controller->components(), $settings);
  233. $this->assertEquals($Security->validatePost, $settings['validatePost']);
  234. }
  235. /**
  236. * testStartup method
  237. *
  238. * @return void
  239. * @triggers Controller.startup $this->Controller
  240. */
  241. public function testStartup()
  242. {
  243. $event = new Event('Controller.startup', $this->Controller);
  244. $this->Controller->Security->startup($event);
  245. $this->assertTrue($this->Security->session->check('_Token'));
  246. }
  247. /**
  248. * testRequireSecureFail method
  249. *
  250. * @return void
  251. * @triggers Controller.startup $this->Controller
  252. */
  253. public function testRequireSecureFail()
  254. {
  255. $_SERVER['HTTPS'] = 'off';
  256. $_SERVER['REQUEST_METHOD'] = 'POST';
  257. $this->Controller->request['action'] = 'posted';
  258. $event = new Event('Controller.startup', $this->Controller);
  259. $this->Controller->Security->requireSecure(['posted']);
  260. $this->Controller->Security->startup($event);
  261. $this->assertTrue($this->Controller->failed);
  262. }
  263. /**
  264. * testRequireSecureSucceed method
  265. *
  266. * @return void
  267. * @triggers Controller.startup $this->Controller
  268. */
  269. public function testRequireSecureSucceed()
  270. {
  271. $_SERVER['HTTPS'] = 'on';
  272. $_SERVER['REQUEST_METHOD'] = 'Secure';
  273. $this->Controller->request['action'] = 'posted';
  274. $event = new Event('Controller.startup', $this->Controller);
  275. $this->Controller->Security->requireSecure('posted');
  276. $this->Controller->Security->startup($event);
  277. $this->assertFalse($this->Controller->failed);
  278. }
  279. /**
  280. * testRequireSecureEmptyFail method
  281. *
  282. * @return void
  283. * @triggers Controller.startup $this->Controller
  284. */
  285. public function testRequireSecureEmptyFail()
  286. {
  287. $_SERVER['HTTPS'] = 'off';
  288. $_SERVER['REQUEST_METHOD'] = 'POST';
  289. $this->Controller->request['action'] = 'posted';
  290. $event = new Event('Controller.startup', $this->Controller);
  291. $this->Controller->Security->requireSecure();
  292. $this->Controller->Security->startup($event);
  293. $this->assertTrue($this->Controller->failed);
  294. }
  295. /**
  296. * testRequireSecureEmptySucceed method
  297. *
  298. * @return void
  299. * @triggers Controller.startup $this->Controller
  300. */
  301. public function testRequireSecureEmptySucceed()
  302. {
  303. $_SERVER['HTTPS'] = 'on';
  304. $_SERVER['REQUEST_METHOD'] = 'Secure';
  305. $this->Controller->request['action'] = 'posted';
  306. $event = new Event('Controller.startup', $this->Controller);
  307. $this->Controller->Security->requireSecure();
  308. $this->Controller->Security->startup($event);
  309. $this->assertFalse($this->Controller->failed);
  310. }
  311. /**
  312. * testRequireAuthFail method
  313. *
  314. * @return void
  315. * @triggers Controller.startup $this->Controller
  316. */
  317. public function testRequireAuthFail()
  318. {
  319. $event = new Event('Controller.startup', $this->Controller);
  320. $_SERVER['REQUEST_METHOD'] = 'AUTH';
  321. $this->Controller->request['action'] = 'posted';
  322. $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
  323. $this->Controller->Security->requireAuth(['posted']);
  324. $this->Controller->Security->startup($event);
  325. $this->assertTrue($this->Controller->failed);
  326. $this->Security->session->write('_Token', ['allowedControllers' => []]);
  327. $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
  328. $this->Controller->request['action'] = 'posted';
  329. $this->Controller->Security->requireAuth('posted');
  330. $this->Controller->Security->startup($event);
  331. $this->assertTrue($this->Controller->failed);
  332. $this->Security->session->write('_Token', [
  333. 'allowedControllers' => ['SecurityTest'], 'allowedActions' => ['posted2']
  334. ]);
  335. $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
  336. $this->Controller->request['action'] = 'posted';
  337. $this->Controller->Security->requireAuth('posted');
  338. $this->Controller->Security->startup($event);
  339. $this->assertTrue($this->Controller->failed);
  340. }
  341. /**
  342. * testRequireAuthSucceed method
  343. *
  344. * @return void
  345. * @triggers Controller.startup $this->Controller
  346. */
  347. public function testRequireAuthSucceed()
  348. {
  349. $_SERVER['REQUEST_METHOD'] = 'AUTH';
  350. $this->Controller->Security->config('validatePost', false);
  351. $event = new Event('Controller.startup', $this->Controller);
  352. $this->Controller->request['action'] = 'posted';
  353. $this->Controller->Security->requireAuth('posted');
  354. $this->Controller->Security->startup($event);
  355. $this->assertFalse($this->Controller->failed);
  356. $this->Controller->Security->session->write('_Token', [
  357. 'allowedControllers' => ['SecurityTest'],
  358. 'allowedActions' => ['posted'],
  359. ]);
  360. $this->Controller->request['controller'] = 'SecurityTest';
  361. $this->Controller->request['action'] = 'posted';
  362. $this->Controller->request->data = [
  363. 'username' => 'willy',
  364. 'password' => 'somePass',
  365. '_Token' => ''
  366. ];
  367. $this->Controller->action = 'posted';
  368. $this->Controller->Security->requireAuth('posted');
  369. $this->Controller->Security->startup($event);
  370. $this->assertFalse($this->Controller->failed);
  371. }
  372. /**
  373. * Simple hash validation test
  374. *
  375. * @return void
  376. * @triggers Controller.startup $this->Controller
  377. */
  378. public function testValidatePost()
  379. {
  380. $event = new Event('Controller.startup', $this->Controller);
  381. $this->Controller->Security->startup($event);
  382. $fields = '68730b0747d4889ec2766f9117405f9635f5fd5e%3AModel.valid';
  383. $unlocked = '';
  384. $debug = '';
  385. $this->Controller->request->data = [
  386. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  387. '_Token' => compact('fields', 'unlocked', 'debug'),
  388. ];
  389. $this->assertTrue($this->validatePost());
  390. }
  391. /**
  392. * Test that validatePost fires on GET with request data.
  393. * This could happen when method overriding is used.
  394. *
  395. * @return void
  396. * @triggers Controller.startup $this->Controller
  397. */
  398. public function testValidatePostOnGetWithData()
  399. {
  400. $event = new Event('Controller.startup', $this->Controller);
  401. $this->Controller->Security->startup($event);
  402. $fields = 'an-invalid-token';
  403. $unlocked = '';
  404. $debug = urlencode(json_encode([
  405. 'some-action',
  406. [],
  407. []
  408. ]));
  409. $this->Controller->request->env('REQUEST_METHOD', 'GET');
  410. $this->Controller->request->data = [
  411. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  412. '_Token' => compact('fields', 'unlocked', 'debug')
  413. ];
  414. $this->Controller->Security->startup($event);
  415. $this->assertTrue($this->Controller->failed);
  416. }
  417. /**
  418. * Test that validatePost fails if you are missing the session information.
  419. *
  420. * @return void
  421. * @triggers Controller.startup $this->Controller
  422. */
  423. public function testValidatePostNoSession()
  424. {
  425. $event = new Event('Controller.startup', $this->Controller);
  426. $this->Controller->Security->startup($event);
  427. $this->Security->session->delete('_Token');
  428. $unlocked = '';
  429. $debug = urlencode(json_encode([
  430. '/articles/index',
  431. [],
  432. []
  433. ]));
  434. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid';
  435. $this->Controller->request->data = [
  436. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  437. '_Token' => compact('fields', 'unlocked', 'debug')
  438. ];
  439. $this->assertFalse($this->validatePost('AuthSecurityException', 'Unexpected field \'Model.password\' in POST data, Unexpected field \'Model.username\' in POST data'));
  440. }
  441. /**
  442. * Test that validatePost fails if you are missing unlocked in request data.
  443. *
  444. * @return void
  445. * @triggers Controller.startup $this->Controller
  446. */
  447. public function testValidatePostNoUnlockedInRequestData()
  448. {
  449. $event = new Event('Controller.startup', $this->Controller);
  450. $this->Controller->Security->startup($event);
  451. $this->Security->session->delete('_Token');
  452. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid';
  453. $this->Controller->request->data = [
  454. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  455. '_Token' => compact('fields')
  456. ];
  457. $this->assertFalse($this->validatePost('AuthSecurityException', '\'_Token.unlocked\' was not found in request data.'));
  458. }
  459. /**
  460. * test that validatePost fails if any of its required fields are missing.
  461. *
  462. * @return void
  463. * @triggers Controller.startup $this->Controller
  464. */
  465. public function testValidatePostFormHacking()
  466. {
  467. $event = new Event('Controller.startup', $this->Controller);
  468. $this->Controller->Security->startup($event);
  469. $unlocked = '';
  470. $this->Controller->request->data = [
  471. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  472. '_Token' => compact('unlocked')
  473. ];
  474. $result = $this->validatePost('AuthSecurityException', '\'_Token.fields\' was not found in request data.');
  475. $this->assertFalse($result, 'validatePost passed when fields were missing. %s');
  476. }
  477. /**
  478. * Test that objects can't be passed into the serialized string. This was a vector for RFI and LFI
  479. * attacks. Thanks to Felix Wilhelm
  480. *
  481. * @return void
  482. * @triggers Controller.startup $this->Controller
  483. */
  484. public function testValidatePostObjectDeserialize()
  485. {
  486. $event = new Event('Controller.startup', $this->Controller);
  487. $this->Controller->Security->startup($event);
  488. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877';
  489. $unlocked = '';
  490. $debug = urlencode(json_encode([
  491. '/articles/index',
  492. ['Model.password', 'Model.username', 'Model.valid'],
  493. []
  494. ]));
  495. // a corrupted serialized object, so we can see if it ever gets to deserialize
  496. $attack = 'O:3:"App":1:{s:5:"__map";a:1:{s:3:"foo";s:7:"Hacked!";s:1:"fail"}}';
  497. $fields .= urlencode(':' . str_rot13($attack));
  498. $this->Controller->request->data = [
  499. 'Model' => ['username' => 'mark', 'password' => 'foo', 'valid' => '0'],
  500. '_Token' => compact('fields', 'unlocked', 'debug')
  501. ];
  502. $result = $this->validatePost('SecurityException', 'Bad Request');
  503. $this->assertFalse($result, 'validatePost passed when key was missing. %s');
  504. }
  505. /**
  506. * Tests validation post data ignores `_csrfToken`.
  507. *
  508. * @return void
  509. * @triggers Controller.startup $this->Controller
  510. */
  511. public function testValidatePostIgnoresCsrfToken()
  512. {
  513. $event = new Event('Controller.startup', $this->Controller);
  514. $this->Controller->Security->startup($event);
  515. $fields = '8e26ef05379e5402c2c619f37ee91152333a0264%3A';
  516. $unlocked = '';
  517. $debug = 'not used';
  518. $this->Controller->request->data = [
  519. '_csrfToken' => 'abc123',
  520. 'Model' => ['multi_field' => ['1', '3']],
  521. '_Token' => compact('fields', 'unlocked', 'debug')
  522. ];
  523. $this->assertTrue($this->validatePost());
  524. }
  525. /**
  526. * Tests validation of checkbox arrays
  527. *
  528. * @return void
  529. * @triggers Controller.startup $this->Controller
  530. */
  531. public function testValidatePostArray()
  532. {
  533. $event = new Event('Controller.startup', $this->Controller);
  534. $this->Controller->Security->startup($event);
  535. $fields = '8e26ef05379e5402c2c619f37ee91152333a0264%3A';
  536. $unlocked = '';
  537. $debug = urlencode(json_encode([
  538. 'some-action',
  539. [],
  540. []
  541. ]));
  542. $this->Controller->request->data = [
  543. 'Model' => ['multi_field' => ['1', '3']],
  544. '_Token' => compact('fields', 'unlocked', 'debug')
  545. ];
  546. $this->assertTrue($this->validatePost());
  547. $this->Controller->request->data = [
  548. 'Model' => ['multi_field' => [12 => '1', 20 => '3']],
  549. '_Token' => compact('fields', 'unlocked', 'debug')
  550. ];
  551. $this->assertTrue($this->validatePost());
  552. }
  553. /**
  554. * Tests validation of integer field names.
  555. *
  556. * @return void
  557. */
  558. public function testValidateIntFieldName()
  559. {
  560. $event = new Event('Controller.startup', $this->Controller);
  561. $this->Controller->Security->startup($event);
  562. $fields = '4a221010dd7a23f7166cb10c38bc21d81341c387%3A';
  563. $unlocked = '';
  564. $debug = urlencode(json_encode([
  565. 'some-action',
  566. [],
  567. []
  568. ]));
  569. $this->Controller->request->data = [
  570. 1 => 'value,',
  571. '_Token' => compact('fields', 'unlocked', 'debug')
  572. ];
  573. $this->assertTrue($this->validatePost());
  574. }
  575. /**
  576. * testValidatePostNoModel method
  577. *
  578. * @return void
  579. * @triggers Controller.startup $this->Controller
  580. */
  581. public function testValidatePostNoModel()
  582. {
  583. $event = new Event('Controller.startup', $this->Controller);
  584. $this->Controller->Security->startup($event);
  585. $fields = 'a1c3724b7ba85e7022413611e30ba2c6181d5aba%3A';
  586. $unlocked = '';
  587. $debug = 'not used';
  588. $this->Controller->request->data = [
  589. 'anything' => 'some_data',
  590. '_Token' => compact('fields', 'unlocked', 'debug')
  591. ];
  592. $result = $this->validatePost();
  593. $this->assertTrue($result);
  594. }
  595. /**
  596. * testValidatePostSimple method
  597. *
  598. * @return void
  599. * @triggers Controller.startup $this->Controller
  600. */
  601. public function testValidatePostSimple()
  602. {
  603. $event = new Event('Controller.startup', $this->Controller);
  604. $this->Controller->Security->startup($event);
  605. $fields = 'b0914d06dfb04abf1fada53e16810e87d157950b%3A';
  606. $unlocked = '';
  607. $debug = 'not used';
  608. $this->Controller->request->data = [
  609. 'Model' => ['username' => '', 'password' => ''],
  610. '_Token' => compact('fields', 'unlocked', 'debug')
  611. ];
  612. $result = $this->validatePost();
  613. $this->assertTrue($result);
  614. }
  615. /**
  616. * Tests hash validation for multiple records, including locked fields
  617. *
  618. * @return void
  619. * @triggers Controller.startup $this->Controller
  620. */
  621. public function testValidatePostComplex()
  622. {
  623. $event = new Event('Controller.startup', $this->Controller);
  624. $this->Controller->Security->startup($event);
  625. $fields = 'b65c7463e44a61d8d2eaecce2c265b406c9c4742%3AAddresses.0.id%7CAddresses.1.id';
  626. $unlocked = '';
  627. $debug = 'not used';
  628. $this->Controller->request->data = [
  629. 'Addresses' => [
  630. '0' => [
  631. 'id' => '123456', 'title' => '', 'first_name' => '', 'last_name' => '',
  632. 'address' => '', 'city' => '', 'phone' => '', 'primary' => ''
  633. ],
  634. '1' => [
  635. 'id' => '654321', 'title' => '', 'first_name' => '', 'last_name' => '',
  636. 'address' => '', 'city' => '', 'phone' => '', 'primary' => ''
  637. ]
  638. ],
  639. '_Token' => compact('fields', 'unlocked', 'debug')
  640. ];
  641. $result = $this->validatePost();
  642. $this->assertTrue($result);
  643. }
  644. /**
  645. * test ValidatePost with multiple select elements.
  646. *
  647. * @return void
  648. * @triggers Controller.startup $this->Controller
  649. */
  650. public function testValidatePostMultipleSelect()
  651. {
  652. $event = new Event('Controller.startup', $this->Controller);
  653. $this->Controller->Security->startup($event);
  654. $fields = '8d8da68ba03b3d6e7e145b948abfe26741422169%3A';
  655. $unlocked = '';
  656. $debug = 'not used';
  657. $this->Controller->request->data = [
  658. 'Tag' => ['Tag' => [1, 2]],
  659. '_Token' => compact('fields', 'unlocked', 'debug'),
  660. ];
  661. $result = $this->validatePost();
  662. $this->assertTrue($result);
  663. $this->Controller->request->data = [
  664. 'Tag' => ['Tag' => [1, 2, 3]],
  665. '_Token' => compact('fields', 'unlocked', 'debug'),
  666. ];
  667. $result = $this->validatePost();
  668. $this->assertTrue($result);
  669. $this->Controller->request->data = [
  670. 'Tag' => ['Tag' => [1, 2, 3, 4]],
  671. '_Token' => compact('fields', 'unlocked', 'debug'),
  672. ];
  673. $result = $this->validatePost();
  674. $this->assertTrue($result);
  675. $fields = 'eae2adda1628b771a30cc133342d16220c6520fe%3A';
  676. $this->Controller->request->data = [
  677. 'User.password' => 'bar', 'User.name' => 'foo', 'User.is_valid' => '1',
  678. 'Tag' => ['Tag' => [1]],
  679. '_Token' => compact('fields', 'unlocked', 'debug'),
  680. ];
  681. $result = $this->validatePost();
  682. $this->assertTrue($result);
  683. }
  684. /**
  685. * testValidatePostCheckbox method
  686. *
  687. * First block tests un-checked checkbox
  688. * Second block tests checked checkbox
  689. *
  690. * @return void
  691. * @triggers Controller.startup $this->Controller
  692. */
  693. public function testValidatePostCheckbox()
  694. {
  695. $event = new Event('Controller.startup', $this->Controller);
  696. $this->Controller->Security->startup($event);
  697. $fields = '68730b0747d4889ec2766f9117405f9635f5fd5e%3AModel.valid';
  698. $unlocked = '';
  699. $debug = 'not used';
  700. $this->Controller->request->data = [
  701. 'Model' => ['username' => '', 'password' => '', 'valid' => '0'],
  702. '_Token' => compact('fields', 'unlocked', 'debug'),
  703. ];
  704. $result = $this->validatePost();
  705. $this->assertTrue($result);
  706. $fields = 'f63e4a69b2edd31f064e8e602a04dd59307cfe9c%3A';
  707. $this->Controller->request->data = [
  708. 'Model' => ['username' => '', 'password' => '', 'valid' => '0'],
  709. '_Token' => compact('fields', 'unlocked', 'debug'),
  710. ];
  711. $result = $this->validatePost();
  712. $this->assertTrue($result);
  713. $this->Controller->request->data = [];
  714. $this->Controller->Security->startup($event);
  715. $this->Controller->request->data = [
  716. 'Model' => ['username' => '', 'password' => '', 'valid' => '0'],
  717. '_Token' => compact('fields', 'unlocked', 'debug'),
  718. ];
  719. $result = $this->validatePost();
  720. $this->assertTrue($result);
  721. }
  722. /**
  723. * testValidatePostHidden method
  724. *
  725. * @return void
  726. * @triggers Controller.startup $this->Controller
  727. */
  728. public function testValidatePostHidden()
  729. {
  730. $event = new Event('Controller.startup', $this->Controller);
  731. $this->Controller->Security->startup($event);
  732. $fields = '973a8939a68ac014cc6f7666cec9aa6268507350%3AModel.hidden%7CModel.other_hidden';
  733. $unlocked = '';
  734. $debug = 'not used';
  735. $this->Controller->request->data = [
  736. 'Model' => [
  737. 'username' => '', 'password' => '', 'hidden' => '0',
  738. 'other_hidden' => 'some hidden value'
  739. ],
  740. '_Token' => compact('fields', 'unlocked', 'debug'),
  741. ];
  742. $result = $this->validatePost();
  743. $this->assertTrue($result);
  744. }
  745. /**
  746. * testValidatePostWithDisabledFields method
  747. *
  748. * @return void
  749. * @triggers Controller.startup $this->Controller
  750. */
  751. public function testValidatePostWithDisabledFields()
  752. {
  753. $event = new Event('Controller.startup', $this->Controller);
  754. $this->Controller->Security->config('disabledFields', ['Model.username', 'Model.password']);
  755. $this->Controller->Security->startup($event);
  756. $fields = '1c59acfbca98bd870c11fb544d545cbf23215880%3AModel.hidden';
  757. $unlocked = '';
  758. $debug = 'not used';
  759. $this->Controller->request->data = [
  760. 'Model' => [
  761. 'username' => '', 'password' => '', 'hidden' => '0'
  762. ],
  763. '_Token' => compact('fields', 'unlocked', 'debug'),
  764. ];
  765. $result = $this->validatePost();
  766. $this->assertTrue($result);
  767. }
  768. /**
  769. * test validating post data with posted unlocked fields.
  770. *
  771. * @return void
  772. * @triggers Controller.startup $this->Controller
  773. */
  774. public function testValidatePostDisabledFieldsInData()
  775. {
  776. $event = new Event('Controller.startup', $this->Controller);
  777. $this->Controller->Security->startup($event);
  778. $unlocked = 'Model.username';
  779. $fields = ['Model.hidden', 'Model.password'];
  780. $fields = urlencode(Security::hash('/articles/index' . serialize($fields) . $unlocked . Security::salt()));
  781. $debug = 'not used';
  782. $this->Controller->request->data = [
  783. 'Model' => [
  784. 'username' => 'mark',
  785. 'password' => 'sekret',
  786. 'hidden' => '0'
  787. ],
  788. '_Token' => compact('fields', 'unlocked', 'debug'),
  789. ];
  790. $result = $this->validatePost();
  791. $this->assertTrue($result);
  792. }
  793. /**
  794. * test that missing 'unlocked' input causes failure
  795. *
  796. * @return void
  797. * @triggers Controller.startup $this->Controller
  798. */
  799. public function testValidatePostFailNoDisabled()
  800. {
  801. $event = new Event('Controller.startup', $this->Controller);
  802. $this->Controller->Security->startup($event);
  803. $fields = ['Model.hidden', 'Model.password', 'Model.username'];
  804. $fields = urlencode(Security::hash(serialize($fields) . Security::salt()));
  805. $this->Controller->request->data = [
  806. 'Model' => [
  807. 'username' => 'mark',
  808. 'password' => 'sekret',
  809. 'hidden' => '0'
  810. ],
  811. '_Token' => compact('fields')
  812. ];
  813. $result = $this->validatePost('SecurityException', '\'_Token.unlocked\' was not found in request data.');
  814. $this->assertFalse($result);
  815. }
  816. /**
  817. * test that missing 'debug' input causes failure
  818. *
  819. * @return void
  820. * @triggers Controller.startup $this->Controller
  821. */
  822. public function testValidatePostFailNoDebug()
  823. {
  824. $event = new Event('Controller.startup', $this->Controller);
  825. $this->Controller->Security->startup($event);
  826. $fields = ['Model.hidden', 'Model.password', 'Model.username'];
  827. $fields = urlencode(Security::hash(serialize($fields) . Security::salt()));
  828. $unlocked = '';
  829. $this->Controller->request->data = [
  830. 'Model' => [
  831. 'username' => 'mark',
  832. 'password' => 'sekret',
  833. 'hidden' => '0'
  834. ],
  835. '_Token' => compact('fields', 'unlocked')
  836. ];
  837. $result = $this->validatePost('SecurityException', '\'_Token.debug\' was not found in request data.');
  838. $this->assertFalse($result);
  839. }
  840. /**
  841. * test that missing 'debug' input is not the problem when debug mode disabled
  842. *
  843. * @return void
  844. * @triggers Controller.startup $this->Controller
  845. */
  846. public function testValidatePostFailNoDebugMode()
  847. {
  848. $event = new Event('Controller.startup', $this->Controller);
  849. $this->Controller->Security->startup($event);
  850. $fields = ['Model.hidden', 'Model.password', 'Model.username'];
  851. $fields = urlencode(Security::hash(serialize($fields) . Security::salt()));
  852. $unlocked = '';
  853. $this->Controller->request->data = [
  854. 'Model' => [
  855. 'username' => 'mark',
  856. 'password' => 'sekret',
  857. 'hidden' => '0'
  858. ],
  859. '_Token' => compact('fields', 'unlocked')
  860. ];
  861. Configure::write('debug', false);
  862. $result = $this->validatePost('SecurityException', 'The request has been black-holed');
  863. }
  864. /**
  865. * Test that validatePost fails when unlocked fields are changed.
  866. *
  867. * @return void
  868. * @triggers Controller.startup $this->Controller
  869. */
  870. public function testValidatePostFailDisabledFieldTampering()
  871. {
  872. $event = new Event('Controller.startup', $this->Controller);
  873. $this->Controller->Security->startup($event);
  874. $unlocked = 'Model.username';
  875. $fields = ['Model.hidden', 'Model.password'];
  876. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  877. $debug = urlencode(json_encode([
  878. '/articles/index',
  879. ['Model.hidden', 'Model.password'],
  880. ['Model.username']
  881. ]));
  882. // Tamper the values.
  883. $unlocked = 'Model.username|Model.password';
  884. $this->Controller->request->data = [
  885. 'Model' => [
  886. 'username' => 'mark',
  887. 'password' => 'sekret',
  888. 'hidden' => '0'
  889. ],
  890. '_Token' => compact('fields', 'unlocked', 'debug')
  891. ];
  892. $result = $this->validatePost('SecurityException', 'Missing field \'Model.password\' in POST data, Unexpected unlocked field \'Model.password\' in POST data');
  893. $this->assertFalse($result);
  894. }
  895. /**
  896. * testValidateHiddenMultipleModel method
  897. *
  898. * @return void
  899. * @triggers Controller.startup $this->Controller
  900. */
  901. public function testValidateHiddenMultipleModel()
  902. {
  903. $event = new Event('Controller.startup', $this->Controller);
  904. $this->Controller->Security->startup($event);
  905. $fields = '075ca6c26c38a09a78d871201df89faf52cbbeb8%3AModel.valid%7CModel2.valid%7CModel3.valid';
  906. $unlocked = '';
  907. $debug = 'not used';
  908. $this->Controller->request->data = [
  909. 'Model' => ['username' => '', 'password' => '', 'valid' => '0'],
  910. 'Model2' => ['valid' => '0'],
  911. 'Model3' => ['valid' => '0'],
  912. '_Token' => compact('fields', 'unlocked', 'debug'),
  913. ];
  914. $result = $this->validatePost();
  915. $this->assertTrue($result);
  916. }
  917. /**
  918. * testValidateHasManyModel method
  919. *
  920. * @return void
  921. * @triggers Controller.startup $this->Controller
  922. */
  923. public function testValidateHasManyModel()
  924. {
  925. $event = new Event('Controller.startup', $this->Controller);
  926. $this->Controller->Security->startup($event);
  927. $fields = '24a753fb62ef7839389987b58e3f7108f564e529%3AModel.0.hidden%7CModel.0.valid';
  928. $fields .= '%7CModel.1.hidden%7CModel.1.valid';
  929. $unlocked = '';
  930. $debug = 'not used';
  931. $this->Controller->request->data = [
  932. 'Model' => [
  933. [
  934. 'username' => 'username', 'password' => 'password',
  935. 'hidden' => 'value', 'valid' => '0'
  936. ],
  937. [
  938. 'username' => 'username', 'password' => 'password',
  939. 'hidden' => 'value', 'valid' => '0'
  940. ]
  941. ],
  942. '_Token' => compact('fields', 'unlocked', 'debug'),
  943. ];
  944. $result = $this->validatePost();
  945. $this->assertTrue($result);
  946. }
  947. /**
  948. * testValidateHasManyRecordsPass method
  949. *
  950. * @return void
  951. * @triggers Controller.startup $this->Controller
  952. */
  953. public function testValidateHasManyRecordsPass()
  954. {
  955. $event = new Event('Controller.startup', $this->Controller);
  956. $this->Controller->Security->startup($event);
  957. $fields = '8f7d82bf7656cf068822d9bdab109ebed1be1825%3AAddress.0.id%7CAddress.0.primary%7C';
  958. $fields .= 'Address.1.id%7CAddress.1.primary';
  959. $unlocked = '';
  960. $debug = 'not used';
  961. $this->Controller->request->data = [
  962. 'Address' => [
  963. 0 => [
  964. 'id' => '123',
  965. 'title' => 'home',
  966. 'first_name' => 'Bilbo',
  967. 'last_name' => 'Baggins',
  968. 'address' => '23 Bag end way',
  969. 'city' => 'the shire',
  970. 'phone' => 'N/A',
  971. 'primary' => '1',
  972. ],
  973. 1 => [
  974. 'id' => '124',
  975. 'title' => 'home',
  976. 'first_name' => 'Frodo',
  977. 'last_name' => 'Baggins',
  978. 'address' => '50 Bag end way',
  979. 'city' => 'the shire',
  980. 'phone' => 'N/A',
  981. 'primary' => '1'
  982. ]
  983. ],
  984. '_Token' => compact('fields', 'unlocked', 'debug'),
  985. ];
  986. $result = $this->validatePost();
  987. $this->assertTrue($result);
  988. }
  989. /**
  990. * Test that values like Foo.0.1
  991. *
  992. * @return void
  993. * @triggers Controller.startup $this->Controller
  994. */
  995. public function testValidateNestedNumericSets()
  996. {
  997. $event = new Event('Controller.startup', $this->Controller);
  998. $this->Controller->Security->startup($event);
  999. $unlocked = '';
  1000. $hashFields = ['TaxonomyData'];
  1001. $fields = urlencode(Security::hash('/articles/index' . serialize($hashFields) . $unlocked . Security::salt()));
  1002. $debug = 'not used';
  1003. $this->Controller->request->data = [
  1004. 'TaxonomyData' => [
  1005. 1 => [[2]],
  1006. 2 => [[3]]
  1007. ],
  1008. '_Token' => compact('fields', 'unlocked', 'debug'),
  1009. ];
  1010. $result = $this->validatePost();
  1011. $this->assertTrue($result);
  1012. }
  1013. /**
  1014. * testValidateHasManyRecords method
  1015. *
  1016. * validatePost should fail, hidden fields have been changed.
  1017. *
  1018. * @return void
  1019. * @triggers Controller.startup $this->Controller
  1020. */
  1021. public function testValidateHasManyRecordsFail()
  1022. {
  1023. $event = new Event('Controller.startup', $this->Controller);
  1024. $this->Controller->Security->startup($event);
  1025. $fields = '7a203edb3d345bbf38fe0dccae960da8842e11d7%3AAddress.0.id%7CAddress.0.primary%7C';
  1026. $fields .= 'Address.1.id%7CAddress.1.primary';
  1027. $unlocked = '';
  1028. $debug = urlencode(json_encode([
  1029. '/articles/index',
  1030. [
  1031. 'Address.0.address',
  1032. 'Address.0.city',
  1033. 'Address.0.first_name',
  1034. 'Address.0.last_name',
  1035. 'Address.0.phone',
  1036. 'Address.0.title',
  1037. 'Address.1.address',
  1038. 'Address.1.city',
  1039. 'Address.1.first_name',
  1040. 'Address.1.last_name',
  1041. 'Address.1.phone',
  1042. 'Address.1.title',
  1043. 'Address.0.id' => '123',
  1044. 'Address.0.primary' => '5',
  1045. 'Address.1.id' => '124',
  1046. 'Address.1.primary' => '1'
  1047. ],
  1048. []
  1049. ]));
  1050. $this->Controller->request->data = [
  1051. 'Address' => [
  1052. 0 => [
  1053. 'id' => '123',
  1054. 'title' => 'home',
  1055. 'first_name' => 'Bilbo',
  1056. 'last_name' => 'Baggins',
  1057. 'address' => '23 Bag end way',
  1058. 'city' => 'the shire',
  1059. 'phone' => 'N/A',
  1060. 'primary' => '5',
  1061. ],
  1062. 1 => [
  1063. 'id' => '124',
  1064. 'title' => 'home',
  1065. 'first_name' => 'Frodo',
  1066. 'last_name' => 'Baggins',
  1067. 'address' => '50 Bag end way',
  1068. 'city' => 'the shire',
  1069. 'phone' => 'N/A',
  1070. 'primary' => '1'
  1071. ]
  1072. ],
  1073. '_Token' => compact('fields', 'unlocked', 'debug'),
  1074. ];
  1075. $result = $this->validatePost('SecurityException', 'Bad Request');
  1076. $this->assertFalse($result);
  1077. }
  1078. /**
  1079. * testFormDisabledFields method
  1080. *
  1081. * @return void
  1082. * @triggers Controller.startup $this->Controller
  1083. */
  1084. public function testFormDisabledFields()
  1085. {
  1086. $event = new Event('Controller.startup', $this->Controller);
  1087. $this->Controller->Security->startup($event);
  1088. $fields = '9da2b3fa2b5b8ac0bfbc1bbce145e58059629125%3An%3A0%3A%7B%7D';
  1089. $unlocked = '';
  1090. $debug = urlencode(json_encode([
  1091. '/articles/index',
  1092. [],
  1093. []
  1094. ]));
  1095. $this->Controller->request->data = [
  1096. 'MyModel' => ['name' => 'some data'],
  1097. '_Token' => compact('fields', 'unlocked', 'debug'),
  1098. ];
  1099. $result = $this->validatePost('SecurityException', 'Unexpected field \'MyModel.name\' in POST data');
  1100. $this->assertFalse($result);
  1101. $this->Controller->Security->startup($event);
  1102. $this->Controller->Security->config('disabledFields', ['MyModel.name']);
  1103. $this->Controller->request->data = [
  1104. 'MyModel' => ['name' => 'some data'],
  1105. '_Token' => compact('fields', 'unlocked', 'debug'),
  1106. ];
  1107. $result = $this->validatePost();
  1108. $this->assertTrue($result);
  1109. }
  1110. /**
  1111. * test validatePost with radio buttons
  1112. *
  1113. * @return void
  1114. * @triggers Controller.startup $this->Controller
  1115. */
  1116. public function testValidatePostRadio()
  1117. {
  1118. $event = new Event('Controller.startup', $this->Controller);
  1119. $this->Controller->Security->startup($event);
  1120. $fields = 'c2226a8879c3f4b513691295fc2519a29c44c8bb%3An%3A0%3A%7B%7D';
  1121. $unlocked = '';
  1122. $debug = urlencode(json_encode([
  1123. '/articles/index',
  1124. [],
  1125. []
  1126. ]));
  1127. $this->Controller->request->data = [
  1128. '_Token' => compact('fields', 'unlocked', 'debug'),
  1129. ];
  1130. $result = $this->validatePost('SecurityException', 'Bad Request');
  1131. $this->assertFalse($result);
  1132. $this->Controller->request->data = [
  1133. '_Token' => compact('fields', 'unlocked', 'debug'),
  1134. 'Test' => ['test' => '']
  1135. ];
  1136. $result = $this->validatePost();
  1137. $this->assertTrue($result);
  1138. $this->Controller->request->data = [
  1139. '_Token' => compact('fields', 'unlocked', 'debug'),
  1140. 'Test' => ['test' => '1']
  1141. ];
  1142. $result = $this->validatePost();
  1143. $this->assertTrue($result);
  1144. $this->Controller->request->data = [
  1145. '_Token' => compact('fields', 'unlocked', 'debug'),
  1146. 'Test' => ['test' => '2']
  1147. ];
  1148. $result = $this->validatePost();
  1149. $this->assertTrue($result);
  1150. }
  1151. /**
  1152. * test validatePost uses here() as a hash input.
  1153. *
  1154. * @return void
  1155. * @triggers Controller.startup $this->Controller
  1156. */
  1157. public function testValidatePostUrlAsHashInput()
  1158. {
  1159. $event = new Event('Controller.startup', $this->Controller);
  1160. $this->Security->startup($event);
  1161. $fields = 'b0914d06dfb04abf1fada53e16810e87d157950b%3A';
  1162. $unlocked = '';
  1163. $debug = urlencode(json_encode([
  1164. 'another-url',
  1165. ['Model.username', 'Model.password'],
  1166. []
  1167. ]));
  1168. $this->Controller->request->data = [
  1169. 'Model' => ['username' => '', 'password' => ''],
  1170. '_Token' => compact('fields', 'unlocked', 'debug')
  1171. ];
  1172. $this->assertTrue($this->validatePost());
  1173. $request = $this->getMockBuilder('Cake\Network\Request')
  1174. ->setMethods(['here'])
  1175. ->getMock();
  1176. $request->expects($this->at(0))
  1177. ->method('here')
  1178. ->will($this->returnValue('/posts/index?page=1'));
  1179. $request->expects($this->at(1))
  1180. ->method('here')
  1181. ->will($this->returnValue('/posts/edit/1'));
  1182. $request->data = $this->Controller->request->data;
  1183. $this->Controller->request = $request;
  1184. $this->assertFalse($this->validatePost('SecurityException', 'URL mismatch in POST data (expected \'another-url\' but found \'/posts/index?page=1\')'));
  1185. $this->assertFalse($this->validatePost('SecurityException', 'URL mismatch in POST data (expected \'another-url\' but found \'/posts/edit/1\')'));
  1186. }
  1187. /**
  1188. * test that blackhole doesn't delete the _Token session key so repeat data submissions
  1189. * stay blackholed.
  1190. *
  1191. * @return void
  1192. * @triggers Controller.startup $this->Controller
  1193. */
  1194. public function testBlackHoleNotDeletingSessionInformation()
  1195. {
  1196. $event = new Event('Controller.startup', $this->Controller);
  1197. $this->Controller->Security->startup($event);
  1198. $this->Controller->Security->blackHole($this->Controller, 'auth');
  1199. $this->assertTrue($this->Controller->Security->session->check('_Token'), '_Token was deleted by blackHole %s');
  1200. }
  1201. /**
  1202. * Test generateToken()
  1203. *
  1204. * @return void
  1205. */
  1206. public function testGenerateToken()
  1207. {
  1208. $request = $this->Controller->request;
  1209. $this->Security->generateToken($request);
  1210. $this->assertNotEmpty($request->params['_Token']);
  1211. $this->assertTrue(isset($request->params['_Token']['unlockedFields']));
  1212. }
  1213. /**
  1214. * Test unlocked actions
  1215. *
  1216. * @return void
  1217. * @triggers Controller.startup $this->Controller
  1218. */
  1219. public function testUnlockedActions()
  1220. {
  1221. $_SERVER['REQUEST_METHOD'] = 'POST';
  1222. $event = new Event('Controller.startup', $this->Controller);
  1223. $this->Controller->request->data = ['data'];
  1224. $this->Controller->Security->unlockedActions = 'index';
  1225. $this->Controller->Security->blackHoleCallback = null;
  1226. $result = $this->Controller->Security->startup($event);
  1227. $this->assertNull($result);
  1228. }
  1229. /**
  1230. * Test that debug token format is right
  1231. *
  1232. * @return void
  1233. * @triggers Controller.startup $this->Controller
  1234. */
  1235. public function testValidatePostDebugFormat()
  1236. {
  1237. $event = new Event('Controller.startup', $this->Controller);
  1238. $this->Controller->Security->startup($event);
  1239. $unlocked = 'Model.username';
  1240. $fields = ['Model.hidden', 'Model.password'];
  1241. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  1242. $debug = urlencode(json_encode([
  1243. '/articles/index',
  1244. ['Model.hidden', 'Model.password'],
  1245. ['Model.username'],
  1246. ['not expected']
  1247. ]));
  1248. $this->Controller->request->data = [
  1249. 'Model' => [
  1250. 'username' => 'mark',
  1251. 'password' => 'sekret',
  1252. 'hidden' => '0'
  1253. ],
  1254. '_Token' => compact('fields', 'unlocked', 'debug')
  1255. ];
  1256. $result = $this->validatePost('SecurityException', 'Invalid security debug token.');
  1257. $this->assertFalse($result);
  1258. $debug = urlencode(json_encode('not an array'));
  1259. $result = $this->validatePost('SecurityException', 'Invalid security debug token.');
  1260. $this->assertFalse($result);
  1261. }
  1262. /**
  1263. * test blackhole will now throw passed exception if debug enabled
  1264. *
  1265. * @expectedException Cake\Controller\Exception\SecurityException
  1266. * @expectedExceptionMessage error description
  1267. * @return void
  1268. */
  1269. public function testBlackholeThrowsException()
  1270. {
  1271. $this->Security->config('blackHoleCallback', '');
  1272. $this->Security->blackHole($this->Controller, 'auth', new SecurityException('error description'));
  1273. }
  1274. /**
  1275. * test blackhole will throw BadRequest if debug disabled
  1276. *
  1277. * @return void
  1278. */
  1279. public function testBlackholeThrowsBadRequest()
  1280. {
  1281. $this->Security->config('blackHoleCallback', '');
  1282. $message = '';
  1283. Configure::write('debug', false);
  1284. try {
  1285. $this->Security->blackHole($this->Controller, 'auth', new SecurityException('error description'));
  1286. } catch (SecurityException $ex) {
  1287. $message = $ex->getMessage();
  1288. $reason = $ex->getReason();
  1289. }
  1290. $this->assertEquals('The request has been black-holed', $message);
  1291. $this->assertEquals('error description', $reason);
  1292. }
  1293. /**
  1294. * Test that validatePost fails with tampered fields and explanation
  1295. *
  1296. * @return void
  1297. * @triggers Controller.startup $this->Controller
  1298. */
  1299. public function testValidatePostFailTampering()
  1300. {
  1301. $event = new Event('Controller.startup', $this->Controller);
  1302. $this->Controller->Security->startup($event);
  1303. $unlocked = '';
  1304. $fields = ['Model.hidden' => 'value', 'Model.id' => '1'];
  1305. $debug = urlencode(json_encode([
  1306. '/articles/index',
  1307. $fields,
  1308. []
  1309. ]));
  1310. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  1311. $fields .= urlencode(':Model.hidden|Model.id');
  1312. $this->Controller->request->data = [
  1313. 'Model' => [
  1314. 'hidden' => 'tampered',
  1315. 'id' => '1',
  1316. ],
  1317. '_Token' => compact('fields', 'unlocked', 'debug')
  1318. ];
  1319. $result = $this->validatePost('SecurityException', 'Tampered field \'Model.hidden\' in POST data (expected value \'value\' but found \'tampered\')');
  1320. $this->assertFalse($result);
  1321. }
  1322. /**
  1323. * Test that validatePost fails with tampered fields and explanation
  1324. *
  1325. * @return void
  1326. * @triggers Controller.startup $this->Controller
  1327. */
  1328. public function testValidatePostFailTamperingMutatedIntoArray()
  1329. {
  1330. $event = new Event('Controller.startup', $this->Controller);
  1331. $this->Controller->Security->startup($event);
  1332. $unlocked = '';
  1333. $fields = ['Model.hidden' => 'value', 'Model.id' => '1'];
  1334. $debug = urlencode(json_encode([
  1335. '/articles/index',
  1336. $fields,
  1337. []
  1338. ]));
  1339. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  1340. $fields .= urlencode(':Model.hidden|Model.id');
  1341. $this->Controller->request->data = [
  1342. 'Model' => [
  1343. 'hidden' => ['some-key' => 'some-value'],
  1344. 'id' => '1',
  1345. ],
  1346. '_Token' => compact('fields', 'unlocked', 'debug')
  1347. ];
  1348. $result = $this->validatePost('SecurityException', 'Unexpected field \'Model.hidden.some-key\' in POST data, Missing field \'Model.hidden\' in POST data');
  1349. $this->assertFalse($result);
  1350. }
  1351. /**
  1352. * Test that debug token should not be sent if debug is disabled
  1353. *
  1354. * @return void
  1355. * @triggers Controller.startup $this->Controller
  1356. */
  1357. public function testValidatePostUnexpectedDebugToken()
  1358. {
  1359. $event = new Event('Controller.startup', $this->Controller);
  1360. $this->Controller->Security->startup($event);
  1361. $unlocked = '';
  1362. $fields = ['Model.hidden' => 'value', 'Model.id' => '1'];
  1363. $debug = urlencode(json_encode([
  1364. '/articles/index',
  1365. $fields,
  1366. []
  1367. ]));
  1368. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  1369. $fields .= urlencode(':Model.hidden|Model.id');
  1370. $this->Controller->request->data = [
  1371. 'Model' => [
  1372. 'hidden' => ['some-key' => 'some-value'],
  1373. 'id' => '1',
  1374. ],
  1375. '_Token' => compact('fields', 'unlocked', 'debug')
  1376. ];
  1377. Configure::write('debug', false);
  1378. $result = $this->validatePost('SecurityException', 'Unexpected \'_Token.debug\' found in request data');
  1379. $this->assertFalse($result);
  1380. }
  1381. /**
  1382. * Auth required throws exception token not found
  1383. *
  1384. * @return void
  1385. * @expectedException Cake\Controller\Exception\AuthSecurityException
  1386. * @expectedExceptionMessage '_Token' was not found in request data.
  1387. * @triggers Controller.startup $this->Controller
  1388. */
  1389. public function testAuthRequiredThrowsExceptionTokenNotFoundPost()
  1390. {
  1391. $this->Controller->Security->config('requireAuth', ['protected']);
  1392. $this->Controller->request->params['action'] = 'protected';
  1393. $this->Controller->request->data = 'notEmpty';
  1394. $this->Controller->Security->authRequired($this->Controller);
  1395. }
  1396. /**
  1397. * Auth required throws exception token not found in Session
  1398. *
  1399. * @return void
  1400. * @expectedException Cake\Controller\Exception\AuthSecurityException
  1401. * @expectedExceptionMessage '_Token' was not found in session.
  1402. * @triggers Controller.startup $this->Controller
  1403. */
  1404. public function testAuthRequiredThrowsExceptionTokenNotFoundSession()
  1405. {
  1406. $this->Controller->Security->config('requireAuth', ['protected']);
  1407. $this->Controller->request->params['action'] = 'protected';
  1408. $this->Controller->request->data = ['_Token' => 'not empty'];
  1409. $this->Controller->Security->authRequired($this->Controller);
  1410. }
  1411. /**
  1412. * Auth required throws exception controller not allowed
  1413. *
  1414. * @return void
  1415. * @expectedException Cake\Controller\Exception\AuthSecurityException
  1416. * @expectedExceptionMessage Controller 'NotAllowed' was not found in allowed controllers: 'Allowed, AnotherAllowed'.
  1417. * @triggers Controller.startup $this->Controller
  1418. */
  1419. public function testAuthRequiredThrowsExceptionControllerNotAllowed()
  1420. {
  1421. $this->Controller->Security->config('requireAuth', ['protected']);
  1422. $this->Controller->request->params['controller'] = 'NotAllowed';
  1423. $this->Controller->request->params['action'] = 'protected';
  1424. $this->Controller->request->data = ['_Token' => 'not empty'];
  1425. $this->Controller->request->session()->write('_Token', [
  1426. 'allowedControllers' => ['Allowed', 'AnotherAllowed']
  1427. ]);
  1428. $this->Controller->Security->authRequired($this->Controller);
  1429. }
  1430. /**
  1431. * Auth required throws exception controller not allowed
  1432. *
  1433. * @return void
  1434. * @expectedException Cake\Controller\Exception\AuthSecurityException
  1435. * @expectedExceptionMessage Action 'NotAllowed::protected' was not found in allowed actions: 'index, view'.
  1436. * @triggers Controller.startup $this->Controller
  1437. */
  1438. public function testAuthRequiredThrowsExceptionActionNotAllowed()
  1439. {
  1440. $this->Controller->Security->config('requireAuth', ['protected']);
  1441. $this->Controller->request->params['controller'] = 'NotAllowed';
  1442. $this->Controller->request->params['action'] = 'protected';
  1443. $this->Controller->request->data = ['_Token' => 'not empty'];
  1444. $this->Controller->request->session()->write('_Token', [
  1445. 'allowedActions' => ['index', 'view']
  1446. ]);
  1447. $this->Controller->Security->authRequired($this->Controller);
  1448. }
  1449. /**
  1450. * Auth required throws exception controller not allowed
  1451. *
  1452. * @return void
  1453. * @triggers Controller.startup $this->Controller
  1454. */
  1455. public function testAuthRequired()
  1456. {
  1457. $this->Controller->Security->config('requireAuth', ['protected']);
  1458. $this->Controller->request->params['controller'] = 'Allowed';
  1459. $this->Controller->request->params['action'] = 'protected';
  1460. $this->Controller->request->data = ['_Token' => 'not empty'];
  1461. $this->Controller->request->session()->write('_Token', [
  1462. 'allowedActions' => ['protected'],
  1463. 'allowedControllers' => ['Allowed'],
  1464. ]);
  1465. $this->assertTrue($this->Controller->Security->authRequired($this->Controller));
  1466. }
  1467. }