diff --git a/src/Database/Trait/Documents.php b/src/Database/Trait/Documents.php index 282704010..e9f9b5457 100644 --- a/src/Database/Trait/Documents.php +++ b/src/Database/Trait/Documents.php @@ -2412,6 +2412,11 @@ private function upsert( foreach ($documents as $key => $document) { $old = $existing[$this->upsertKey($document)] ?? new Document(); + // A case- or accent-variant id updates the stored document under its stored id, as updateDocument() does + if (! $old->isEmpty() && $old->getId() !== $document->getId()) { + $document->setAttribute(Document::ID, $old->getId()); + } + $document = $this->removeUnknownAttributes($collection, $document); $unchanged = $this->roundOperators($collection, $document); if (! $old->isEmpty()) { @@ -2716,20 +2721,56 @@ private function findDocumentsToUpsert(string $collection, array $documents): ar $batches[$key]['ids'][] = $document->getId(); } + $find = function (array $ids, int|string|null $tenant) use ($collection, $perTenant): array { + /** @var list $ids */ + $read = fn (): array => $this->authorization->skip(fn () => $this->silent(fn () => $this->skipQueryHooks(fn () => $this->find($collection, [ + Query::equal(Document::ID, $ids), + Query::limit($this->maxQueryValues), + ], forPermission: PermissionType::Update)))); + + return $perTenant ? $this->withTenant($tenant, $read) : $read(); + }; + $existing = []; - foreach ($batches as $batch) { + $found = []; + foreach ($batches as $batchKey => $batch) { foreach (\array_chunk(\array_values(\array_unique($batch['ids'])), \max(1, $this->maxQueryValues)) as $chunk) { - $read = fn (): array => $this->authorization->skip(fn () => $this->silent(fn () => $this->skipQueryHooks(fn () => $this->find($collection, [ - Query::equal(Document::ID, $chunk), - Query::limit($this->maxQueryValues), - ], forPermission: PermissionType::Update)))); + foreach ($find($chunk, $batch['tenant']) as $document) { + $existing[$this->upsertKey($document)] = $document; + $found[$batchKey] = true; + } + } + } - $found = $perTenant - ? $this->withTenant($batch['tenant'], $read) - : $read(); + // The engine compares ids in its own collation, which can ignore case and accents: a request for + // `ABC` then finds the stored `abc`, keyed under the stored spelling. The request would miss it, + // be authorized as a create, and overwrite `abc` through the unique `_uid` conflict. Whether `abc` + // was also requested exactly does not matter, so read the missed ids again on their own: any row + // that comes back is a variant of one of them, and only then is each missed id looked up alone. + // A variant is among the rows the batch already read, so a batch that read none has no variant. + foreach ($batches as $batchKey => $batch) { + if (! isset($found[$batchKey])) { + continue; + } - foreach ($found as $document) { - $existing[$this->upsertKey($document)] = $document; + $missed = []; + foreach (\array_unique($batch['ids']) as $id) { + $key = $perTenant ? $batch['tenant'].':'.$id : $id; + if (! isset($existing[$key])) { + $missed[$key] = $id; + } + } + + foreach (\array_chunk($missed, \max(1, $this->maxQueryValues), true) as $chunk) { + if ($find(\array_values($chunk), $batch['tenant']) === []) { + continue; + } + + foreach ($chunk as $key => $id) { + $stored = $find([$id], $batch['tenant'])[0] ?? null; + if ($stored instanceof Document) { + $existing[$key] = $stored; + } } } } diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index 7f7a1080f..19bf6a6ed 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -6,6 +6,7 @@ use PHPUnit\Framework\TestCase; use Tests\E2E\Adapter\Scopes\AggregationTests; use Tests\E2E\Adapter\Scopes\AttributeTests; +use Tests\E2E\Adapter\Scopes\CaseVariantUpsertTests; use Tests\E2E\Adapter\Scopes\CollectionTests; use Tests\E2E\Adapter\Scopes\CursorTests; use Tests\E2E\Adapter\Scopes\CustomDocumentTypeTests; @@ -51,6 +52,7 @@ abstract class Base extends TestCase { use AggregationTests; use AttributeTests; + use CaseVariantUpsertTests; use CollectionTests; use CursorTests; use CustomDocumentTypeTests; diff --git a/tests/e2e/Adapter/Scopes/CaseVariantUpsertTests.php b/tests/e2e/Adapter/Scopes/CaseVariantUpsertTests.php new file mode 100644 index 000000000..8ac69d869 --- /dev/null +++ b/tests/e2e/Adapter/Scopes/CaseVariantUpsertTests.php @@ -0,0 +1,106 @@ +getDatabase(); + if (! $database->getAdapter()->hasFeature(Feature\Upserts::class)) { + $this->expectNotToPerformAssertions(); + + return; + } + $auth = $database->getAuthorization(); + + $database->createCollection(Collection::create(id: 'caseVariantUpsert', permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + ], documentSecurity: true)); + $database->createAttribute('caseVariantUpsert', Attribute::string('name', 64)); + + $database->createDocument('caseVariantUpsert', new Document([ + '$id' => 'abc', + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::user('owner')), + ], + 'name' => 'original', + ])); + + if ($database->getDocument('caseVariantUpsert', 'ABC')->isEmpty()) { + $database->deleteCollection('caseVariantUpsert'); + $this->expectNotToPerformAssertions(); + + return; + } + if ($database->find('caseVariantUpsert', [Query::equal('$id', ['ABC'])]) === []) { + $database->deleteCollection('caseVariantUpsert'); + $this->markTestSkipped('This adapter reads `ABC` as `abc` by id but not through find(), which the upsert lookup relies on'); + } + + try { + $auth->cleanRoles(); + $auth->addRole(Role::any()->toString()); + $auth->addRole(Role::user('intruder')->toString()); + + $variant = new Document([ + '$id' => 'ABC', + '$permissions' => [ + Permission::read(Role::user('intruder')), + Permission::update(Role::user('intruder')), + ], + 'name' => 'overwritten', + ]); + // An unchanged copy of the stored document, requested by its exact id, must not hide the variant + $unchanged = new Document(['$id' => 'abc', 'name' => 'original']); + + foreach ([[$unchanged, $variant], [$variant]] as $batch) { + try { + $database->upsertDocuments('caseVariantUpsert', $batch); + $this->fail('A case-variant upsert must be authorized as an update of the stored document'); + } catch (AuthorizationException) { + } + } + + $auth->cleanRoles(); + $auth->addRole(Role::any()->toString()); + $auth->addRole(Role::user('owner')->toString()); + + $upserted = []; + $database->upsertDocuments('caseVariantUpsert', [new Document([ + '$id' => 'ABC', + 'name' => 'renamed', + ])], onNext: function (Document $document) use (&$upserted): void { + $upserted[] = $document->getId(); + }); + $this->assertSame(['abc'], $upserted, 'The update must keep the stored id'); + } finally { + $auth->cleanRoles(); + $auth->addRole(Role::any()->toString()); + } + + $stored = $database->getDocument('caseVariantUpsert', 'abc'); + $this->assertSame('renamed', $stored->getAttribute('name')); + $this->assertContains(Permission::update(Role::user('owner')), $stored->getPermissions()); + $this->assertCount(1, $database->find('caseVariantUpsert')); + + $database->deleteCollection('caseVariantUpsert'); + } +} diff --git a/tests/unit/Adapter/RedisUniqueIndexTest.php b/tests/unit/Adapter/RedisUniqueIndexTest.php index a9b72b76a..60e2e5e22 100644 --- a/tests/unit/Adapter/RedisUniqueIndexTest.php +++ b/tests/unit/Adapter/RedisUniqueIndexTest.php @@ -141,7 +141,8 @@ public function testAnUpsertBatchReadsTheStoredDocumentsOnceForItsUniqueChecks() new Document(['$id' => 'fifth', 'email' => 'fifth@example.test']), ])); - $this->assertSame($single, $this->memberReads, 'The unique checks must read the collection once per batch, not once per document'); + // A batch that both updates and creates reads its missed ids once more, to find stored case or accent variants + $this->assertSame($single + 1, $this->memberReads, 'The unique checks must read the collection a fixed number of times per batch, not once per document'); $this->assertSame(['fifth@example.test', 'first-moved@example.test', 'fourth@example.test', 'moved@example.test', 'renamed@example.test'], $this->emails($database)); }