-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
CsrfCounterMeasure: Only validate transmitted tokens
- Loading branch information
Showing
2 changed files
with
102 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
<?php | ||
|
||
namespace ipl\Tests\Web\Common; | ||
|
||
use ipl\Html\Contract\FormElement; | ||
use ipl\Html\Form; | ||
use ipl\Html\FormElement\HiddenElement; | ||
use ipl\Tests\Web\TestCase; | ||
use ipl\Web\Common\CsrfCounterMeasure; | ||
|
||
class CsrfCounterMeasureTest extends TestCase | ||
{ | ||
public function testTokenCreation() | ||
{ | ||
$token = $this->createElement(); | ||
|
||
$this->assertInstanceOf(HiddenElement::class, $token); | ||
$this->assertMatchesRegularExpression( | ||
'/ value="[^"]+\|[^"]+"/', | ||
(string) $token, | ||
'The value is not rendered or does not contain a seed and a hash' | ||
); | ||
} | ||
|
||
public function testMissingToken() | ||
{ | ||
$token = $this->createElement(); | ||
|
||
$this->assertNull($token->getValue(), 'The default value must only be set after the form is rendered'); | ||
|
||
$this->expectError(); | ||
$this->expectErrorMessage('Invalid CSRF token provided'); | ||
|
||
$token->isValid(); | ||
} | ||
|
||
public function testValidToken() | ||
{ | ||
$token = $this->createElement(); | ||
|
||
$this->assertSame(1, preg_match('/ value="([^"]+)"/', (string) $token, $matches)); | ||
|
||
$token->setValue($matches[1]); | ||
$this->assertTrue($token->isValid(), 'Token should be valid with the default value'); | ||
} | ||
|
||
public function testInvalidToken() | ||
{ | ||
$token = $this->createElement(); | ||
|
||
$token->setValue('invalid'); | ||
|
||
$this->expectError(); | ||
$this->expectErrorMessage('Invalid CSRF token provided'); | ||
|
||
$token->isValid(); | ||
} | ||
|
||
private function createElement(): FormElement | ||
{ | ||
$form = new class extends Form { | ||
use CsrfCounterMeasure { | ||
createCsrfCounterMeasure as public; | ||
} | ||
}; | ||
|
||
return $form->createCsrfCounterMeasure('uniqueId'); | ||
} | ||
} |