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

Add new configuration properties : introspection, maximum_query_complexity and maximum_query_depth #66

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public function getConfigTreeBuilder()
->children()
->enumNode('enable_login')->values(['on', 'off', 'auto'])->defaultValue('auto')->info('Enable to automatically create a login/logout mutation. "on": enable, "auto": enable if security bundle is available.')->end()
->enumNode('enable_me')->values(['on', 'off', 'auto'])->defaultValue('auto')->info('Enable to automatically create a "me" query to fetch the current user. "on": enable, "auto": enable if security bundle is available.')->end()
->booleanNode('introspection')->defaultValue(true)->info('Allow the introspection of the GraphQL API.')->end()
->integerNode('maximum_query_complexity')->info('Define a maximum query complexity value.')->end()
->integerNode('maximum_query_depth')->info('Define a maximum query depth value.')->end()
->scalarNode('firewall_name')->defaultValue('main')->info('The name of the firewall to use for login')->end()
->end()
->end()
Expand Down
20 changes: 20 additions & 0 deletions DependencyInjection/GraphqliteCompilerPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@

namespace TheCodingMachine\Graphqlite\Bundle\DependencyInjection;

use GraphQL\Server\ServerConfig;
use GraphQL\Validator\Rules\DisableIntrospection;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\QueryDepth;
use ReflectionNamedType;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Adapter\PhpFilesAdapter;
Expand Down Expand Up @@ -163,6 +167,22 @@ public function process(ContainerBuilder $container): void
}
}

// ServerConfig rules
$serverConfigDefinition = $container->findDefinition(ServerConfig::class);
$rulesDefinition = [];
if ($container->getParameter('graphqlite.security.introspection') === false) {
$rulesDefinition[] = $container->findDefinition(DisableIntrospection::class);
}
if ($container->getParameter('graphqlite.security.maximum_query_complexity')) {
$complexity = (int) $container->getParameter('graphqlite.security.maximum_query_complexity');
$rulesDefinition[] = $container->findDefinition(QueryComplexity::class)->setArgument(0, $complexity);
}
if ($container->getParameter('graphqlite.security.maximum_query_depth')) {
$depth = (int) $container->getParameter('graphqlite.security.maximum_query_depth');
$rulesDefinition[] = $container->findDefinition(QueryDepth::class)->setArgument(0, $depth);
}
$serverConfigDefinition->addMethodCall('setValidationRules', [$rulesDefinition]);

if ($disableMe === false) {
$this->registerController(MeController::class, $container);
}
Expand Down
3 changes: 3 additions & 0 deletions DependencyInjection/GraphqliteExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ public function load(array $configs, ContainerBuilder $container): void
$container->setParameter('graphqlite.namespace.types', $namespaceType);
$container->setParameter('graphqlite.security.enable_login', $enableLogin);
$container->setParameter('graphqlite.security.enable_me', $enableMe);
$container->setParameter('graphqlite.security.introspection', $configs[0]['security']['introspection'] ?? true);
$container->setParameter('graphqlite.security.maximum_query_complexity', $configs[0]['security']['maximum_query_complexity'] ?? null);
$container->setParameter('graphqlite.security.maximum_query_depth', $configs[0]['security']['maximum_query_depth'] ?? null);
$container->setParameter('graphqlite.security.firewall_name', $configs[0]['security']['firewall_name'] ?? 'main');

$loader->load('graphqlite.xml');
Expand Down
10 changes: 8 additions & 2 deletions Resources/config/container/graphqlite.xml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@

<service id="TheCodingMachine\GraphQLite\Security\AuthorizationServiceInterface" alias="TheCodingMachine\Graphqlite\Bundle\Security\AuthorizationService" />

<service id="GraphQL\Server\ServerConfig">
<service id="GraphQL\Server\ServerConfig" class="TheCodingMachine\Graphqlite\Bundle\Server\ServerConfig">
<call method="setSchema">
<argument type="service" id="TheCodingMachine\GraphQLite\Schema"/>
</call>
Expand All @@ -72,6 +72,12 @@
</call>
</service>

