Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support security_post_denormalization and custom controllers #16

Draft
wants to merge 3 commits into
base: add-tests
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions src/AccessControl/RouteAccessControlFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,8 @@ public function __construct(

public function createRouteAccessControlData(string $name, Route $route): RouteAccessControlData
{
$controller = $route->getDefault('_controller');

$expression = RouteAccessControlData::NOT_API_PLATFORM_ROUTE;

if ($controller && $this->isControllerCorrespondingToApiPlatform($controller)) {
if ($this->isControllerCorrespondingToApiPlatform($route)) {
$expression = $this->getAccessControlExpressionForApiPlatform($route);
}

Expand All @@ -38,11 +35,14 @@ public function createRouteAccessControlData(string $name, Route $route): RouteA
return $accessControlRouteData;
}

protected function isControllerCorrespondingToApiPlatform(string $controller): bool
protected function isControllerCorrespondingToApiPlatform(Route $route): bool
{
$controller = $route->getDefault('_controller');
$resourceClass = $route->getDefault('_api_resource_class');

$apiPlatformPrefix = 'api_platform';

return 0 === mb_strpos($controller, $apiPlatformPrefix);
return 0 === mb_strpos($controller, $apiPlatformPrefix) || null !== $resourceClass;
}

protected function getAccessControlExpressionForApiPlatform(Route $route): string
Expand All @@ -57,7 +57,7 @@ protected function getAccessControlExpressionForApiPlatform(Route $route): strin
$resourceMetadata = $this->resourceMetadataCollectionFactory->create($resourceClass);
$operation = $resourceMetadata->getOperation($operationName);

$isGranted = $operation->getSecurity();
$isGranted = $operation->getSecurity() ?? $operation->getSecurityPostDenormalize();
if (null === $isGranted) {
$isGranted = RouteAccessControlData::NO_ACCESS_CONTROL;
}
Expand Down
6 changes: 3 additions & 3 deletions src/Command/AccessControlCheckerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

namespace Theodo\AccentBundle\Command;

use Theodo\AccentBundle\AccessControl\AccentReportFactory;
use Theodo\AccentBundle\Descriptor\AccessControlDescriptor;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Theodo\AccentBundle\AccessControl\AccentReportFactory;
use Theodo\AccentBundle\Descriptor\AccessControlDescriptor;

#[AsCommand('theodo:access-control', 'Check access control for each route.')]
class AccessControlCheckerCommand extends Command
Expand Down Expand Up @@ -54,7 +54,7 @@ protected function execute(InputInterface $input, OutputInterface $output)

$output->writeln($accentReport->getUnprotectedRoutesCount().' unprotected route(s)');

$exitCode = (0 < $accentReport->getUnprotectedRoutesCount()) ? 1 : 0;
$exitCode = (0 < $accentReport->getUnprotectedRoutesCount()) ? Command::FAILURE : Command::SUCCESS;

return $exitCode;
}
Expand Down
4 changes: 3 additions & 1 deletion src/Descriptor/AccessControlDescriptor.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@

namespace Theodo\AccentBundle\Descriptor;

use Theodo\AccentBundle\AccessControl\RouteAccessControlData;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Output\OutputInterface;
use Theodo\AccentBundle\AccessControl\RouteAccessControlData;

class AccessControlDescriptor
{
public const ACCESS_CONTROL_TRANSLATIONS = [
RouteAccessControlData::NO_ACCESS_CONTROL => '<fg=white;bg=red>No access control.</>',
RouteAccessControlData::NOT_API_PLATFORM_ROUTE => 'This route is not linked to API Platform.',
RouteAccessControlData::RESOURCE_NOT_FOUND => 'The resource linked to his route was not found.',
RouteAccessControlData::OPERATION_NOT_FOUND => 'This route does not seem to be linked to a valid operation.',
RouteAccessControlData::RESOURCE_UNRELATED_ROUTE => 'This route is not linked to a resource',
];

private $output;

/**
Expand Down
89 changes: 46 additions & 43 deletions tests/BundleInitializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,58 +2,20 @@

declare(strict_types=1);

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Nyholm\BundleTest\TestKernel;
use ApiPlatform\Symfony\Bundle\ApiPlatformBundle;
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Nyholm\BundleTest\TestKernel;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\KernelInterface;
use Theodo\AccentBundle\TheodoAccentBundle;
use Theodo\AccentBundle\AccessControl\AccentReportFactory;
use Theodo\AccentBundle\AccessControl\RouteAccessControlData;
use Theodo\AccentBundle\TheodoAccentBundle;

class BundleInitializationTest extends KernelTestCase
{
protected static function getKernelClass(): string
{
return TestKernel::class;
}

protected static function createKernel(array $options = []): KernelInterface
{
/**
* @var TestKernel $kernel
*/
$kernel = parent::createKernel($options);
$kernel->addTestBundle(DoctrineBundle::class);
$kernel->addTestBundle(ApiPlatformBundle::class);
$kernel->addTestBundle(TheodoAccentBundle::class);
$kernel->addTestConfig(__DIR__.'/config/packages/doctrine.yaml');
$kernel->addTestConfig(__DIR__.'/config/packages/api_platform.yaml');
$kernel->addTestRoutingFile(__DIR__.'/config/routes.yaml');

// Unused, non public services are removed during kernel boot.
// We force them as public during test.
$kernel->addTestCompilerPass(new class () implements CompilerPassInterface {
public function process(ContainerBuilder $container): void
{
$services = $container->getDefinitions() + $container->getAliases();

foreach ($services as $id => $definition) {
if (stripos($id, 'theodo_accent') === 0) {
$definition->setPublic(true);
}
}
}
});

$kernel->handleOptions($options);

return $kernel;
}

public function testInitBundle(): void
{
$container = self::getContainer();
Expand All @@ -80,18 +42,59 @@ public function testExposedRoutes(): void
fn ($route) => RouteAccessControlData::RESOURCE_UNRELATED_ROUTE !== $route->getExpression()
);

$this->assertCount(3, $resourceRelatedRoutes);
$this->assertCount(6, $resourceRelatedRoutes);
$checkedRoutes = [];
foreach($resourceRelatedRoutes as $routeData) {
foreach ($resourceRelatedRoutes as $routeData) {
$checkedRoutes[$routeData->getRouteName()] = $routeData->getExpression();
}

$expectedRoutes = [
'_api_/books/{id}{._format}_get' => "is_granted('ROLE_USER_GET')",
'_api_/books{._format}_post' => "is_granted('ROLE_USER_DEFAULT')",
'_api_/books/{id}{._format}_patch' => "is_granted('ROLE_USER_PATCH')",
'_api_/authors/{id}{._format}_put' => "is_granted('ROLE_USER_PUT')",
'_api_/authors/{id}{._format}_get' => "is_granted('ROLE_USER_GET')",
'book_get_publication' => "is_granted('ROLE_USER_CUSTOM_CONTROLLER')",
];

$this->assertEquals($expectedRoutes, $checkedRoutes);
}

protected static function getKernelClass(): string
{
return TestKernel::class;
}

protected static function createKernel(array $options = []): KernelInterface
{
/**
* @var TestKernel $kernel
*/
$kernel = parent::createKernel($options);
$kernel->addTestBundle(DoctrineBundle::class);
$kernel->addTestBundle(ApiPlatformBundle::class);
$kernel->addTestBundle(TheodoAccentBundle::class);
$kernel->addTestConfig(__DIR__.'/config/packages/doctrine.yaml');
$kernel->addTestConfig(__DIR__.'/config/packages/api_platform.yaml');
$kernel->addTestRoutingFile(__DIR__.'/config/routes.yaml');

// Unused, non public services are removed during kernel boot.
// We force them as public during test.
$kernel->addTestCompilerPass(new class() implements CompilerPassInterface {
public function process(ContainerBuilder $container): void
{
$services = $container->getDefinitions() + $container->getAliases();

foreach ($services as $id => $definition) {
if (0 === mb_stripos($id, 'theodo_accent')) {
$definition->setPublic(true);
}
}
}
});

$kernel->handleOptions($options);

return $kernel;
}
}
18 changes: 18 additions & 0 deletions tests/Controller/BookController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace App\Controller;

