diff --git a/src/Database/Validator/Index.php b/src/Database/Validator/Index.php index 2270a6e0f..5452471cb 100644 --- a/src/Database/Validator/Index.php +++ b/src/Database/Validator/Index.php @@ -176,8 +176,12 @@ public function checkIndexLength(Document $index): bool $total = 0; $lengths = $index->getAttribute('lengths', []); - - foreach ($index->getAttribute('attributes', []) as $attributePosition => $attributeName) { + $attributes = $index->getAttribute('attributes', []); + if (count($lengths) > count($attributes)) { + $this->message = 'Invalid index lengths. Count of lengths must be equal or less than the number of attributes.'; + return false; + } + foreach ($attributes as $attributePosition => $attributeName) { $attribute = $this->attributes[\strtolower($attributeName)]; switch ($attribute->getAttribute('type')) { @@ -194,6 +198,10 @@ public function checkIndexLength(Document $index): bool $indexLength = 1; break; } + if ($indexLength < 0) { + $this->message = 'Negative index length provided for ' . $attributeName; + return false; + } if ($attribute->getAttribute('array', false)) { $attributeSize = Database::ARRAY_INDEX_LENGTH; diff --git a/tests/e2e/Adapter/Scopes/IndexTests.php b/tests/e2e/Adapter/Scopes/IndexTests.php index 6e0069d54..6bb563379 100644 --- a/tests/e2e/Adapter/Scopes/IndexTests.php +++ b/tests/e2e/Adapter/Scopes/IndexTests.php @@ -243,6 +243,49 @@ public function testIndexValidation(): void } catch (Exception $e) { $this->assertEquals($errorMessage, $e->getMessage()); } + + + $indexes = [ + new Document([ + '$id' => ID::custom('index_negative_length'), + 'type' => Database::INDEX_KEY, + 'attributes' => ['title1'], + 'lengths' => [-1], + 'orders' => [], + ]), + ]; + + $errorMessage = 'Negative index length provided for title1'; + $this->assertFalse($validator->isValid($indexes[0])); + $this->assertEquals($errorMessage, $validator->getDescription()); + + try { + static::getDatabase()->createCollection(ID::unique(), $attributes, $indexes); + $this->fail('Failed to throw exception'); + } catch (Exception $e) { + $this->assertEquals($errorMessage, $e->getMessage()); + } + + $indexes = [ + new Document([ + '$id' => ID::custom('index_extra_lengths'), + 'type' => Database::INDEX_KEY, + 'attributes' => ['title1', 'title2'], + 'lengths' => [100, 100, 100], + 'orders' => [], + ]), + ]; + + $errorMessage = 'Invalid index lengths. Count of lengths must be equal or less than the number of attributes.'; + $this->assertFalse($validator->isValid($indexes[0])); + $this->assertEquals($errorMessage, $validator->getDescription()); + + try { + static::getDatabase()->createCollection(ID::unique(), $attributes, $indexes); + $this->fail('Failed to throw exception'); + } catch (Exception $e) { + $this->assertEquals($errorMessage, $e->getMessage()); + } } public function testRenameIndex(): void