<service id="GraphQL\Validator\Rules\DisableIntrospection" />

<service id="GraphQL\Validator\Rules\QueryComplexity" />

<service id="GraphQL\Validator\Rules\QueryDepth" />

<service id="TheCodingMachine\GraphQLite\Mappers\StaticTypeMapper">
<tag name="graphql.type_mapper"/>
</service>
Expand Down Expand Up @@ -103,7 +109,7 @@
</argument>
<tag name="graphql.type_mapper_factory"/>
</service>

<service id="graphqlite.phpfilescache" class="Symfony\Component\Cache\Adapter\PhpFilesAdapter">
<argument>graphqlite</argument>
</service>
Expand Down
35 changes: 35 additions & 0 deletions Server/ServerConfig.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php


namespace TheCodingMachine\Graphqlite\Bundle\Server;

use GraphQL\Error\InvariantViolation;
use GraphQL\Utils\Utils;
use GraphQL\Validator\DocumentValidator;
use GraphQL\Validator\Rules\ValidationRule;
use function array_merge;
use function is_array;
use function is_callable;

/**
* A slightly modified version of the server config: default validators are added by default when setValidators is called.
*/
class ServerConfig extends \GraphQL\Server\ServerConfig
{
/**
* Set validation rules for this server, AND adds by default all the "default" validation rules provided by Webonyx
*
* @param ValidationRule[]|callable $validationRules
*
* @return \GraphQL\Server\ServerConfig
*
* @api
*/
public function setValidationRules($validationRules)
{
parent::setValidationRules(array_merge(DocumentValidator::defaultRules(), $validationRules));

return $this;
}

}
8 changes: 8 additions & 0 deletions Tests/Fixtures/Entities/Contact.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,12 @@ public function prefetchData(iterable $iterable, stdClass $someOtherService = nu
}
return 'OK';
}

/**
* @Field()
*/
public function getManager(): ?Contact
{
return null;
}
}
6 changes: 3 additions & 3 deletions Tests/Fixtures/Entities/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
namespace TheCodingMachine\Graphqlite\Bundle\Tests\Fixtures\Entities;


use TheCodingMachine\GraphQLite\Annotations\Field;

class Product
{
/**
Expand Down Expand Up @@ -36,6 +38,4 @@ public function getPrice(): float
{
return $this->price;
}


}
}
11 changes: 10 additions & 1 deletion Tests/Fixtures/Types/ProductType.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@

namespace TheCodingMachine\Graphqlite\Bundle\Tests\Fixtures\Types;

use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\SourceField;
use TheCodingMachine\GraphQLite\Annotations\Type;
use TheCodingMachine\Graphqlite\Bundle\Tests\Fixtures\Entities\Contact;
use TheCodingMachine\Graphqlite\Bundle\Tests\Fixtures\Entities\Product;


Expand All @@ -15,5 +17,12 @@
*/
class ProductType
{
/**
* @Field()
*/
public function getSeller(Product $product): ?Contact
{
return null;
}

}
}
105 changes: 105 additions & 0 deletions Tests/FunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ public function testNoLoginNoSessionQuery(): void

$result = json_decode($response->getContent(), true);

$this->assertArrayHasKey('errors', $result);
$this->assertSame('Cannot query field "login" on type "Mutation".', $result['errors'][0]['message']);
}

Expand Down Expand Up @@ -421,6 +422,110 @@ public function testValidation(): void
$this->assertSame('Validate', $errors[0]['extensions']['category']);
}

