如何在Laravel Lighthouse中检查查询的深度和复杂度
<p>在将lighthouse部署到生产服务器之前,我会检查安全性(https://www.howtographql.com/advanced/4-security/)。因此,我决定检查查询深度和查询复杂度。</p>
<p>在lighthouse文档中,他们提到了<code>config/lighthouse.php</code>。</p>
<pre class="brush:php;toolbar:false;">/*
|--------------------------------------------------------------------------
| Security
|--------------------------------------------------------------------------
|
| 控制Lighthouse处理与安全相关的查询验证。
| 详细阅读: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>并且推荐阅读https://webonyx.github.io/graphql-php/security/。</p>
<p>在这个链接中,他们给出了一些示例:</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>但是如何在lighthouse中应用这些呢?</p>
<p>首先,我将这些代码写入了<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>但是这样无法捕获任何问题。</p>
<p>我认为lighthouse在<code>vendor/nuwave/.../GraphQLController.php</code>中启动,所以我无法执行<code>GraphQL::executeQuery(/*...*/);</code></p>
<p><code>@complexity</code>指令也不起作用,<code>@complexity(resolver: "App\\Security\\ComplexityAnalyzer@userPosts")</code>不会调用userPosts函数。</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>我错过了什么?请帮助我睡个舒服觉。</p>