SecurityComponentTest.php 57 KB

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