Skip to content
Closed
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
7 changes: 6 additions & 1 deletion src/Validator/Rules/QueryComplexity.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ class QueryComplexity extends QuerySecurityRule
*/
private bool $variableCoercionFailed = false;

/** @var array<string, int> Complexity of each fragment by name; reset per document */
private array $fragmentComplexities = [];

/** @throws \InvalidArgumentException */
public function __construct(int $maxQueryComplexity)
{
Expand All @@ -66,6 +69,7 @@ public function getVisitor(QueryValidationContext $context): array
$this->fieldNodeAndDefs = new \ArrayObject();
$this->coercedVariableValues = null;
$this->variableCoercionFailed = false;
$this->fragmentComplexities = [];

return $this->invokeIfNeeded(
$context,
Expand Down Expand Up @@ -184,7 +188,8 @@ protected function nodeComplexity(SelectionNode $node): int
$fragment = $this->getFragment($node);

if ($fragment !== null) {
return $this->fieldComplexity($fragment->selectionSet);
// Score each fragment once, so spreading it repeatedly does not re-walk it
return $this->fragmentComplexities[$fragment->name->value] ??= $this->fieldComplexity($fragment->selectionSet);
}
}

Expand Down
30 changes: 26 additions & 4 deletions src/Validator/Rules/QueryDepth.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ class QueryDepth extends QuerySecurityRule
/** @var array<string, bool> Fragment names which are already calculated in recursion */
protected array $calculatedFragments = [];

/** @var array<string, int> Depth of each fragment relative to where it is spread, -1 when it has no nested selections; reset per document */
private array $fragmentDepths = [];

/** @var array<string, bool> Fragment names which contain a cycle; reset per document */
private array $cyclicFragments = [];

protected int $maxQueryDepth;

/** @throws \InvalidArgumentException */
Expand All @@ -28,6 +34,9 @@ public function __construct(int $maxQueryDepth)

public function getVisitor(QueryValidationContext $context): array
{
$this->fragmentDepths = [];
$this->cyclicFragments = [];

return $this->invokeIfNeeded(
$context,
[
Expand Down Expand Up @@ -86,13 +95,26 @@ protected function nodeDepth(Node $node, int $depth = 0, int $maxDepth = 0): int

if ($fragment !== null) {
$name = $fragment->name->value;
if (isset($this->calculatedFragments[$name])) {
if (isset($this->calculatedFragments[$name]) || isset($this->cyclicFragments[$name])) {
$this->cyclicFragments += $this->calculatedFragments;

return $this->maxQueryDepth + 1;
}

$this->calculatedFragments[$name] = true;
$maxDepth = $this->fieldDepth($fragment, $depth, $maxDepth);
unset($this->calculatedFragments[$name]);
// Measure each fragment once, so spreading it repeatedly does not re-walk it
if (! isset($this->fragmentDepths[$name])) {
$this->calculatedFragments[$name] = true;
$fragmentDepth = $this->fieldDepth($fragment, 0, -1);
unset($this->calculatedFragments[$name]);

if (isset($this->cyclicFragments[$name])) {
return $this->maxQueryDepth + 1;
}

$this->fragmentDepths[$name] = $fragmentDepth;
}

$maxDepth = max($maxDepth, $depth + $this->fragmentDepths[$name]);
}

break;
Expand Down
36 changes: 36 additions & 0 deletions tests/Validator/QueryComplexityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,42 @@ public function fragmentQueriesOnRootProvider(): iterable
yield ['query { ...humanFragment } fragment humanFragment on QueryRoot { human { dogs { name } } }'];
}

/** @dataProvider repeatedFragmentSpreadsProvider */
public function testRepeatedFragmentSpreads(int $levels): void
{
$query = "query MyQuery { human { ...F{$levels} } } fragment F0 on Human { firstName }";

foreach (range(1, $levels) as $level) {
$previous = $level - 1;
$query .= " fragment F{$level} on Human { dogs { master { ...F{$previous} ...F{$previous} } } }";
}

// human (1) + F{n}, where F0 = 1 and F{n} = dogs (10) + master (1) + 2 * F{n-1}
$complexity = 12 * 2 ** $levels - 10;

$this->assertDocumentValidator($query, $complexity);
$this->assertDocumentValidator($query, $complexity - 1, [self::createFormattedError($complexity - 1, $complexity)]);
}

/** @return iterable<array{int}> */
public static function repeatedFragmentSpreadsProvider(): iterable
{
yield [1];
yield [4];
yield [50]; // Would never finish if each spread re-walked its fragment
}

public function testRepeatedFragmentSpreadsWithDirectives(): void
{
$query = 'query MyQuery($withDogs: Boolean!) { human { ...F1 } jeremy: human(name: "Jeremy") { ...F1 ...F1 } } fragment F1 on Human { firstName dogs(name: "Root") @include(if: $withDogs) { name } }';

$this->getRule()->setRawVariableValues(['withDogs' => true]);
$this->assertDocumentValidators($query, 11, 12);

$this->getRule()->setRawVariableValues(['withDogs' => false]);
$this->assertDocumentValidators($query, 5, 6);
}

public function testAliasesQueries(): void
{
$query = 'query MyQuery { thomas: human(name: "Thomas") { firstName } jeremy: human(name: "Jeremy") { firstName } }';
Expand Down
51 changes: 51 additions & 0 deletions tests/Validator/QueryDepthTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,57 @@ public function testInfiniteRecursion(): void
$this->assertDocumentValidator($query, 7, [self::createFormattedError(7, 8)]);
}

public function testFragmentSpreadAtDifferentDepths(): void
{
$query = 'query MyQuery { human { ...F1 dogs { master { ...F1 } } } } fragment F1 on Human { dogs { name } }';

$this->assertDocumentValidator($query, 3);
$this->assertDocumentValidator($query, 2, [self::createFormattedError(2, 3)]);
}

/** @dataProvider repeatedFragmentSpreadsProvider */
public function testRepeatedFragmentSpreads(int $levels): void
{
$query = $this->buildRepeatedFragmentSpreadsQuery($levels);
$depth = 2 * $levels;

$this->assertDocumentValidator($query, $depth);
$this->assertDocumentValidator($query, $depth - 1, [self::createFormattedError($depth - 1, $depth)]);
}

/** @return iterable<array{int}> */
public static function repeatedFragmentSpreadsProvider(): iterable
{
yield [1];
yield [4];
yield [50]; // Would never finish if each spread re-walked its fragment
}

/** Each fragment spreads the one below it twice, so the expanded query doubles in size per level. */
private function buildRepeatedFragmentSpreadsQuery(int $levels): string
{
$query = "query MyQuery { human { ...F{$levels} } } fragment F0 on Human { firstName }";

foreach (range(1, $levels) as $level) {
$previous = $level - 1;
$query .= " fragment F{$level} on Human { dogs { master { ...F{$previous} ...F{$previous} } } }";
}

return $query;
}

public function testInfiniteRecursionWithRepeatedFragmentSpreads(): void
{
$query = 'query MyQuery { human { ...F0 } } fragment F50 on Human { ...F0 }';

foreach (range(0, 49) as $level) {
$next = $level + 1;
$query .= " fragment F{$level} on Human { ...F{$next} ...F{$next} }";
}

$this->assertDocumentValidator($query, 7, [self::createFormattedError(7, 8)]);
}

/** @return iterable<array{0: int, 1?: int, 2?: array<int, array<string, mixed>>}> */
public static function queryDataProvider(): iterable
{
Expand Down