CSRF guards added to 16 admin pages that previously accepted POST requests without token verification (GR-SEC-001): departments, permissions, roles, settings, tenants, users (create/edit/bulk/tokens), and lang switch. New contract tests: - PostEndpointCsrfContractTest: scans all pages/ for POST handlers and verifies checkCsrfToken is present (API/data endpoints exempt). - DatabaseUpdatesContractTest: validates db/updates/ scripts follow naming convention and use idempotent SQL patterns (GR-CORE-010). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
81 lines
2.1 KiB
PHP
81 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace MintyPHP\Tests\Architecture;
|
|
|
|
use PHPUnit\Framework\TestCase;
|
|
use RecursiveDirectoryIterator;
|
|
use RecursiveIteratorIterator;
|
|
|
|
/**
|
|
* GR-SEC-001: Every POST endpoint in pages/ MUST verify CSRF token before
|
|
* processing the request body.
|
|
*/
|
|
class PostEndpointCsrfContractTest extends TestCase
|
|
{
|
|
use ProjectFileAssertionSupport;
|
|
|
|
/** Files that use API-token auth instead of CSRF (data endpoints, API v1). */
|
|
private const CSRF_EXEMPT_PATTERNS = [
|
|
'#/api/v1/#',
|
|
'#/data\(\)\.php$#',
|
|
];
|
|
|
|
public function testAllPostHandlersVerifyCsrfToken(): void
|
|
{
|
|
$pagesDir = $this->projectRootPath() . '/pages';
|
|
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pagesDir));
|
|
|
|
$missing = [];
|
|
|
|
foreach ($iterator as $file) {
|
|
if (!$file->isFile() || $file->getExtension() !== 'php') {
|
|
continue;
|
|
}
|
|
|
|
$relativePath = 'pages/' . ltrim(str_replace($pagesDir, '', $file->getPathname()), '/');
|
|
|
|
if ($this->isCsrfExempt($relativePath)) {
|
|
continue;
|
|
}
|
|
|
|
$content = (string) file_get_contents($file->getPathname());
|
|
|
|
if (!$this->handlesPostData($content)) {
|
|
continue;
|
|
}
|
|
|
|
if (!str_contains($content, 'checkCsrfToken')) {
|
|
$missing[] = $relativePath;
|
|
}
|
|
}
|
|
|
|
sort($missing);
|
|
|
|
$this->assertSame(
|
|
[],
|
|
$missing,
|
|
"POST handlers missing CSRF verification (GR-SEC-001):\n" . implode("\n", $missing)
|
|
);
|
|
}
|
|
|
|
private function isCsrfExempt(string $path): bool
|
|
{
|
|
foreach (self::CSRF_EXEMPT_PATTERNS as $pattern) {
|
|
if (preg_match($pattern, $path)) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private function handlesPostData(string $content): bool
|
|
{
|
|
return str_contains($content, "isMethod('POST')")
|
|
|| str_contains($content, 'hasBody(')
|
|
|| str_contains($content, 'bodyAll()')
|
|
|| preg_match('/->body\(/', $content) === 1;
|
|
}
|
|
|
|
}
|