321 lines
19 KiB
PHP
321 lines
19 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Symfony\SecurityAccessControl;
|
|
use JumPHP\Ide\Symfony\SecurityCommands;
|
|
use JumPHP\Ide\Symfony\SecurityConfig;
|
|
use JumPHP\Ide\Symfony\SecurityGenerator;
|
|
use JumPHP\Ide\Symfony\SecurityRoutes;
|
|
use JumPHP\Ide\Symfony\SecurityYamlEditor;
|
|
use JumPHP\Ide\Symfony\ValidationPhp;
|
|
use JumPHP\Ide\Workspace\MemoryWorkspace;
|
|
use PHPUnit\Framework\TestCase;
|
|
use Symfony\Component\Yaml\Yaml;
|
|
|
|
/** The Security window: security.yaml rewritten node by node, access_control's matcher, routes x roles, generators. */
|
|
final class SymfonySecurityTest extends TestCase
|
|
{
|
|
/** the recipe's file (symfony/security-bundle) */
|
|
private const RECIPE = <<<'YAML'
|
|
security:
|
|
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
|
|
password_hashers:
|
|
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
|
|
|
|
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
|
|
providers:
|
|
users_in_memory: { memory: null }
|
|
|
|
firewalls:
|
|
dev:
|
|
# Ensure dev tools and static assets are always allowed
|
|
pattern: ^/(_profiler(/|$)|(_wdt|assets|build)/)
|
|
security: false
|
|
main:
|
|
lazy: true
|
|
provider: users_in_memory
|
|
|
|
# Activate different ways to authenticate:
|
|
# https://symfony.com/doc/current/security.html#the-firewall
|
|
|
|
# https://symfony.com/doc/current/security/impersonating_user.html
|
|
# switch_user: true
|
|
|
|
# Note: Only the *first* matching rule is applied
|
|
access_control:
|
|
# - { path: ^/admin, roles: ROLE_ADMIN }
|
|
# - { path: ^/profile, roles: ROLE_USER }
|
|
|
|
when@test:
|
|
security:
|
|
password_hashers:
|
|
# Password hashers are resource-intensive by design to ensure security.
|
|
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
|
|
algorithm: auto
|
|
cost: 4 # Lowest possible value for bcrypt
|
|
|
|
YAML;
|
|
|
|
private static function security(string $text = self::RECIPE): array
|
|
{
|
|
return Yaml::parse($text)['security'];
|
|
}
|
|
|
|
public function testNothingChangedWritesTheSameBytes(): void
|
|
{
|
|
self::assertSame(self::RECIPE, SecurityConfig::write(self::RECIPE, self::security()));
|
|
}
|
|
|
|
public function testAChangedScalarRewritesOnlyItsLine(): void
|
|
{
|
|
$s = self::security();
|
|
$s['firewalls']['main']['lazy'] = false;
|
|
self::assertSame(str_replace(' lazy: true', ' lazy: false', self::RECIPE), SecurityConfig::write(self::RECIPE, $s));
|
|
// an end-of-line comment stays
|
|
$t = SecurityConfig::write(self::RECIPE, Yaml::parse(self::RECIPE)['when@test']['security'] === [] ? [] : array_replace_recursive(Yaml::parse(self::RECIPE)['when@test']['security'],
|
|
['password_hashers' => ['Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface' => ['cost' => 5]]]), 'test');
|
|
self::assertSame(str_replace('cost: 4 # Lowest', 'cost: 5 # Lowest', self::RECIPE), $t);
|
|
}
|
|
|
|
public function testANewKeyGoesAtTheEndOfItsMappingAndTheCommentsStay(): void
|
|
{
|
|
$s = self::security();
|
|
$s['firewalls']['main']['form_login'] = ['login_path' => 'app_login', 'check_path' => 'app_login', 'enable_csrf' => true];
|
|
$s['firewalls']['main']['logout'] = ['path' => 'app_logout'];
|
|
$out = SecurityConfig::write(self::RECIPE, $s);
|
|
self::assertSame(str_replace(" provider: users_in_memory\n", " provider: users_in_memory\n form_login:\n login_path: app_login\n check_path: app_login\n enable_csrf: true\n logout:\n path: app_logout\n", self::RECIPE), $out);
|
|
}
|
|
|
|
public function testAccessControlIsWrittenUnderItsCommentedExamples(): void
|
|
{
|
|
$s = self::security();
|
|
$s['access_control'] = [['path' => '^/admin', 'roles' => 'ROLE_ADMIN'], ['path' => '^/api', 'roles' => ['ROLE_API', 'ROLE_ADMIN'], 'methods' => ['POST']]];
|
|
$out = SecurityConfig::write(self::RECIPE, $s);
|
|
self::assertStringContainsString(" access_control:\n # - { path: ^/admin, roles: ROLE_ADMIN }\n # - { path: ^/profile, roles: ROLE_USER }\n - { path: ^/admin, roles: ROLE_ADMIN }\n - { path: ^/api, roles: [ROLE_API, ROLE_ADMIN], methods: [POST] }\n\nwhen@test:", $out);
|
|
self::assertSame($s, Yaml::parse($out)['security']);
|
|
// and replaced as a whole the next time (the examples still there)
|
|
$s['access_control'] = [['path' => '^/profile', 'roles' => 'ROLE_USER']];
|
|
$again = SecurityConfig::write($out, $s);
|
|
self::assertStringContainsString(" # - { path: ^/profile, roles: ROLE_USER }\n - { path: ^/profile, roles: ROLE_USER }\n\nwhen@test:", $again);
|
|
}
|
|
|
|
public function testFlowStyleKeysRemovedAndFirewallsReordered(): void
|
|
{
|
|
$s = self::security();
|
|
$s['providers']['users_in_memory'] = ['memory' => ['users' => ['admin' => ['password' => 'x', 'roles' => ['ROLE_ADMIN']]]]];
|
|
$out = SecurityConfig::write(self::RECIPE, $s);
|
|
self::assertStringContainsString(" users_in_memory: { memory: { users: { admin: { password: x, roles: [ROLE_ADMIN] } } } }\n", $out);
|
|
$s = self::security();
|
|
unset($s['firewalls']['dev']['security']);
|
|
$s['firewalls'] = ['main' => $s['firewalls']['main'], 'dev' => $s['firewalls']['dev']];
|
|
$out = SecurityConfig::write(self::RECIPE, $s);
|
|
self::assertSame(['main', 'dev'], array_keys(Yaml::parse($out)['security']['firewalls']));
|
|
self::assertStringContainsString(" dev:\n # Ensure dev tools and static assets are always allowed\n pattern: ^/(_profiler(/|$)|(_wdt|assets|build)/)\n\n # Note", $out);
|
|
self::assertStringContainsString(" firewalls:\n main:\n lazy: true\n provider: users_in_memory\n\n # Activate", $out);
|
|
self::assertSame($s, Yaml::parse($out)['security']);
|
|
}
|
|
|
|
public function testRoleHierarchyIsAddedAsANewSection(): void
|
|
{
|
|
$s = self::security();
|
|
$s['role_hierarchy'] = ['ROLE_ADMIN' => 'ROLE_USER', 'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH']];
|
|
$out = SecurityConfig::write(self::RECIPE, $s);
|
|
self::assertStringContainsString(" # - { path: ^/profile, roles: ROLE_USER }\n role_hierarchy:\n ROLE_ADMIN: ROLE_USER\n ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]\n", $out);
|
|
self::assertSame($s, Yaml::parse($out)['security']);
|
|
self::assertSame(['ROLE_SUPER_ADMIN', 'ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH', 'ROLE_USER'], SecurityConfig::reachable($s['role_hierarchy'], 'ROLE_SUPER_ADMIN'));
|
|
}
|
|
|
|
public function testTheEditorOnItsOwn(): void
|
|
{
|
|
$e = new SecurityYamlEditor("a:\n b: 1 # one\n c: [x]\n");
|
|
$e->set(['a', 'b'], 2);
|
|
$e->set(['a', 'd', 'e'], true);
|
|
$e->remove(['a', 'c']);
|
|
self::assertSame("a:\n b: 2 # one\n d:\n e: true\n", $e->text());
|
|
}
|
|
|
|
public function testWarningsForCommonMistakes(): void
|
|
{
|
|
$codes = fn (array $s) => array_column(SecurityConfig::warnings($s), 'code');
|
|
self::assertSame([], $codes(self::security()));
|
|
self::assertSame(['ambiguous-provider'], $codes(['providers' => ['a' => [], 'b' => []], 'firewalls' => ['main' => ['form_login' => null]]]));
|
|
self::assertSame(['no-provider'], $codes(['firewalls' => ['main' => ['form_login' => null]]]));
|
|
self::assertSame(['unknown-provider'], $codes(['providers' => ['a' => []], 'firewalls' => ['main' => ['provider' => 'b']]]));
|
|
self::assertSame(['catch-all'], $codes(['providers' => ['a' => []], 'firewalls' => ['main' => ['lazy' => true], 'api' => ['pattern' => '^/api']]]));
|
|
self::assertSame(['plaintext'], $codes(['password_hashers' => ['App\Entity\User' => 'plaintext']]));
|
|
self::assertSame(['shadowed', 'unanchored'], $codes(['access_control' => [['path' => '^/admin', 'roles' => 'ROLE_ADMIN'], ['path' => '^/admin/login', 'roles' => 'PUBLIC_ACCESS'], ['path' => '/x']]]));
|
|
self::assertSame(['cycle', 'cycle'], $codes(['role_hierarchy' => ['ROLE_A' => 'ROLE_B', 'ROLE_B' => ['ROLE_A']]]));
|
|
self::assertSame(['stateless-form'], $codes(['providers' => ['a' => []], 'firewalls' => ['main' => ['stateless' => true, 'form_login' => []]]]));
|
|
}
|
|
|
|
public function testWhichRuleMatchesARequest(): void
|
|
{
|
|
$rules = [
|
|
['path' => '^/admin', 'roles' => 'ROLE_ADMIN', 'ips' => ['10.0.0.0/8']],
|
|
['path' => '^/admin', 'roles' => 'ROLE_SUPER_ADMIN'],
|
|
['path' => '^/api', 'methods' => ['POST', 'PUT'], 'roles' => 'ROLE_API'],
|
|
['path' => '^/', 'host' => 'shop\.example\.com$', 'roles' => 'ROLE_USER'],
|
|
['path' => '^/', 'roles' => 'PUBLIC_ACCESS'],
|
|
];
|
|
$m = fn (array $r) => SecurityAccessControl::match($rules, $r);
|
|
self::assertSame(0, $m(['path' => '/admin/users', 'ip' => '10.2.3.4'])['index']);
|
|
$r = $m(['path' => '/admin/users', 'ip' => '192.168.1.1']);
|
|
self::assertSame(1, $r['index']);
|
|
self::assertSame('ips', $r['trace'][0]['failed']);
|
|
self::assertSame(4, $m(['path' => '/api/x', 'method' => 'GET'])['index']);
|
|
self::assertSame(2, $m(['path' => '/api/x', 'method' => 'put'])['index']);
|
|
self::assertSame(3, $m(['path' => '/', 'host' => 'SHOP.example.com'])['index']);
|
|
self::assertSame(-1, SecurityAccessControl::match([['path' => '^/x']], ['path' => '/y'])['index']);
|
|
self::assertSame(0, SecurityAccessControl::match([['path' => '^/café']], ['path' => '/caf%C3%A9'])['index']);
|
|
self::assertTrue(SecurityAccessControl::ipIn('2001:db8::1', ['2001:db8::/32']));
|
|
self::assertFalse(SecurityAccessControl::ipIn('2001:db9::1', ['2001:db8::/32']));
|
|
self::assertTrue(SecurityAccessControl::ipIn('127.0.0.1', ['private_ranges']));
|
|
}
|
|
|
|
public function testShadowedRules(): void
|
|
{
|
|
$s = SecurityAccessControl::shadowed([
|
|
['path' => '^/admin'], ['path' => '^/admin/login'],
|
|
['path' => '^/api', 'methods' => ['GET']], ['path' => '^/api/public'],
|
|
['path' => '^/b[a-z]+'], ['path' => '^/blog'],
|
|
]);
|
|
self::assertSame([['index' => 1, 'by' => 0, 'sure' => true], ['index' => 5, 'by' => 4, 'sure' => false]], $s);
|
|
}
|
|
|
|
private const CONTROLLER = <<<'PHP'
|
|
<?php
|
|
|
|
namespace App\Controller;
|
|
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
use Symfony\Component\Routing\Attribute\Route;
|
|
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
|
|
|
#[Route('/admin', name: 'admin_')]
|
|
final class AdminController extends AbstractController
|
|
{
|
|
#[Route('/', name: 'home')]
|
|
public function index(): Response
|
|
{
|
|
return new Response('admin');
|
|
}
|
|
|
|
#[Route('/post/{id}/edit', name: 'post_edit', methods: ['GET', 'POST'])]
|
|
#[IsGranted('POST_EDIT', subject: 'post')]
|
|
public function edit(int $id): Response
|
|
{
|
|
$this->denyAccessUnlessGranted('ROLE_EDITOR');
|
|
return new Response('edit');
|
|
}
|
|
|
|
#[Route('/stats')]
|
|
public function stats(): Response
|
|
{
|
|
return new Response('stats');
|
|
}
|
|
}
|
|
|
|
PHP;
|
|
|
|
public function testRoutesWithTheirProtections(): void
|
|
{
|
|
$routes = SecurityRoutes::routes(self::CONTROLLER, 'src/Controller/AdminController.php');
|
|
self::assertSame(['admin_home', 'admin_post_edit', 'admin_app_admin_stats'], array_column($routes, 'name'));
|
|
self::assertSame(['/admin/', '/admin/post/{id}/edit', '/admin/stats'], array_column($routes, 'path'));
|
|
self::assertSame([['attribute' => 'POST_EDIT', 'line' => 20, 'level' => 'method', 'index' => 0, 'subject' => 'post'], ['attribute' => 'ROLE_EDITOR', 'line' => 23, 'level' => 'call']], $routes[1]['grants']);
|
|
self::assertSame('app_home_index', SecurityRoutes::defaultName('App\Controller\HomeController', 'index'));
|
|
|
|
$security = ['role_hierarchy' => ['ROLE_ADMIN' => ['ROLE_EDITOR']], 'firewalls' => ['main' => []],
|
|
'access_control' => [['path' => '^/admin/stats', 'roles' => 'ROLE_ADMIN'], ['path' => '^/admin', 'roles' => 'ROLE_EDITOR']]];
|
|
$m = SecurityRoutes::matrix($routes, $security);
|
|
self::assertSame(['ROLE_ADMIN', 'ROLE_EDITOR'], $m['roles']);
|
|
// columns: anonymous, ROLE_ADMIN, ROLE_EDITOR
|
|
self::assertSame(['no', 'yes', 'yes'], $m['rows'][0]['cells']);
|
|
self::assertSame(['no', 'voter', 'voter'], $m['rows'][1]['cells']);
|
|
self::assertSame(['no', 'yes', 'no'], $m['rows'][2]['cells']);
|
|
self::assertSame(0, $m['rows'][2]['rule']);
|
|
}
|
|
|
|
public function testIsGrantedIsAddedAndRemovedInPlace(): void
|
|
{
|
|
$after = SecurityRoutes::addIsGranted(self::CONTROLLER, 'stats', 'ROLE_ADMIN');
|
|
self::assertSame(str_replace(" #[Route('/stats')]\n", " #[Route('/stats')]\n #[IsGranted('ROLE_ADMIN')]\n", self::CONTROLLER), $after);
|
|
$after = SecurityRoutes::addIsGranted(self::CONTROLLER, null, 'ROLE_USER');
|
|
self::assertStringContainsString("#[Route('/admin', name: 'admin_')]\n#[IsGranted('ROLE_USER')]\nfinal class", $after);
|
|
self::assertSame(str_replace(" #[IsGranted('POST_EDIT', subject: 'post')]\n", '', self::CONTROLLER), SecurityRoutes::removeIsGranted(self::CONTROLLER, 'edit', 0));
|
|
$bare = str_replace("use Symfony\\Component\\Security\\Http\\Attribute\\IsGranted;\n", '', self::CONTROLLER);
|
|
self::assertStringContainsString("use Symfony\\Component\\Routing\\Attribute\\Route;\nuse Symfony\\Component\\Security\\Http\\Attribute\\IsGranted;\n", SecurityRoutes::addIsGranted($bare, 'index', 'ROLE_X'));
|
|
}
|
|
|
|
public function testGeneratorsWriteValidPhpAndConfig(): void
|
|
{
|
|
$gen = new SecurityGenerator();
|
|
$user = $gen->user(['class' => 'User', 'identifier' => 'email'], self::security());
|
|
self::assertSame(['src/Entity/User.php', 'src/Repository/UserRepository.php'], array_keys($user['files']));
|
|
self::assertSame(['app_user_provider' => ['entity' => ['class' => 'App\Entity\User', 'property' => 'email']]], $user['security']['providers']);
|
|
self::assertSame('app_user_provider', $user['security']['firewalls']['main']['provider']);
|
|
self::assertArrayNotHasKey('provider', $user['security']['firewalls']['dev']);
|
|
$out = SecurityConfig::write(self::RECIPE, $user['security']);
|
|
self::assertStringContainsString(" providers:\n app_user_provider:\n entity:\n class: App\\Entity\\User\n property: email\n", $out);
|
|
self::assertStringContainsString(" provider: app_user_provider\n", $out);
|
|
|
|
$login = $gen->loginForm(['firewall' => 'main', 'rememberMe' => true, 'authenticator' => true], $user['security']);
|
|
self::assertSame(['src/Controller/SecurityController.php', 'templates/security/login.html.twig', 'src/Security/LoginFormAuthenticator.php'], array_keys($login['files']));
|
|
self::assertSame(['App\Security\LoginFormAuthenticator'], $login['security']['firewalls']['main']['custom_authenticators']);
|
|
self::assertSame(['path' => 'app_logout'], $login['security']['firewalls']['main']['logout']);
|
|
$plain = $gen->loginForm([], self::security());
|
|
self::assertSame(['login_path' => 'app_login', 'check_path' => 'app_login', 'enable_csrf' => true], $plain['security']['firewalls']['main']['form_login']);
|
|
|
|
$voter = $gen->voter(['name' => 'Post', 'attributes' => ['view', 'post edit'], 'subject' => 'App\Entity\Post']);
|
|
$code = $voter['files']['src/Security/Voter/PostVoter.php'];
|
|
self::assertStringContainsString(" public const VIEW = 'VIEW';\n public const POST_EDIT = 'POST_EDIT';", $code);
|
|
self::assertStringContainsString("return in_array(\$attribute, [self::VIEW, self::POST_EDIT], true)\n && \$subject instanceof Post;", $code);
|
|
self::assertStringContainsString('TokenInterface $token, ?Vote $vote = null): bool', $code);
|
|
self::assertStringNotContainsString('?Vote', (new SecurityGenerator(voteParam: false))->voter(['name' => 'X'])['files']['src/Security/Voter/XVoter.php']);
|
|
|
|
$auth = $gen->authenticator(['name' => 'ApiKeyAuthenticator', 'header' => 'X-API-KEY', 'firewall' => 'main'], self::security());
|
|
self::assertSame(['App\Security\ApiKeyAuthenticator'], $auth['security']['firewalls']['main']['custom_authenticators']);
|
|
|
|
$jwt = $gen->jwt([], self::security());
|
|
self::assertSame(['dev', 'login', 'api', 'main'], array_keys($jwt['security']['firewalls']));
|
|
self::assertNull($jwt['security']['firewalls']['api']['jwt']);
|
|
self::assertSame("api_login_check:\n path: /api/login_check\n", $jwt['files']['config/routes/jwt.yaml']);
|
|
$out = SecurityConfig::write(self::RECIPE, $jwt['security']);
|
|
self::assertSame($jwt['security'], Yaml::parse($out)['security']);
|
|
self::assertStringContainsString(" jwt: ~\n", $out);
|
|
|
|
$all = [...$user['files'], ...$login['files'], ...$voter['files'], ...$auth['files'], ...$gen->registration([])['files'], ...$gen->resetPassword([])['files']];
|
|
foreach ($all as $path => $content) {
|
|
if (str_ends_with($path, '.php')) {
|
|
self::assertNotEmpty(ValidationPhp::parse($content), $path);
|
|
}
|
|
}
|
|
self::assertArrayHasKey('config/packages/reset_password.yaml', $gen->resetPassword([])['files']);
|
|
}
|
|
|
|
public function testTheCommandsReturnFilesBeforeAndAfter(): void
|
|
{
|
|
$ws = new MemoryWorkspace(['composer.json' => '{"require":{"symfony/security-bundle":"*","doctrine/orm":"*"},"autoload":{"psr-4":{"App\\\\":"src/"}}}',
|
|
SecurityConfig::PATH => self::RECIPE, 'src/Controller/AdminController.php' => self::CONTROLLER]);
|
|
self::assertTrue(SecurityCommands::applies($ws));
|
|
$c = [];
|
|
SecurityCommands::register(function (string $n, callable $h) use (&$c) { $c[$n] = $h; }, $ws);
|
|
$r = $c['security.read']([]);
|
|
self::assertTrue($r['exists']);
|
|
self::assertTrue($r['bundles']['doctrine']);
|
|
self::assertFalse($r['bundles']['jwt']);
|
|
self::assertSame(15, $r['lines']['firewalls.main']);
|
|
$s = $r['security'];
|
|
$s['firewalls']['main']['lazy'] = false;
|
|
$p = $c['security.preview'](['security' => $s]);
|
|
self::assertSame(str_replace('lazy: true', 'lazy: false', self::RECIPE), $p['files'][0]['after']);
|
|
self::assertSame(self::RECIPE, $ws->read(SecurityConfig::PATH));
|
|
$g = $c['security.generate'](['kind' => 'user', 'spec' => []]);
|
|
self::assertSame(['src/Entity/User.php', 'src/Repository/UserRepository.php', SecurityConfig::PATH], array_column($g['files'], 'path'));
|
|
$m = $c['security.match'](['request' => ['path' => '/_profiler/x']]);
|
|
self::assertSame('dev', $m['firewall']);
|
|
self::assertSame(3, count($c['security.routes']([])['rows']));
|
|
}
|
|
}
|