Testing CakePHP with a security component

Consider this code:

Controller code

<?php App::uses('AppController', 'Controller'); class UsersController extends AppController { public $components = array( 'Security', 'Session' ); public function example() { if ($this->request->is('post')) { $this->set('some_var', true); } } } 

Code view

 <?php echo $this->Form->create(); echo $this->Form->input('name'); echo $this->Form->end('Submit'); 

Since I have the Security component in place, somehow changing the form (for example, adding a field to it), the request will be black. I would like to check this out:

Test code

 <?php class UsersControllerTest extends ControllerTestCase { public function testExamplePostValidData() { $this->Controller = $this->generate('Users', array( 'components' => array( 'Security' ) )); $data = array( 'User' => array( 'name' => 'John Doe' ) ); $this->testAction('/users/example', array('data' => $data, 'method' => 'post')); $this->assertTrue($this->vars['some_var']); } public function testExamplePostInvalidData() { $this->Controller = $this->generate('Users', array( 'components' => array( 'Security' ) )); $data = array( 'User' => array( 'name' => 'John Doe', 'some_field' => 'The existence of this should cause the request to be black-holed.' ) ); $this->testAction('/users/example', array('data' => $data, 'method' => 'post')); $this->assertTrue($this->vars['some_var']); } } 

The second test testExamplePostInvalidData should fail because some_field is in the $data array, but it passes! What am I doing wrong?

+6
source share
1 answer

By adding "some_field" to the data → testAction, the security component will assume that this field is part of your application (since it comes from your code, not the POST array), so it will not be considered as a "hack attempt".

Checking black holes is a bit confusing. But Core Cake tests are already testing blackhole functionality, so if these tests pass, you don't need to test them in your application.

If you insist on this, check out the basic Cake tests for guidance:

In particular:

 /** * test that validatePost fails if any of its required fields are missing. * * @return void */ public function testValidatePostFormHacking() { $this->Controller->Security->startup($this->Controller); $key = $this->Controller->params['_Token']['key']; $unlocked = ''; $this->Controller->request->data = array( 'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'), '_Token' => compact('key', 'unlocked') ); $result = $this->Controller->Security->validatePost($this->Controller); $this->assertFalse($result, 'validatePost passed when fields were missing. %s'); } 

The file has more examples:
https://github.com/cakephp/cakephp/blob/master/lib/Cake/Test/Case/Controller/Component/SecurityComponentTest.php

+1
source

Source: https://habr.com/ru/post/944731/


All Articles