feat: add CSRF token store and verifier
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BattleForge\Http;
|
||||
|
||||
final class CsrfToken
|
||||
{
|
||||
/** @return array{0: string, 1: string} */
|
||||
public static function issue(string $secret): array
|
||||
{
|
||||
$token = bin2hex(random_bytes(32));
|
||||
$cookie = hash_hmac('sha256', $token, $secret);
|
||||
|
||||
return [$token, $cookie];
|
||||
}
|
||||
|
||||
public static function verify(string $submitted, string $secret, string $expectedCookieValue): bool
|
||||
{
|
||||
$computed = hash_hmac('sha256', $submitted, $secret);
|
||||
|
||||
return hash_equals($expectedCookieValue, $computed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BattleForge\Tests\Unit\Http;
|
||||
|
||||
use BattleForge\Http\CsrfToken;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class CsrfTokenTest extends TestCase
|
||||
{
|
||||
private const SECRET = 'unit-test-secret';
|
||||
|
||||
public function testIssueReturnsTokenAndCookieValue(): void
|
||||
{
|
||||
[$token, $cookie] = CsrfToken::issue(self::SECRET);
|
||||
|
||||
self::assertNotSame('', $token);
|
||||
self::assertNotSame('', $cookie);
|
||||
self::assertSame(64, strlen($token));
|
||||
}
|
||||
|
||||
public function testVerifyAcceptsAValidPair(): void
|
||||
{
|
||||
[$token, $cookie] = CsrfToken::issue(self::SECRET);
|
||||
|
||||
self::assertTrue(CsrfToken::verify($token, self::SECRET, $cookie));
|
||||
}
|
||||
|
||||
public function testVerifyRejectsATamperedCookieValue(): void
|
||||
{
|
||||
[$token] = CsrfToken::issue(self::SECRET);
|
||||
|
||||
self::assertFalse(CsrfToken::verify($token, self::SECRET, 'not-the-cookie'));
|
||||
}
|
||||
|
||||
public function testVerifyRejectsATamperedToken(): void
|
||||
{
|
||||
[, $cookie] = CsrfToken::issue(self::SECRET);
|
||||
|
||||
self::assertFalse(CsrfToken::verify('not-the-token', self::SECRET, $cookie));
|
||||
}
|
||||
|
||||
public function testIssueProducesDifferentTokensAcrossCalls(): void
|
||||
{
|
||||
[$tokenA] = CsrfToken::issue(self::SECRET);
|
||||
[$tokenB] = CsrfToken::issue(self::SECRET);
|
||||
|
||||
self::assertNotSame($tokenA, $tokenB);
|
||||
}
|
||||
|
||||
public function testDifferentSecretsProduceDifferentCookieValues(): void
|
||||
{
|
||||
[$tokenA, $cookieA] = CsrfToken::issue('secret-a');
|
||||
[, $cookieB] = CsrfToken::issue('secret-b');
|
||||
|
||||
self::assertTrue(CsrfToken::verify($tokenA, 'secret-a', $cookieA));
|
||||
self::assertFalse(CsrfToken::verify($tokenA, 'secret-b', $cookieB));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user