Skip to content

Commit

Permalink
fix: ensure csrf token is string
Browse files Browse the repository at this point in the history
  • Loading branch information
datlechin committed Jan 7, 2025
1 parent 3c851f1 commit 4087e5b
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
2 changes: 1 addition & 1 deletion system/Security/Security.php
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ private function getPostedToken(RequestInterface $request): ?string
// Does the token exist in POST, HEADER or optionally php:://input - json data or PUT, DELETE, PATCH - raw data.

if ($tokenValue = $request->getPost($this->config->tokenName)) {
return $tokenValue;
return is_string($tokenValue) ? $tokenValue : null;
}

if ($request->hasHeader($this->config->headerName)
Expand Down
45 changes: 45 additions & 0 deletions tests/system/Security/SecurityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
use Config\Security as SecurityConfig;
use PHPUnit\Framework\Attributes\BackupGlobals;
use PHPUnit\Framework\Attributes\Group;
use ReflectionClass;
use ReflectionMethod;

/**
* @internal
Expand All @@ -49,6 +51,16 @@ private function createMockSecurity(?SecurityConfig $config = null): MockSecurit
return new MockSecurity($config);
}

private function getPostedTokenMethod(): ReflectionMethod
{
$reflection = new ReflectionClass(Security::class);
$method = $reflection->getMethod('getPostedToken');

$method->setAccessible(true);

return $method;
}

public function testBasicConfigIsSaved(): void
{
$security = $this->createMockSecurity();
Expand Down Expand Up @@ -315,4 +327,37 @@ public function testGetters(): void
$this->assertIsString($security->getCookieName());
$this->assertIsBool($security->shouldRedirect());
}

public function testGetPostedTokenReturnsTokenWhenValid(): void
{
$method = $this->getPostedTokenMethod();
$security = $this->createMockSecurity();

$_POST['csrf_test_name'] = '8b9218a55906f9dcc1dc263dce7f005a';
$request = $this->createIncomingRequest();

$this->assertSame('8b9218a55906f9dcc1dc263dce7f005a', $method->invoke($security, $request));
}

public function testGetPostedTokenReturnsNullWhenEmpty(): void
{
$method = $this->getPostedTokenMethod();
$security = $this->createMockSecurity();

$_POST = [];
$request = $this->createIncomingRequest();

$this->assertNull($method->invoke($security, $request));
}

public function testGetPostedTokenReturnsNullWhenMaliciousData(): void
{
$method = $this->getPostedTokenMethod();
$security = $this->createMockSecurity();

$_POST['csrf_test_name'] = ['malicious' => 'data'];
$request = $this->createIncomingRequest();

$this->assertNull($method->invoke($security, $request));
}
}

0 comments on commit 4087e5b

Please sign in to comment.