Skip to content

Commit

Permalink
Fix CSRF validation failure.
Browse files Browse the repository at this point in the history
When the cookie is not present CSRF validation should always fail.
  • Loading branch information
markstory committed May 8, 2015
1 parent dfa7337 commit 522ed2f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/Controller/Component/CsrfComponent.php
Expand Up @@ -144,6 +144,10 @@ protected function _validateToken(Request $request)
$post = $request->data($this->_config['field']);
$header = $request->header('X-CSRF-Token');

if (empty($cookie)) {
throw new ForbiddenException(__d('cake', 'Invalid CSRF token.'));
}

if ($post !== $cookie && $header !== $cookie) {
throw new ForbiddenException(__d('cake', 'Invalid CSRF token.'));
}
Expand Down
44 changes: 43 additions & 1 deletion tests/TestCase/Controller/Component/CsrfComponentTest.php
Expand Up @@ -163,7 +163,6 @@ public function testValidTokenRequestData($method)
* @dataProvider httpMethodProvider
* @expectedException \Cake\Network\Exception\ForbiddenException
* @return void
* @triggers Controller.startup $controller
*/
public function testInvalidTokenRequestData($method)
{
Expand All @@ -180,6 +179,49 @@ public function testInvalidTokenRequestData($method)
$this->component->startup($event);
}

/**
* Test that missing post field fails
*
* @expectedException \Cake\Network\Exception\ForbiddenException
* @return void
*/
public function testInvalidTokenRequestDataMissing()
{
$_SERVER['REQUEST_METHOD'] = 'POST';

$controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
$controller->request = new Request([
'post' => [],
'cookies' => ['csrfToken' => 'testing123']
]);
$controller->response = new Response();

$event = new Event('Controller.startup', $controller);
$this->component->startup($event);
}

/**
* Test that missing header and cookie fails
*
* @dataProvider httpMethodProvider
* @expectedException \Cake\Network\Exception\ForbiddenException
* @return void
*/
public function testInvalidTokenMissingCookie($method)
{
$_SERVER['REQUEST_METHOD'] = $method;

$controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
$controller->request = new Request([
'post' => ['_csrfToken' => 'could-be-valid'],
'cookies' => []
]);
$controller->response = new Response();

$event = new Event('Controller.startup', $controller);
$this->component->startup($event);
}

/**
* Test that CSRF checks are not applied to request action requests.
*
Expand Down

0 comments on commit 522ed2f

Please sign in to comment.