From 504b62a42b6bfab7a3ad49fa535382eac86bee17 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 4 Jan 2025 11:42:02 +0700 Subject: [PATCH] add tests --- system/Security/Security.php | 6 +--- tests/system/Security/SecurityTest.php | 44 ++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/system/Security/Security.php b/system/Security/Security.php index f221a3df24e4..9cb64561e0f3 100644 --- a/system/Security/Security.php +++ b/system/Security/Security.php @@ -307,11 +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)) { - if (! is_string($tokenValue)) { - return null; - } - - return $tokenValue; + return is_string($tokenValue) ? $tokenValue : null; } if ($request->hasHeader($this->config->headerName) diff --git a/tests/system/Security/SecurityTest.php b/tests/system/Security/SecurityTest.php index f8799230e056..4886b04f3f8b 100644 --- a/tests/system/Security/SecurityTest.php +++ b/tests/system/Security/SecurityTest.php @@ -25,6 +25,7 @@ use Config\Security as SecurityConfig; use PHPUnit\Framework\Attributes\BackupGlobals; use PHPUnit\Framework\Attributes\Group; +use ReflectionClass; /** * @internal @@ -49,6 +50,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(); @@ -315,4 +326,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)); + } }