From 1680a36ac5edaed90e6763bbe3374347f663554c Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 30 Nov 2026 09:34:07 +0000 Subject: [PATCH 1/5] fix(relationships): require update permission to unlink a one-to-many document Unlinking a one-to-many child clears the child's own parent key, yet it ran with authorization skipped, so a caller who could update the parent could change children it had no update permission on. Check the same permission linking does on each removed child that is still stored. Many-to-many unlinks only delete junction rows and stay as they are. Co-Authored-By: Claude Opus 5.5 --- src/Database/Hook/Relationships.php | 25 ++++++++ .../Scopes/Relationships/OneToManyTests.php | 60 +++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/src/Database/Hook/Relationships.php b/src/Database/Hook/Relationships.php index 68f19ffb2..28c88107c 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 diff --git a/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php b/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php index a1df08d7a..1894f2e4b 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,63 @@ 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 { + // 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) { + } + $this->assertSame('parent1', $database->getDocument($children, 'locked')->getAttribute('parent')?->getId()); + + $authorization->addRole(Role::user('childOwner')->toString()); + + $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); + } + } } From 630286a56aa83feeb68510fbedbb48efa68b0748 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 30 Nov 2026 09:37:57 +0000 Subject: [PATCH 2/5] test(relationships): assert the linked parent's type before reading its id Co-Authored-By: Claude Opus 5.5 --- tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php b/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php index 1894f2e4b..ca6d17fcf 100644 --- a/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php +++ b/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php @@ -2849,7 +2849,9 @@ public function testUnlinkingAOneToManyDocumentNeedsUpdatePermission(): void $this->fail('Unlinking a one-to-many document the caller cannot update must be refused'); } catch (AuthorizationException) { } - $this->assertSame('parent1', $database->getDocument($children, 'locked')->getAttribute('parent')?->getId()); + $parent = $database->getDocument($children, 'locked')->getAttribute('parent'); + $this->assertInstanceOf(Document::class, $parent); + $this->assertSame('parent1', $parent->getId()); $authorization->addRole(Role::user('childOwner')->toString()); From 668c385264740892106f385e8bf076b8f41018ca Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 30 Nov 2026 10:03:32 +0000 Subject: [PATCH 3/5] test(permissions): replacing a child the caller cannot update is refused testCreateRelationDocumentWithoutUpdatePermission relied on unlinking child1 without update permission on it. Unlinking now needs that permission, so the replace is refused and child1 stays linked; adding child2 alongside it, which only creates a document, still works. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/Adapter/Scopes/PermissionTests.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) 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'); From 68da7768e0e49bfcebc82d43b8a8fe70746dac6b Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 30 Nov 2026 10:09:45 +0000 Subject: [PATCH 4/5] fix(relationships): refuse a one-to-many unlink in the update pre-check too authorizeUpdate() must throw whenever updateDocument() would refuse, but it only checked the related values the update carries, so a removed child the caller cannot update passed the pre-check and was refused by the write. Check each removed one-to-many child as the write's authorizeUnlink() does, through the staged view when one is given. Co-Authored-By: Claude Opus 5.5 --- src/Database/Hook/Relationships.php | 15 +++++++++++++++ .../Scopes/Relationships/OneToManyTests.php | 8 ++++++++ 2 files changed, 23 insertions(+) diff --git a/src/Database/Hook/Relationships.php b/src/Database/Hook/Relationships.php index 28c88107c..4eee0a014 100644 --- a/src/Database/Hook/Relationships.php +++ b/src/Database/Hook/Relationships.php @@ -3639,15 +3639,30 @@ 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)) { + foreach (\array_diff($linked, $kept) as $removed) { + $staged = $resolve === null ? null : $resolve($relatedCollection->getId(), $removed); + $stored = $staged ?? $this->database->getAuthorization()->skip(fn () => $this->database->skipRelationships(fn () => $this->database->skipQueryHooks(fn () => $this->database->getDocument($relatedCollection->getId(), $removed)))); + if (! $stored->isEmpty()) { + $this->authorizeLink($relatedCollection, $stored); + } + } + } } } diff --git a/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php b/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php index ca6d17fcf..83a167aa8 100644 --- a/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php +++ b/tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php @@ -2843,6 +2843,13 @@ public function testUnlinkingAOneToManyDocumentNeedsUpdatePermission(): void $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' => []])); @@ -2855,6 +2862,7 @@ public function testUnlinkingAOneToManyDocumentNeedsUpdatePermission(): void $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 { From 1f9c0fae9dca18abe6969c00219f5a7971eb7205 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 30 Nov 2026 10:43:47 +0000 Subject: [PATCH 5/5] perf(relationships): batch the pre-check's reads of removed children Read the removed one-to-many children the staged view does not give through authorizeUnlink(), in chunks, instead of one getDocument() each. Co-Authored-By: Claude Opus 5.5 --- src/Database/Hook/Relationships.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Database/Hook/Relationships.php b/src/Database/Hook/Relationships.php index 4eee0a014..832891fac 100644 --- a/src/Database/Hook/Relationships.php +++ b/src/Database/Hook/Relationships.php @@ -3655,13 +3655,17 @@ private function authorizeRelated(Document $collection, Document $document, ?Doc // 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)) { - foreach (\array_diff($linked, $kept) as $removed) { + $unstaged = []; + foreach (\array_values(\array_diff($linked, $kept)) as $removed) { $staged = $resolve === null ? null : $resolve($relatedCollection->getId(), $removed); - $stored = $staged ?? $this->database->getAuthorization()->skip(fn () => $this->database->skipRelationships(fn () => $this->database->skipQueryHooks(fn () => $this->database->getDocument($relatedCollection->getId(), $removed)))); - if (! $stored->isEmpty()) { - $this->authorizeLink($relatedCollection, $stored); + 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); } } }