Add CorsRegexEnvProcessor and corresponding tests

- Implemented CorsRegexEnvProcessor to build CORS origin regex from a comma-separated host list (ALLOWED_FRONTEND_HOSTS).
- Added tests for CorsRegexEnvProcessor to validate regex generation and matching behavior.
- Created JSON files for AST representation of the new classes and tests.
This commit is contained in:
hamed
2026-07-07 14:58:41 +03:30
parent 4ee1524f31
commit 87f4d1695f
18 changed files with 2536 additions and 1343 deletions
@@ -0,0 +1,68 @@
<?php
namespace App\Tests\Shared;
use App\Shared\DependencyInjection\CorsRegexEnvProcessor;
use PHPUnit\Framework\TestCase;
class CorsRegexEnvProcessorTest extends TestCase
{
private function regexFor(string $hosts): string
{
$processor = new CorsRegexEnvProcessor();
return $processor->getEnv('cors_regex', 'ALLOWED_FRONTEND_HOSTS', fn () => $hosts);
}
/** رجکس ساخته‌شده با delimiter نلمیو (`#`) کامپایل و روی origin تست می‌شود. */
private function originMatches(string $regex, string $origin): bool
{
return (bool) preg_match('#' . $regex . '#i', $origin);
}
public function testAllowsListedHostsHttpsAndSubdomains(): void
{
$regex = $this->regexFor('yasuj-nobat.ir,nobat724.com');
$this->assertTrue($this->originMatches($regex, 'https://yasuj-nobat.ir'));
$this->assertTrue($this->originMatches($regex, 'https://www.nobat724.com'));
}
public function testAllowsHttpAndPortForLocalDev(): void
{
$regex = $this->regexFor('localhost,yazd-nobat.localhost');
$this->assertTrue($this->originMatches($regex, 'http://yazd-nobat.localhost:3000'));
$this->assertTrue($this->originMatches($regex, 'http://localhost:8080'));
}
public function testRejectsUnlistedAndLookalikeHosts(): void
{
$regex = $this->regexFor('yasuj-nobat.ir');
$this->assertFalse($this->originMatches($regex, 'https://evil.com'));
// انکورِ انتها: دامنه‌ای که با هاست مجاز شروع/تمام نشود نباید مچ شود.
$this->assertFalse($this->originMatches($regex, 'https://yasuj-nobat.ir.evil.com'));
$this->assertFalse($this->originMatches($regex, 'https://notyasuj-nobat.ir'));
}
public function testDotIsEscapedNotWildcard(): void
{
$regex = $this->regexFor('nobat724.com');
// نقطه نباید به‌عنوان wildcard عمل کند.
$this->assertFalse($this->originMatches($regex, 'https://nobat724xcom'));
}
public function testEmptyListMatchesNothing(): void
{
$regex = $this->regexFor('');
$this->assertFalse($this->originMatches($regex, 'https://yasuj-nobat.ir'));
$this->assertFalse($this->originMatches($regex, 'https://anything.com'));
}
public function testProvidedType(): void
{
$this->assertSame(['cors_regex' => 'string'], CorsRegexEnvProcessor::getProvidedTypes());
}
}