diff --git a/src/Database/Hook/Relationships.php b/src/Database/Hook/Relationships.php index 68f19ffb2..832891fac 100644 --- a/src/Database/Hook/Relationships.php +++ b/src/Database/Hook/Relationships.php @@ -1277,6 +1277,8 @@ public function afterDocumentUpdate(Document $collection, Document $old, Documen $removedDocuments = \array_values(\array_diff($oldIds, $newIds)); if (! empty($removedDocuments)) { + $this->authorizeUnlink($relatedCollection, $removedDocuments); + // Chunk to honor the validator's maxQueryValues cap; without // this a relationship update with thousands of removed // children would throw QueryException. @@ -3391,6 +3393,29 @@ private function authorizeLink(Document $collection, Document $related): void } } + /** + * Unlinking a related document changes it as much as linking it does, so it needs the same update + * permission on each one still stored. The unlink itself then writes with authorization skipped. + * + * @param list $ids + * + * @throws AuthorizationException + */ + private function authorizeUnlink(Document $relatedCollection, array $ids): void + { + foreach (\array_chunk(\array_values(\array_unique($ids)), $this->relationQueryChunkSize()) as $chunk) { + $stored = $this->database->getAuthorization()->skip(fn () => $this->database->skipRelationships(fn () => $this->database->skipQueryHooks(fn () => $this->database->find($relatedCollection->getId(), [ + Query::select([Document::ID, Document::PERMISSIONS]), + Query::equal(Document::ID, $chunk), + Query::limit(\count($chunk)), + ])))); + + foreach ($stored as $related) { + $this->authorizeLink($relatedCollection, $related); + } + } + } + /** * Prepare the related documents $document holds as documents, as deep as the write relates them, replacing its * relationship values with prepared copies so the caller's related documents are not changed. Each copy is first @@ -3614,15 +3639,34 @@ private function authorizeRelated(Document $collection, Document $document, ?Doc $value = $value->isArrayOperation() ? $this->applyRelationshipOperator($value, $linked) : []; } + $kept = []; foreach (self::relatedValues($value) as $related) { if (\is_string($related)) { + $kept[] = $related; $this->authorizeLinkById($relatedCollection, $related, $linked, $writes, $resolve); continue; } + $kept[] = $related->getId(); $this->authorizeRelatedDocument($collection, $relatedCollection, $related, $linked, $writes, $writeStack, $resolve); } + + // Unlinking a one-to-many child writes the child's own key, so it needs what the write's authorizeUnlink() checks + $operator = $document->getAttribute($key); + if ($writes && ! ($operator instanceof Operator && ! $operator->isArrayOperation()) && ($relationship->type === RelationshipType::OneToMany || $relationship->type === RelationshipType::ManyToOne)) { + $unstaged = []; + foreach (\array_values(\array_diff($linked, $kept)) as $removed) { + $staged = $resolve === null ? null : $resolve($relatedCollection->getId(), $removed); + if ($staged === null) { + $unstaged[] = $removed; + } elseif (! $staged->isEmpty()) { + $this->authorizeLink($relatedCollection, $staged); + } + } + // Stored children are read in chunks, as the write reads them + $this->authorizeUnlink($relatedCollection, $unstaged); + } } } diff --git a/tests/e2e/Adapter/Scopes/PermissionTests.php b/tests/e2e/Adapter/Scopes/PermissionTests.php index 31a704235..3a009a844 100644 --- a/tests/e2e/Adapter/Scopes/PermissionTests.php +++ b/tests/e2e/Adapter/Scopes/PermissionTests.php @@ -1882,11 +1882,24 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void '$id' => 'child2', ], ]); + + // Replacing child1 unlinks it, which writes child1's parent key: that needs update permission on child1 + try { + $database->updateDocument('parentRelationTest', 'parent1', $parent); + $this->fail('Unlinking a child the caller cannot update must be refused'); + } catch (AuthorizationException) { + } + + $children = $database->getDocument('parentRelationTest', 'parent1')->getDocuments('children'); + $this->assertSame(['child1'], \array_map(fn (Document $child) => $child->getId(), $children)); + + // Adding a child without removing one only creates it, which the collection's create permission allows + $parent->setAttribute('children', ['child1', ['$id' => 'child2']]); $updatedParent = $database->updateDocument('parentRelationTest', 'parent1', $parent); - $updatedChildren = $updatedParent->getDocuments('children'); - $this->assertNotEmpty($updatedChildren); - $this->assertEquals('child2', $updatedChildren[0]->getId()); + $updatedChildren = \array_map(fn (Document $child) => $child->getId(), $updatedParent->getDocuments('children')); + \sort($updatedChildren); + $this->assertSame(['child1', 'child2'], $updatedChildren); $database->deleteCollection('parentRelationTest'); $database->deleteCollection('childRelationTest'); diff --git a/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php b/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php index a1df08d7a..83a167aa8 100644 --- a/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php +++ b/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php @@ -9,6 +9,7 @@ use Utopia\Database\Collection; use Utopia\Database\Database; use Utopia\Database\Document; +use Utopia\Database\Exception\Authorization as AuthorizationException; use Utopia\Database\Exception\Restricted as RestrictedException; use Utopia\Database\Exception\Structure; use Utopia\Database\Id; @@ -2805,4 +2806,73 @@ public function testDeleteDocumentsWithASelectHonoursRestrict_OneToMany(): void $database->deleteCollection($parentCollection); $database->deleteCollection($childCollection); } + + public function testUnlinkingAOneToManyDocumentNeedsUpdatePermission(): void + { + /** @var Database $database */ + $database = $this->getDatabase(); + + if (! ($database->getAdapter()->hasFeature(Feature\Relationships::class))) { + $this->expectNotToPerformAssertions(); + + return; + } + + $parents = Id::unique(); + $children = Id::unique(); + $database->createCollection(Collection::create(id: $parents, permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + Permission::update(Role::any()), + ])); + $database->createCollection(Collection::create(id: $children, permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + ], documentSecurity: true)); + $database->createRelationship($parents, Relationship::oneToMany(relatedCollection: $children, key: 'children', twoWay: true, twoWayKey: 'parent', onDelete: RelationshipDeleteAction::SetNull)); + + $database->createDocument($children, new Document([ + '$id' => 'locked', + '$permissions' => [Permission::read(Role::any()), Permission::update(Role::user('childOwner'))], + ])); + $database->getAuthorization()->skip(fn () => $database->createDocument($parents, new Document(['$id' => 'parent1', 'children' => ['locked']]))); + + $authorization = $database->getAuthorization(); + $roles = $authorization->getRoles(); + $authorization->cleanRoles(); + $authorization->addRole(Role::any()->toString()); + + try { + // The pre-check must refuse what updateDocument() refuses + try { + $database->authorizeUpdate($parents, $database->getDocument($parents, 'parent1'), new Document(['children' => []])); + $this->fail('authorizeUpdate() must refuse unlinking a one-to-many document the caller cannot update'); + } catch (AuthorizationException) { + } + + // Unlinking writes the child's own parent key, so it needs the same update permission as linking it + try { + $database->updateDocument($parents, 'parent1', new Document(['children' => []])); + $this->fail('Unlinking a one-to-many document the caller cannot update must be refused'); + } catch (AuthorizationException) { + } + $parent = $database->getDocument($children, 'locked')->getAttribute('parent'); + $this->assertInstanceOf(Document::class, $parent); + $this->assertSame('parent1', $parent->getId()); + + $authorization->addRole(Role::user('childOwner')->toString()); + + $database->authorizeUpdate($parents, $database->getDocument($parents, 'parent1'), new Document(['children' => []])); + $database->updateDocument($parents, 'parent1', new Document(['children' => []])); + $this->assertNull($database->getDocument($children, 'locked')->getAttribute('parent')); + } finally { + $authorization->cleanRoles(); + foreach ($roles as $role) { + $authorization->addRole($role); + } + + $database->deleteCollection($parents); + $database->deleteCollection($children); + } + } }