Skip to content
Merged
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
61 changes: 51 additions & 10 deletions src/Database/Trait/Documents.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down Expand Up @@ -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<string> $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;
}
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions tests/e2e/Adapter/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -51,6 +52,7 @@ abstract class Base extends TestCase
{
use AggregationTests;
use AttributeTests;
use CaseVariantUpsertTests;
use CollectionTests;
use CursorTests;
use CustomDocumentTypeTests;
Expand Down
106 changes: 106 additions & 0 deletions tests/e2e/Adapter/Scopes/CaseVariantUpsertTests.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

namespace Tests\E2E\Adapter\Scopes;

use Utopia\Database\Adapter\Feature;
use Utopia\Database\Attribute;
use Utopia\Database\Collection;
use Utopia\Database\Document;
use Utopia\Database\Exception\Authorization as AuthorizationException;
use Utopia\Database\Permission;
use Utopia\Database\Query;
use Utopia\Database\Role;

/**
* Where an adapter reads a case variant of a stored id as that document (MariaDB and MySQL through the default
* collation, Postgres through utf8_ci_ai, SQLite through its collation), an upsert through the variant is an
* update of the stored document, never a create that overwrites it. Adapters that keep the variant a separate
* id skip the test.
*/
trait CaseVariantUpsertTests
{
public function testCaseVariantUpsertIsAuthorizedAsAnUpdate(): void
{
$database = $this->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');
}
}
3 changes: 2 additions & 1 deletion tests/unit/Adapter/RedisUniqueIndexTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand Down
Loading