6

次のコードを検討してください。

コントローラーコード

<?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);
        }
    }
}

コードを表示

<?php

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

セキュリティ コンポーネントが配置されているため、何らかの方法でフォームを改ざんすると (フォームにフィールドを追加するなど)、リクエストがブラックホール化されます。これをテストしたい:

テストコード

<?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']);
    }
}

2 番目のテストは、配列内にあるtestExamplePostInvalidDataために失敗するはずですが、成功します。私は何を間違っていますか?some_field$data

4

1 に答える 1

1

->testAction のデータに「some_field」を追加することにより、セキュリティ コンポーネントはフィールドがアプリの一部であると想定し (POST 配列ではなくコードから取得されるため)、「ハック」と見なされなくなります。試み"。

ブラックホールのチェックはもう少し複雑です。ただし、Cake のコア テストではすでにブラックホール機能がテストされているため、これらのテストに合格した場合は、アプリでチェックする必要はありません。

それでもどうしてもという場合は、ガイダンスとしてコアの Cake テストを確認してください。

具体的には:

/**
 * 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');
}

ファイル内のさらに多くの例:
https://github.com/cakephp/cakephp/blob/master/lib/Cake/Test/Case/Controller/Component/SecurityComponentTest.php

于 2013-05-24T04:33:12.737 に答える