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
44 changes: 44 additions & 0 deletions src/Database/Hook/Relationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// Chunk to honor the validator's maxQueryValues cap; without
// this a relationship update with thousands of removed
// children would throw QueryException.
Expand Down Expand Up @@ -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<string> $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
Expand Down Expand Up @@ -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);
}
}
}

Expand Down
19 changes: 16 additions & 3 deletions tests/e2e/Adapter/Scopes/PermissionTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
70 changes: 70 additions & 0 deletions tests/e2e/Adapter/Scopes/Relationships/OneToManyTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}
}
Loading