SecurityComponentTest.php 56 KB

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