SecurityComponentTest.php 55 KB

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