SecurityComponentTest.php 56 KB

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