How to check query depth and complexity in Laravel Lighthouse
<p>Before deploying lighthouse to a production server, I check security (https://www.howtographql.com/advanced/4-security/). So I decided to check query depth and query complexity. </p>
<p>In the lighthouse documentation, they mention <code>config/lighthouse.php</code>. </p>
<pre class="brush:php;toolbar:false;">/*
|------------------------------------------------- -----------------------
| Security
|------------------------------------------------- -----------------------
|
| Control Lighthouse to handle security-related query verification.
| Detailed reading: https://webonyx.github.io/graphql-php/security/
|
*/
'security' => [
'max_query_complexity' => \GraphQL\Validator\Rules\QueryComplexity::DISABLED,
'max_query_depth' => \GraphQL\Validator\Rules\QueryDepth::DISABLED,
'disable_introspection' => \GraphQL\Validator\Rules\DisableIntrospection::DISABLED,
],
</pre>
<p>And it is recommended to read https://webonyx.github.io/graphql-php/security/. </p>
<p>In this link they give some examples: </p>
<pre class="brush:php;toolbar:false;">use GraphQL\GraphQL;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\DocumentValidator;
$rule = new QueryComplexity($maxQueryComplexity = 100);
DocumentValidator::addRule($rule);
GraphQL::executeQuery(/*...*/);
</pre>
<pre class="brush:php;toolbar:false;">use GraphQL\GraphQL;
use GraphQL\Validator\Rules\QueryDepth;
use GraphQL\Validator\DocumentValidator;
$rule = new QueryDepth($maxDepth = 10);
DocumentValidator::addRule($rule);
GraphQL::executeQuery(/*...*/);
</pre>
<p>But how to apply these in lighthouse? </p>
<p>First, I wrote this code into <code>ExampleQuery.php(php artisan lighthouse:query ExampleQuery)</code>. </p>
<pre class="brush:php;toolbar:false;">final class ExampleQuery
{
public function __invoke(_, array $args)
{
$rule = new QueryComplexity(2);
DocumentValidator::addRule($rule);
$rule2 = new QueryDepth(2);
DocumentValidator::addRule($rule2);
return [
...
];
}
}
</pre>
<p>But this won't catch any problems.</p>
<p>I think lighthouse is started in <code>vendor/nuwave/.../GraphQLController.php</code> so I cannot execute <code>GraphQL::executeQuery(/*...*/ );</code></p>
The <p><code>@complexity</code> directive also does not work, <code>@complexity(resolver: "App\\Security\\ComplexityAnalyzer@userPosts")</code> will not be called userPosts function. </p>
<pre class="brush:php;toolbar:false;">class ComplexityAnalyzer {
public function userPosts(int $childrenComplexity, array $args): int // not called
{
$postComplexity = $args['includeFullText']
? 3
: 2;
\Log::Debug($postComplexity); // not called
return $childrenComplexity * $postComplexity;
}
}
</pre>
<p>What did I miss? Please help me sleep well. </p>