use App\Entity\Book;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpKernel\Attribute\AsController;

#[AsController]
class BookController extends AbstractController
{
public function __invoke(): Book
{
return new Book();
}
}
19 changes: 19 additions & 0 deletions tests/Entity/Author.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Put;

#[ApiResource()]
#[Get(security: "is_granted('ROLE_USER_GET')")]
#[Put(securityPostDenormalize: "is_granted('ROLE_USER_PUT')")]
class Author
{
public ?int $id = null;

public ?string $name = null;
}
9 changes: 6 additions & 3 deletions tests/Entity/Book.php
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
<?php

declare(strict_types=1);

namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;

#[ApiResource(security:"is_granted('ROLE_USER_DEFAULT')")]
#[Get(security:"is_granted('ROLE_USER_GET')")]
#[ApiResource(security: "is_granted('ROLE_USER_DEFAULT')")]
#[Get(security: "is_granted('ROLE_USER_GET')")]
#[Get(name: 'publication', routeName: 'book_get_publication', security: "is_granted('ROLE_USER_CUSTOM_CONTROLLER')")]
#[Post]
#[Patch(security:"is_granted('ROLE_USER_PATCH')")]
#[Patch(security: "is_granted('ROLE_USER_PATCH')")]
class Book
{
public ?int $id = null;
Expand Down
8 changes: 8 additions & 0 deletions tests/config/routes.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,11 @@ api_platform:
resource: .
type: api_platform
prefix: /api

book_get_publication:
path: /books/{id}/publication
methods: ["GET"]
defaults:
_controller: App\Controller\BookController
_api_resource_class: App\Entity\Book
_api_operation_name: book_get_publication