public function testWithIntrospection(): void
{
$kernel = new GraphqliteTestingKernel(true, null, true, null);
$kernel->boot();

$request = Request::create('/graphql', 'POST', ['query' => '
{
__schema {
queryType {
name
}
}
}
']);

$response = $kernel->handle($request);

$result = json_decode($response->getContent(), true);
$data = $result['data'];

$this->assertArrayHasKey('__schema', $data);
}

public function testDisableIntrospection(): void
{
$kernel = new GraphqliteTestingKernel(true, null, true, null, false, 2, 2);
$kernel->boot();

$request = Request::create('/graphql', 'POST', ['query' => '
{
__schema {
queryType {
name
}
}
}
']);

$response = $kernel->handle($request);

$result = json_decode($response->getContent(), true);
$errors = $result['errors'];

$this->assertSame('GraphQL introspection is not allowed, but the query contained __schema or __type', $errors[0]['message']);
}

public function testMaxQueryComplexity(): void
{
$kernel = new GraphqliteTestingKernel(true, null, true, null, false, 2, null);
$kernel->boot();

$request = Request::create('/graphql', 'POST', ['query' => '
{
products
{
name,
price,
seller {
name
}
}
}
']);

$response = $kernel->handle($request);

$result = json_decode($response->getContent(), true);
$errors = $result['errors'];

$this->assertSame('Max query complexity should be 2 but got 5.', $errors[0]['message']);
}

public function testMaxQueryDepth(): void
{
$kernel = new GraphqliteTestingKernel(true, null, true, null, false, null, 1);
$kernel->boot();

$request = Request::create('/graphql', 'POST', ['query' => '
{
products
{
name,
price,
seller {
name
manager {
name
manager {
name
}
}
}
}
}
']);

$response = $kernel->handle($request);

$result = json_decode($response->getContent(), true);
$errors = $result['errors'];

$this->assertSame('Max query depth should be 1 but got 3.', $errors[0]['message']);
}

private function logIn(ContainerInterface $container)
{
// put a token into the storage so the final calls can function
Expand Down
31 changes: 29 additions & 2 deletions Tests/GraphqliteTestingKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,29 @@ class GraphqliteTestingKernel extends Kernel
* @var string|null
*/
private $enableMe;
/**
* @var bool
*/
private $introspection;
/**
* @var int|null
*/
private $maximumQueryComplexity;
/**
* @var int|null
*/
private $maximumQueryDepth;

public function __construct(bool $enableSession = true, ?string $enableLogin = null, bool $enableSecurity = true, ?string $enableMe = null)
public function __construct(bool $enableSession = true, ?string $enableLogin = null, bool $enableSecurity = true, ?string $enableMe = null, bool $introspection = true, ?int $maximumQueryComplexity = null, ?int $maximumQueryDepth = null)
{
parent::__construct('test', true);
$this->enableSession = $enableSession;
$this->enableLogin = $enableLogin;
$this->enableSecurity = $enableSecurity;
$this->enableMe = $enableMe;
$this->introspection = $introspection;
$this->maximumQueryComplexity = $maximumQueryComplexity;
$this->maximumQueryDepth = $maximumQueryDepth;
}

public function registerBundles()
Expand Down Expand Up @@ -126,6 +141,18 @@ public function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
$graphqliteConf['security']['enable_me'] = $this->enableMe;
}

if ($this->introspection === false) {
$graphqliteConf['security']['introspection'] = false;
}

if ($this->maximumQueryComplexity !== null) {
$graphqliteConf['security']['maximum_query_complexity'] = $this->maximumQueryComplexity;
}

if ($this->maximumQueryDepth !== null) {
$graphqliteConf['security']['maximum_query_depth'] = $this->maximumQueryDepth;
}

$container->loadFromExtension('graphqlite', $graphqliteConf);
});
$confDir = $this->getProjectDir().'/Tests/Fixtures/config';
Expand All @@ -143,6 +170,6 @@ protected function configureRoutes(RouteCollectionBuilder $routes)

public function getCacheDir()
{
return __DIR__.'/../cache/'.($this->enableSession?'withSession':'withoutSession').$this->enableLogin.($this->enableSecurity?'withSecurity':'withoutSecurity').$this->enableMe;
return __DIR__.'/../cache/'.($this->enableSession?'withSession':'withoutSession').$this->enableLogin.($this->enableSecurity?'withSecurity':'withoutSecurity').$this->enableMe.'_'.($this->introspection?'withIntrospection':'withoutIntrospection').'_'.$this->maximumQueryComplexity.'_'.$this->maximumQueryDepth;
}
}