diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index 110a878d8b..04f112c0fa 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -11,6 +11,7 @@ use OC\OCM\OCMSignatoryManager; use OCA\Analytics\Datasource\DatasourceEvent; use OCA\Circles\Events\CircleDestroyedEvent; +use OCA\Circles\Events\RemovingCircleMemberEvent; use OCA\Tables\Capabilities; use OCA\Tables\Config\ConfigLexicon; use OCA\Tables\Event\RowDeletedEvent; @@ -25,6 +26,7 @@ use OCA\Tables\Listener\ReceiverCleanupListener; use OCA\Tables\Listener\ResourceTypeRegisterListener; use OCA\Tables\Listener\TablesReferenceListener; +use OCA\Tables\Listener\TeamOwnershipListener; use OCA\Tables\Listener\UserDeletedListener; use OCA\Tables\Listener\WhenRowDeletedAuditLogListener; use OCA\Tables\Listener\WhenTableDeletedAuditLogListener; @@ -95,6 +97,7 @@ public function register(IRegistrationContext $context): void { $context->registerService(ISignatoryManager::class, fn (ContainerInterface $c) => $c->get(OCMSignatoryManager::class)); $context->registerEventListener(BeforeUserDeletedEvent::class, UserDeletedListener::class); + $context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class); $context->registerEventListener(DatasourceEvent::class, AnalyticsDatasourceListener::class); $context->registerEventListener(RegisterShareReviewSourceEvent::class, ShareReviewListener::class); $context->registerEventListener(RenderReferenceEvent::class, TablesReferenceListener::class); @@ -108,6 +111,8 @@ public function register(IRegistrationContext $context): void { $context->registerEventListener(UserDeletedEvent::class, ReceiverCleanupListener::class); $context->registerEventListener(GroupDeletedEvent::class, ReceiverCleanupListener::class); $context->registerEventListener(CircleDestroyedEvent::class, ReceiverCleanupListener::class); + $context->registerEventListener(CircleDestroyedEvent::class, TeamOwnershipListener::class); + $context->registerEventListener(RemovingCircleMemberEvent::class, TeamOwnershipListener::class); $context->registerEventListener(LocalOCMDiscoveryEvent::class, ResourceTypeRegisterListener::class); $context->registerSearchProvider(SearchTablesProvider::class); diff --git a/lib/BackgroundJob/RetryTeamTableHandover.php b/lib/BackgroundJob/RetryTeamTableHandover.php new file mode 100644 index 0000000000..ee3c2a9dcd --- /dev/null +++ b/lib/BackgroundJob/RetryTeamTableHandover.php @@ -0,0 +1,47 @@ +setInterval(15 * 60); + } + + /** + * @param array{teamId: string, userId: string} $argument + */ + #[\Override] + public function run($argument): void { + if (!$this->circleHelper->isCirclesEnabled()) { + return; + } + if ($this->userManager->userExists($argument['userId'])) { + $this->jobList->remove(self::class, $argument); + return; + } + + $this->tableService->handleTeamStewardDeparture($argument['teamId'], $argument['userId']); + $this->jobList->remove(self::class, $argument); + } +} diff --git a/lib/Controller/ApiTablesController.php b/lib/Controller/ApiTablesController.php index 3cf2e1e86f..f59a347a1d 100644 --- a/lib/Controller/ApiTablesController.php +++ b/lib/Controller/ApiTablesController.php @@ -385,19 +385,25 @@ public function importScheme(int $id, string $title, string $emoji, string $desc * @param string|null $emoji Emoji for the table * @param string|null $description Description for the table * @param string $template Template to use if wanted + * @param string|null $teamId Team to attach the table to * - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: Tables returned * 400: Invalid request data + * 403: No permissions */ #[NoAdminRequired] - public function create(string $title, ?string $emoji, ?string $description, string $template = 'custom'): DataResponse { + public function create(string $title, ?string $emoji, ?string $description, string $template = 'custom', ?string $teamId = null): DataResponse { try { - return new DataResponse($this->service->create($title, $template, $emoji, $description)->jsonSerialize()); + return new DataResponse($this->service->create($title, $template, $emoji, $description, teamId: $teamId)->jsonSerialize()); } catch (\InvalidArgumentException $e) { $this->logger->warning('An invalid request occurred: ' . $e->getMessage(), ['exception' => $e]); return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); + } catch (BadRequestError $e) { + return $this->handleBadRequestError($e); + } catch (PermissionError $e) { + return $this->handlePermissionError($e); } catch (InternalError|Exception $e) { return $this->handleError($e); } @@ -482,7 +488,7 @@ public function destroy(int $id): DataResponse { /** * [api v2] Transfer table * - * Transfer table from one user to another + * Transfer a table from one user to another. Team-owned tables can only be transferred to a member of that team. * * @param int $id Table ID * @param string $newOwnerUserId New user ID diff --git a/lib/Db/Table.php b/lib/Db/Table.php index 808d2ca435..ecdd525f56 100644 --- a/lib/Db/Table.php +++ b/lib/Db/Table.php @@ -33,6 +33,8 @@ * @method setDescription(string $description) * @method getOwnership(): ?string * @method setOwnership(string $ownership) + * @method getTeamId(): ?string + * @method setTeamId(?string $teamId) * @method getOwnerDisplayName(): string * @method setOwnerDisplayName(string $ownerDisplayName) * @method getIsShared(): bool @@ -73,6 +75,7 @@ class Table extends EntitySuper implements JsonSerializable { protected ?string $title = null; protected ?string $emoji = null; protected ?string $ownership = null; + protected ?string $teamId = null; protected ?string $createdBy = null; protected ?string $createdAt = null; protected ?string $lastEditBy = null; @@ -104,6 +107,7 @@ public function __construct() { $this->addType('uuid', 'string'); $this->addType('archived', 'boolean'); $this->addType('externalId', 'integer'); + $this->addType('teamId', 'string'); } public function setter(string $name, array $args): void { @@ -140,6 +144,7 @@ public function jsonSerialize(): array { 'title' => $this->title ?: '', 'emoji' => $this->emoji, 'ownership' => $this->ownership ?: '', + 'teamId' => $this->teamId, 'ownerDisplayName' => $this->ownerDisplayName ?: '', 'createdBy' => $this->createdBy ?: '', 'createdAt' => $this->createdAt ?: '', diff --git a/lib/Db/TableMapper.php b/lib/Db/TableMapper.php index 5a9ad8d368..14d083dcbd 100644 --- a/lib/Db/TableMapper.php +++ b/lib/Db/TableMapper.php @@ -67,6 +67,39 @@ public function findByUuid(string $uuid): Table { return $this->findEntity($qb); } + /** + * @throws DoesNotExistException + * @throws Exception + * @throws MultipleObjectsReturnedException + */ + public function findForUpdate(int $id): Table { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->table) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))); + if ($this->db->getDatabaseProvider() !== IDBConnection::PLATFORM_SQLITE) { + $qb->forUpdate(); + } + $table = $this->findEntity($qb); + $this->cache[(string)$id] = $table; + return $table; + } + + /** + * @return Table[] + * @throws Exception + */ + public function findAllByTeamId(string $teamId, ?string $ownerUserId = null): array { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->table) + ->where($qb->expr()->eq('team_id', $qb->createNamedParameter($teamId, IQueryBuilder::PARAM_STR))); + if ($ownerUserId !== null) { + $qb->andWhere($qb->expr()->eq('ownership', $qb->createNamedParameter($ownerUserId, IQueryBuilder::PARAM_STR))); + } + return $this->findEntities($qb); + } + /** * @param int[] $ids * @return array indexed by table id diff --git a/lib/Helper/CircleHelper.php b/lib/Helper/CircleHelper.php index d362b2f0ea..05b8d39544 100644 --- a/lib/Helper/CircleHelper.php +++ b/lib/Helper/CircleHelper.php @@ -8,11 +8,15 @@ namespace OCA\Tables\Helper; use OCA\Circles\CirclesManager; +use OCA\Circles\Db\CircleRequest; +use OCA\Circles\Db\MemberRequest; use OCA\Circles\Model\Circle; use OCA\Circles\Model\Member; use OCA\Circles\Model\Probes\CircleProbe; +use OCA\Tables\Errors\InternalError; use OCP\App\IAppManager; use OCP\IL10N; +use OCP\IUserManager; use OCP\Server; use Psr\Log\LoggerInterface; use Throwable; @@ -23,6 +27,8 @@ class CircleHelper { private bool $circlesEnabled; private ?CirclesManager $circlesManager; + private ?MemberRequest $memberRequest = null; + private ?CircleRequest $circleRequest = null; private array $circleDisplayNames = []; private array $federatedUsers = []; private array $unreachableUserIds = []; @@ -34,6 +40,7 @@ public function __construct( private readonly LoggerInterface $logger, IAppManager $appManager, private readonly IL10N $l10n, + private readonly IUserManager $userManager, ) { $this->circlesEnabled = $appManager->isEnabledForUser('circles'); $this->circlesManager = null; @@ -136,7 +143,7 @@ public function getUserIdsInCircle(string $circleId): array { } public function circleExists(string $circleId, string $userId): bool { - if (!$this->circlesEnabled) { + if (!$this->circlesEnabled || !$this->userManager->userExists($userId)) { return false; } @@ -147,4 +154,45 @@ public function circleExists(string $circleId, string $userId): bool { return in_array($circleId, $userCircleIds, true); } + public function findSuccessorUserId(string $circleId, string $excludeUserId): ?string { + if (!$this->circlesEnabled) { + throw new InternalError('Cannot find a table owner while Circles is unavailable'); + } + + try { + // Do not replace the Circles session while a membership event is running. + $circleRequest = $this->circleRequest ??= Server::get(CircleRequest::class); + $circle = $circleRequest->getCircle($circleId); + if ($circle->hasOwner() && $this->isEligibleSuccessor($circle->getOwner(), $excludeUserId)) { + return $circle->getOwner()->getUserId(); + } + + $memberRequest = $this->memberRequest ??= Server::get(MemberRequest::class); + $successor = null; + $highestLevel = -1; + foreach ($memberRequest->getMembers($circleId) as $member) { + if (!$this->isEligibleSuccessor($member, $excludeUserId)) { + continue; + } + if ($member->getLevel() > $highestLevel) { + $successor = $member->getUserId(); + $highestLevel = $member->getLevel(); + } + } + return $successor; + } catch (Throwable $e) { + $this->logger->error('Could not find a successor for a team table', ['circleId' => $circleId, 'exception' => $e]); + throw new InternalError('Could not find a successor for a team table', previous: $e); + } + } + + private function isEligibleSuccessor(Member $member, string $excludeUserId): bool { + return $member->getUserType() === Member::TYPE_USER + && $member->isLocal() + && $member->getStatus() === Member::STATUS_MEMBER + && $member->getUserId() !== '' + && $member->getUserId() !== $excludeUserId + && $this->userManager->userExists($member->getUserId()); + } + } diff --git a/lib/Listener/TeamOwnershipListener.php b/lib/Listener/TeamOwnershipListener.php new file mode 100644 index 0000000000..1a41f3517b --- /dev/null +++ b/lib/Listener/TeamOwnershipListener.php @@ -0,0 +1,48 @@ + */ +class TeamOwnershipListener implements IEventListener { + public function __construct( + private readonly TableService $tableService, + private readonly LoggerInterface $logger, + ) { + } + + public function handle(Event $event): void { + if ($event instanceof CircleDestroyedEvent) { + try { + $this->tableService->deleteTeamOwnedTables($event->getCircle()->getSingleId()); + } catch (\Throwable $e) { + $this->logger->error('Could not delete tables owned by a destroyed team: ' . $e->getMessage(), [ + 'exception' => $e, + ]); + } + } elseif ($event instanceof RemovingCircleMemberEvent) { + $member = $event->getMember(); + if ($member->getUserType() === Member::TYPE_USER && $member->isLocal()) { + try { + $this->tableService->handleTeamStewardDeparture($event->getCircle()->getSingleId(), $member->getUserId()); + } catch (\Throwable $e) { + $this->logger->error('Could not update team-owned tables after a team membership change: ' . $e->getMessage(), [ + 'exception' => $e, + ]); + } + } + } + } +} diff --git a/lib/Listener/UserDeletedListener.php b/lib/Listener/UserDeletedListener.php index 69b1944611..fcc703444b 100644 --- a/lib/Listener/UserDeletedListener.php +++ b/lib/Listener/UserDeletedListener.php @@ -7,39 +7,75 @@ namespace OCA\Tables\Listener; +use OCA\Tables\BackgroundJob\RetryTeamTableHandover; use OCA\Tables\Errors\InternalError; +use OCA\Tables\Errors\NotFoundError; +use OCA\Tables\Errors\PermissionError; +use OCA\Tables\Helper\CircleHelper; use OCA\Tables\Service\TableService; +use OCP\BackgroundJob\IJobList; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; use OCP\User\Events\BeforeUserDeletedEvent; +use OCP\User\Events\UserDeletedEvent; use Psr\Log\LoggerInterface; /** - * @template-implements IEventListener + * @template-implements IEventListener */ class UserDeletedListener implements IEventListener { public function __construct( private readonly TableService $tableService, private readonly LoggerInterface $logger, + private readonly CircleHelper $circleHelper, + private readonly IJobList $jobList, ) { } public function handle(Event $event): void { - if (!($event instanceof BeforeUserDeletedEvent)) { + if (!($event instanceof BeforeUserDeletedEvent || $event instanceof UserDeletedEvent)) { return; } + $userId = $event->getUser()->getUID(); try { - $tables = $this->tableService->findAll($event->getUser()->getUID(), true, true, false); - $this->logger->info('event "user deleted" was triggered, will try to delete all data for the user: ' . $event->getUser()->getUID() . ' (' . $event->getUser()->getDisplayName() . ')'); + $tables = $this->tableService->findAll($userId, true, true, false); + } catch (InternalError $e) { + $this->logger->error('Could not list tables for user deletion', [ + 'userId' => $userId, + 'exception' => $e, + ]); + return; + } + + $teamIds = []; + foreach ($tables as $table) { + $teamId = $table->getTeamId(); + if ($teamId !== null) { + $teamIds[] = $teamId; + } elseif ($event instanceof BeforeUserDeletedEvent) { + try { + $this->tableService->delete($table->getId(), $userId); + } catch (InternalError|NotFoundError|PermissionError $e) { + $this->logger->error('Could not clean up a personal table for a deleted user', [ + 'tableId' => $table->getId(), 'userId' => $userId, 'exception' => $e, + ]); + } + } + } - // delete tables - $this->logger->debug('found ' . count($tables) . ' tables for the user'); - foreach ($tables as $table) { - $this->tableService->delete($table->getId(), $event->getUser()->getUID()); + foreach (array_unique($teamIds) as $teamId) { + if ($event instanceof UserDeletedEvent) { + $this->jobList->add(RetryTeamTableHandover::class, ['teamId' => $teamId, 'userId' => $userId]); + } elseif ($this->circleHelper->isCirclesEnabled()) { + try { + $this->tableService->handleTeamStewardDeparture($teamId, $userId); + } catch (InternalError|NotFoundError|PermissionError $e) { + $this->logger->error('Could not hand over team tables before user deletion', [ + 'teamId' => $teamId, 'userId' => $userId, 'exception' => $e, + ]); + } } - $this->logger->debug('tables for the deleted user removed'); - } catch (InternalError) { } } } diff --git a/lib/Migration/Version3000Date20261130000000.php b/lib/Migration/Version3000Date20261130000000.php new file mode 100644 index 0000000000..d55245771b --- /dev/null +++ b/lib/Migration/Version3000Date20261130000000.php @@ -0,0 +1,42 @@ +hasTable($tableName)) { + return null; + } + + $table = $schema->getTable($tableName); + if (!$table->hasColumn('team_id')) { + $table->addColumn('team_id', Types::STRING, [ + 'notnull' => false, + 'length' => 64, + ]); + } + if (!$table->hasIndex('tables_tables_team_id')) { + $table->addIndex(['team_id'], 'tables_tables_team_id'); + } + + return $schema; + } +} diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 7c6b233d9b..525ff04409 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -55,6 +55,7 @@ * title: string, * emoji: string|null, * ownership: string, + * teamId: string|null, * ownerDisplayName: string, * createdBy: string, * createdAt: string, diff --git a/lib/Service/TableService.php b/lib/Service/TableService.php index 3adc38d9c4..c5e1716993 100644 --- a/lib/Service/TableService.php +++ b/lib/Service/TableService.php @@ -14,6 +14,7 @@ use OCA\Tables\Activity\ChangeSet; use OCA\Tables\AppInfo\Application; use OCA\Tables\AuditLog\Operation; +use OCA\Tables\Constants\ShareReceiverType; use OCA\Tables\Db\Table; use OCA\Tables\Db\TableMapper; use OCA\Tables\Dto\Column as ColumnDto; @@ -23,6 +24,7 @@ use OCA\Tables\Errors\PermissionError; use OCA\Tables\Event\TableDeletedEvent; use OCA\Tables\Event\TableOwnershipTransferredEvent; +use OCA\Tables\Helper\CircleHelper; use OCA\Tables\Helper\UserHelper; use OCA\Tables\Model\ColumnSettings; use OCA\Tables\Model\FilterSet; @@ -33,6 +35,7 @@ use OCA\Tables\Model\ViewUpdateInput; use OCA\Tables\ResponseDefinitions; use OCA\Tables\Service\Support\AuditLogServiceInterface; +use OCA\Tables\Service\ValueObject\ShareCreate; use OCA\Tables\Service\ValueObject\Title; use OCA\Tables\Vendor\Symfony\Component\Uid\Uuid; use OCP\App\IAppManager; @@ -65,6 +68,7 @@ public function __construct( private ViewService $viewService, private ShareService $shareService, protected UserHelper $userHelper, + private CircleHelper $circleHelper, protected FavoritesService $favoritesService, protected IEventDispatcher $eventDispatcher, private ContextService $contextService, @@ -289,9 +293,17 @@ public function find(int $id, bool $skipTableEnhancement = false, ?string $userI * @throws \InvalidArgumentException * @noinspection DuplicatedCode */ - public function create(string $title, string $template, ?string $emoji, ?string $description = '', ?string $userId = null, ?string $uuid = null): Table { + public function create(string $title, string $template, ?string $emoji, ?string $description = '', ?string $userId = null, ?string $uuid = null, ?string $teamId = null): Table { $userId = $this->permissionsService->preCheckUserId($userId, false); // we can assume that the $userId is set $title = (string)new Title($title); + if ($teamId !== null) { + if ($teamId === '' || !$this->circleHelper->isCirclesEnabled()) { + throw new BadRequestError('Team ownership requires a team ID and the Circles app'); + } + if (!$this->circleHelper->circleExists($teamId, $userId)) { + throw new PermissionError('You must be a team member to create a team table'); + } + } $time = new DateTime(); $item = new Table(); @@ -301,6 +313,7 @@ public function create(string $title, string $template, ?string $emoji, ?string $item->setEmoji($emoji); } $item->setOwnership($userId); + $item->setTeamId($teamId); $item->setCreatedBy($userId); $item->setLastEditBy($userId); $item->setCreatedAt($time->format('Y-m-d H:i:s')); @@ -322,8 +335,15 @@ public function create(string $title, string $template, ?string $emoji, ?string $item->setUuid($applicableUuid); try { - $newTable = $this->mapper->insert($item); - } catch (OcpDbException $e) { + $newTable = $teamId === null ? $this->mapper->insert($item) : $this->atomic(function () use ($item, $teamId): Table { + $table = $this->mapper->insert($item); + $this->shareService->create(new ShareCreate( + $table->getId(), 'table', $teamId, ShareReceiverType::CIRCLE, + true, true, true, true, false, 0, + )); + return $table; + }, $this->dbc); + } catch (OcpDbException|InternalError $e) { $this->logger->error($e->getMessage()); throw new InternalError($e->getMessage()); } @@ -374,31 +394,41 @@ public function create(string $title, string $template, ?string $emoji, ?string */ public function setOwner(int $id, string $newOwnerUserId, ?string $userId = null): Table { $userId = $this->permissionsService->preCheckUserId($userId); + return $this->transferOwnership($id, $newOwnerUserId, $userId); + } + private function transferOwnership(int $id, string $newOwnerUserId, string $userId, ?string $expectedTeamId = null): Table { try { - $table = $this->mapper->find($id); + [$table, $previousOwnerUserId] = $this->atomic(function () use ($id, $newOwnerUserId, $userId, $expectedTeamId): array { + $table = $this->mapper->findForUpdate($id); + if (!$this->permissionsService->canChangeElementOwner($table, $userId)) { + throw new PermissionError('PermissionError: can not change table owner with table id ' . $id); + } + + $teamId = $table->getTeamId(); + if ($expectedTeamId !== null) { + // Automatic handover already selected a team member without changing the Circles session. + if ($teamId !== $expectedTeamId || $table->getOwnership() !== $userId) { + throw new PermissionError('Table ownership changed during team handover'); + } + } elseif ($teamId !== null && !$this->circleHelper->circleExists($teamId, $newOwnerUserId)) { + throw new PermissionError('Team-owned tables can only be transferred to a member of that team'); + } + + $previousOwnerUserId = $table->getOwnership(); + $table->setOwnership($newOwnerUserId); + $table = $this->mapper->update($table); + $this->shareService->changeSenderForNode('table', $id, $newOwnerUserId, $userId); + return [$table, $previousOwnerUserId]; + }, $this->dbc); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (MultipleObjectsReturnedException|OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); - } - - // security - if (!$this->permissionsService->canChangeElementOwner($table, $userId)) { - throw new PermissionError('PermissionError: can not change table owner with table id ' . $id); - } - - $previousOwnerUserId = $table->getOwnership(); - $table->setOwnership($newOwnerUserId); - - try { - $table = $this->atomic(function () use ($table, $id, $newOwnerUserId, $userId) { - $table = $this->mapper->update($table); - $this->shareService->changeSenderForNode('table', $id, $newOwnerUserId, $userId); - return $table; - }, $this->dbc); + } catch (PermissionError $e) { + throw $e; } catch (\Exception $e) { $this->logger->error('Failed to transfer table ownership: ' . $e->getMessage(), ['exception' => $e]); throw new InternalError('Failed to transfer table ownership: ' . $e->getMessage()); @@ -415,6 +445,48 @@ public function setOwner(int $id, string $newOwnerUserId, ?string $userId = null return $table; } + public function handleTeamStewardDeparture(string $teamId, string $userId): void { + try { + $tables = $this->mapper->findAllByTeamId($teamId, $userId); + if ($tables === []) { + return; + } + $successor = $this->circleHelper->findSuccessorUserId($teamId, $userId); + foreach ($tables as $table) { + if ($successor === null) { + $this->deleteTeamOwnedTable($table->getId(), $teamId, $userId); + } else { + $this->transferOwnership($table->getId(), $successor, $userId, $teamId); + } + } + } catch (OcpDbException $e) { + $this->logger->error('Could not hand over team tables', ['teamId' => $teamId, 'exception' => $e]); + throw new InternalError('Could not hand over team tables', previous: $e); + } + } + + public function deleteTeamOwnedTables(string $teamId): void { + try { + foreach ($this->mapper->findAllByTeamId($teamId) as $table) { + $this->deleteTeamOwnedTable($table->getId(), $teamId); + } + } catch (OcpDbException $e) { + $this->logger->error('Could not delete team tables', ['teamId' => $teamId, 'exception' => $e]); + throw new InternalError('Could not delete team tables', previous: $e); + } + } + + private function deleteTeamOwnedTable(int $id, string $teamId, ?string $expectedOwner = null): void { + $this->atomic(function () use ($id, $teamId, $expectedOwner): void { + $table = $this->mapper->findForUpdate($id); + if ($table->getTeamId() !== $teamId || ($expectedOwner !== null && $table->getOwnership() !== $expectedOwner)) { + $this->logger->info('Skipping team cleanup because table ownership changed', ['tableId' => $id]); + return; + } + $this->delete($id, $table->getOwnership()); + }, $this->dbc); + } + /** * @param int $id * @param null|string $userId diff --git a/openapi.json b/openapi.json index 9fcb2b17d7..b6b87f3566 100644 --- a/openapi.json +++ b/openapi.json @@ -907,6 +907,7 @@ "title", "emoji", "ownership", + "teamId", "ownerDisplayName", "createdBy", "createdAt", @@ -943,6 +944,10 @@ "ownership": { "type": "string" }, + "teamId": { + "type": "string", + "nullable": true + }, "ownerDisplayName": { "type": "string" }, @@ -7475,6 +7480,12 @@ "type": "string", "default": "custom", "description": "Template to use if wanted" + }, + "teamId": { + "type": "string", + "nullable": true, + "default": null, + "description": "Team to attach the table to" } } } @@ -7562,6 +7573,44 @@ } } }, + "403": { + "description": "No permissions", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, "500": { "description": "", "content": { @@ -8889,7 +8938,7 @@ "put": { "operationId": "api_tables-transfer", "summary": "[api v2] Transfer table", - "description": "Transfer table from one user to another", + "description": "Transfer a table from one user to another. Team-owned tables can only be transferred to a member of that team.", "tags": [ "api_tables" ], diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index feeea04136..78a13d1215 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -629,7 +629,7 @@ export type paths = { readonly get?: never; /** * [api v2] Transfer table - * @description Transfer table from one user to another + * @description Transfer a table from one user to another. Team-owned tables can only be transferred to a member of that team. */ readonly put: operations["api_tables-transfer"]; readonly post?: never; @@ -1446,6 +1446,7 @@ export type components = { readonly title: string; readonly emoji: string | null; readonly ownership: string; + readonly teamId: string | null; readonly ownerDisplayName: string; readonly createdBy: string; readonly createdAt: string; @@ -4977,6 +4978,11 @@ export interface operations { * @default custom */ readonly template?: string; + /** + * @description Team to attach the table to + * @default null + */ + readonly teamId?: string | null; }; }; }; @@ -5025,6 +5031,22 @@ export interface operations { }; }; }; + /** @description No permissions */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; readonly 500: { headers: { readonly [name: string]: unknown; diff --git a/tests/stub.phpstub b/tests/stub.phpstub index 1abb26a1ec..8e4e3baf3d 100644 --- a/tests/stub.phpstub +++ b/tests/stub.phpstub @@ -71,6 +71,27 @@ namespace OCP\Share\ShareReview\Events { namespace OCA\Circles\Model { class Circle { abstract public function getSingleId(): string {} + public function hasOwner(): bool {} + public function getOwner(): Member {} + } + class Member { + public const TYPE_USER = 1; + public const STATUS_MEMBER = 'Member'; + public function getUserType(): int {} + public function getUserId(): string {} + public function getStatus(): string {} + public function getLevel(): int {} + public function isLocal(): bool {} + } +} + +namespace OCA\Circles\Db { + class CircleRequest { + public function getCircle(string $id): \OCA\Circles\Model\Circle {} + } + class MemberRequest { + /** @return \OCA\Circles\Model\Member[] */ + public function getMembers(string $singleId): array {} } } @@ -78,6 +99,10 @@ namespace OCA\Circles\Events { class CircleDestroyedEvent extends \OCP\EventDispatcher\Event { public function getCircle(): \OCA\Circles\Model\Circle {} } + class RemovingCircleMemberEvent extends \OCP\EventDispatcher\Event { + public function getCircle(): \OCA\Circles\Model\Circle {} + public function getMember(): \OCA\Circles\Model\Member {} + } } namespace OC\Collaboration\Reference { diff --git a/tests/unit/BackgroundJob/RetryTeamTableHandoverTest.php b/tests/unit/BackgroundJob/RetryTeamTableHandoverTest.php new file mode 100644 index 0000000000..8ac6ecde7e --- /dev/null +++ b/tests/unit/BackgroundJob/RetryTeamTableHandoverTest.php @@ -0,0 +1,82 @@ + 'team', 'userId' => 'alice']; + private CircleHelper&MockObject $circleHelper; + private TableService&MockObject $tableService; + private IJobList&MockObject $jobList; + private IUserManager&MockObject $userManager; + private RetryTeamTableHandover $job; + + protected function setUp(): void { + parent::setUp(); + $this->circleHelper = $this->createMock(CircleHelper::class); + $this->tableService = $this->createMock(TableService::class); + $this->jobList = $this->createMock(IJobList::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->job = new RetryTeamTableHandover( + $this->createMock(ITimeFactory::class), + $this->circleHelper, + $this->tableService, + $this->jobList, + $this->userManager, + ); + } + + public function testHandoverStaysQueuedUntilCirclesReturns(): void { + $this->circleHelper->method('isCirclesEnabled')->willReturnOnConsecutiveCalls(false, true); + $this->userManager->method('userExists')->with('alice')->willReturn(false); + $handoverAttempted = false; + $this->tableService->expects(self::once())->method('handleTeamStewardDeparture')->with('team', 'alice') + ->willReturnCallback(static function () use (&$handoverAttempted): void { + $handoverAttempted = true; + }); + $this->jobList->expects(self::once())->method('remove')->with(RetryTeamTableHandover::class, self::ARGUMENT) + ->willReturnCallback(static function () use (&$handoverAttempted): void { + self::assertTrue($handoverAttempted); + }); + + $this->job->run(self::ARGUMENT); + self::assertFalse($handoverAttempted); + $this->job->run(self::ARGUMENT); + self::assertTrue($handoverAttempted); + } + + public function testFailedHandoverStaysQueued(): void { + $this->circleHelper->method('isCirclesEnabled')->willReturn(true); + $this->userManager->method('userExists')->willReturn(false); + $this->tableService->method('handleTeamStewardDeparture')->willThrowException(new InternalError('lookup failed')); + $this->jobList->expects(self::never())->method('remove'); + + $this->expectException(InternalError::class); + $this->job->run(self::ARGUMENT); + } + + public function testRetryDoesNotTouchTablesIfTheUserIdHasBeenReused(): void { + $this->circleHelper->method('isCirclesEnabled')->willReturn(true); + $this->userManager->method('userExists')->with('alice')->willReturn(true); + $this->tableService->expects(self::never())->method('handleTeamStewardDeparture'); + $this->jobList->expects(self::once())->method('remove')->with(RetryTeamTableHandover::class, self::ARGUMENT); + + $this->job->run(self::ARGUMENT); + } +} diff --git a/tests/unit/Db/TableMapperTest.php b/tests/unit/Db/TableMapperTest.php new file mode 100644 index 0000000000..fbf031c0f6 --- /dev/null +++ b/tests/unit/Db/TableMapperTest.php @@ -0,0 +1,59 @@ +createMock(IQueryBuilder::class); + $expression = $this->createMock(IExpressionBuilder::class); + $query->method('select')->willReturnSelf(); + $query->method('from')->willReturnSelf(); + $query->method('where')->willReturnSelf(); + $query->method('expr')->willReturn($expression); + $query->method('createNamedParameter')->willReturn(':id'); + $expression->method('eq')->willReturn('id = :id'); + $query->expects($supportsRowLock ? self::once() : self::never())->method('forUpdate')->willReturnSelf(); + + $connection = $this->createMock(IDBConnection::class); + $connection->method('getDatabaseProvider')->willReturn($provider); + $connection->method('getQueryBuilder')->willReturn($query); + $mapper = $this->getMockBuilder(TableMapper::class) + ->setConstructorArgs([$connection, $this->createMock(UserHelper::class)]) + ->onlyMethods(['findEntity']) + ->getMock(); + $stale = new Table(); + $current = new Table(); + $mapper->expects(self::exactly(2))->method('findEntity')->willReturnOnConsecutiveCalls($stale, $current); + + self::assertSame($stale, $mapper->find(5)); + self::assertSame($current, $mapper->findForUpdate(5)); + self::assertSame($current, $mapper->find(5)); + } + + public static function databaseProviders(): array { + return [ + 'sqlite' => [IDBConnection::PLATFORM_SQLITE, false], + 'postgresql' => [IDBConnection::PLATFORM_POSTGRES, true], + 'mysql' => [IDBConnection::PLATFORM_MYSQL, true], + ]; + } + +} diff --git a/tests/unit/Helper/CircleHelperTest.php b/tests/unit/Helper/CircleHelperTest.php new file mode 100644 index 0000000000..d570ef26f0 --- /dev/null +++ b/tests/unit/Helper/CircleHelperTest.php @@ -0,0 +1,128 @@ +createMock(IAppManager::class); + $appManager->method('isEnabledForUser')->willReturn(false); + $userManager = $this->createMock(IUserManager::class); + $userManager->method('userExists')->willReturnCallback(static fn (string $userId): bool => $userId !== 'deleted'); + $this->helper = new CircleHelper($this->createMock(LoggerInterface::class), $appManager, $this->createMock(IL10N::class), $userManager); + $this->memberRequest = $this->createMock(MemberRequest::class); + $this->circle = new Circle(); + $this->circleRequest = $this->createMock(CircleRequest::class); + $this->circleRequest->method('getCircle')->with('team')->willReturn($this->circle); + (new ReflectionProperty(CircleHelper::class, 'circlesEnabled'))->setValue($this->helper, true); + (new ReflectionProperty(CircleHelper::class, 'memberRequest'))->setValue($this->helper, $this->memberRequest); + (new ReflectionProperty(CircleHelper::class, 'circleRequest'))->setValue($this->helper, $this->circleRequest); + } + + public function testUsesTheTeamOwnerWithoutListingMembers(): void { + $this->circle->setOwner($this->member('owner', Member::LEVEL_OWNER)); + $this->memberRequest->expects(self::never())->method('getMembers'); + + self::assertSame('owner', $this->helper->findSuccessorUserId('team', 'alice')); + } + + /** + * @dataProvider ineligibleOwnerProvider + */ + public function testFallsBackWhenTheTeamOwnerIsIneligible(string $userId, bool $local, string $status): void { + $this->circle->setOwner($this->member($userId, Member::LEVEL_OWNER, local: $local, status: $status)); + $this->memberRequest->expects(self::once())->method('getMembers')->willReturn([ + $this->member('bob', Member::LEVEL_MEMBER), + $this->member('carol', Member::LEVEL_ADMIN), + ]); + + self::assertSame('carol', $this->helper->findSuccessorUserId('team', 'alice')); + } + + public static function ineligibleOwnerProvider(): array { + return [ + 'departing owner' => ['alice', true, 'Member'], + 'remote owner' => ['owner', false, 'Member'], + 'inactive owner' => ['owner', true, 'Invited'], + 'empty user ID' => ['', true, 'Member'], + 'deleted owner still listed in Circles' => ['deleted', true, 'Member'], + ]; + } + + public function testOwnerLookupFailureDoesNotFallBackOrLookLikeAnEmptyTeam(): void { + $this->circleRequest->method('getCircle')->willThrowException(new \RuntimeException('unavailable')); + $this->memberRequest->expects(self::never())->method('getMembers'); + + $this->expectException(InternalError::class); + $this->helper->findSuccessorUserId('team', 'alice'); + } + + public function testSelectsTheHighestRankedActiveLocalSuccessor(): void { + $this->memberRequest->method('getMembers')->with('team')->willReturn([ + $this->member('alice', 9), + $this->member('bob', 1), + $this->member('carol', 8), + $this->member('remote', 9, local: false), + $this->member('invited', 9, status: Member::STATUS_INVITED), + $this->member('group', 9, type: Member::TYPE_GROUP), + $this->member('deleted', 9), + ]); + + self::assertSame('carol', $this->helper->findSuccessorUserId('team', 'alice')); + } + + public function testNoRemainingEligibleMemberReturnsNull(): void { + $this->memberRequest->method('getMembers')->willReturn([$this->member('alice', 9)]); + + self::assertNull($this->helper->findSuccessorUserId('team', 'alice')); + } + + public function testLookupFailureDoesNotLookLikeAnEmptyTeam(): void { + $this->memberRequest->method('getMembers')->willThrowException(new \RuntimeException('unavailable')); + + $this->expectException(InternalError::class); + $this->helper->findSuccessorUserId('team', 'alice'); + } + + public function testDisabledCirclesDoesNotLookLikeAnEmptyTeam(): void { + (new ReflectionProperty(CircleHelper::class, 'circlesEnabled'))->setValue($this->helper, false); + + $this->expectException(InternalError::class); + $this->helper->findSuccessorUserId('team', 'alice'); + } + + private function member(string $userId, int $level, bool $local = true, string $status = Member::STATUS_MEMBER, int $type = Member::TYPE_USER): Member { + $member = $this->getMockBuilder(Member::class)->onlyMethods(['isLocal'])->getMock(); + $member->method('isLocal')->willReturn($local); + return $member->setUserId($userId)->setLevel($level)->setStatus($status)->setUserType($type); + } +} diff --git a/tests/unit/Listener/TeamOwnershipListenerTest.php b/tests/unit/Listener/TeamOwnershipListenerTest.php new file mode 100644 index 0000000000..15c11b3d94 --- /dev/null +++ b/tests/unit/Listener/TeamOwnershipListenerTest.php @@ -0,0 +1,61 @@ +getMockBuilder(Member::class)->onlyMethods(['isLocal'])->getMock(); + $member->setUserType($type === 'user' ? Member::TYPE_USER : Member::TYPE_GROUP)->setUserId('alice'); + $member->method('isLocal')->willReturn($local); + $event = $this->createMock(RemovingCircleMemberEvent::class); + $event->method('getCircle')->willReturn((new Circle())->setSingleId('team')); + $event->method('getMember')->willReturn($member); + $service = $this->createMock(TableService::class); + $service->expects($expected ? self::once() : self::never())->method('handleTeamStewardDeparture')->with('team', 'alice'); + + (new TeamOwnershipListener($service, $this->createMock(LoggerInterface::class)))->handle($event); + } + + public static function removedMemberProvider(): array { + return [ + 'local user' => ['user', true, true], + 'remote user' => ['user', false, false], + 'group' => ['group', true, false], + ]; + } + + public function testDestroyedTeamDeletesItsTables(): void { + $event = $this->createMock(CircleDestroyedEvent::class); + $event->method('getCircle')->willReturn((new Circle())->setSingleId('team')); + $service = $this->createMock(TableService::class); + $service->expects(self::once())->method('deleteTeamOwnedTables')->with('team'); + + (new TeamOwnershipListener($service, $this->createMock(LoggerInterface::class)))->handle($event); + } +} diff --git a/tests/unit/Listener/UserDeletedListenerTest.php b/tests/unit/Listener/UserDeletedListenerTest.php new file mode 100644 index 0000000000..74b1261307 --- /dev/null +++ b/tests/unit/Listener/UserDeletedListenerTest.php @@ -0,0 +1,78 @@ +createMock(IUser::class); + $user->method('getUID')->willReturn('alice'); + $user->method('getDisplayName')->willReturn('Alice'); + $teamTable = new Table(); + $teamTable->setId(1); + $teamTable->setTeamId('team'); + $personalTable = new Table(); + $personalTable->setId(2); + $tableService = $this->createMock(TableService::class); + $tableService->method('handleTeamStewardDeparture')->with('team', 'alice')->willThrowException(new InternalError('handover failed')); + $tableService->method('findAll')->willReturn([$teamTable, $personalTable]); + $tableService->expects(self::once())->method('delete')->with(2, 'alice')->willReturn($personalTable); + $logger = $this->createMock(LoggerInterface::class); + $logger->expects(self::once())->method('error'); + $circleHelper = $this->createMock(CircleHelper::class); + $circleHelper->method('isCirclesEnabled')->willReturn(true); + + (new UserDeletedListener($tableService, $logger, $circleHelper, $this->createMock(IJobList::class)))->handle(new BeforeUserDeletedEvent($user)); + } + + public function testCirclesDowntimeDefersHandoverUntilAfterUserDeletion(): void { + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn('alice'); + $teamTable = new Table(); + $teamTable->setId(1); + $teamTable->setTeamId('team'); + $secondTeamTable = clone $teamTable; + $secondTeamTable->setId(2); + $personalTable = new Table(); + $personalTable->setId(3); + + $tableService = $this->createMock(TableService::class); + $tableService->expects(self::exactly(2))->method('findAll')->with('alice', true, true, false) + ->willReturnOnConsecutiveCalls([$teamTable, $secondTeamTable, $personalTable], [$teamTable, $secondTeamTable]); + $tableService->expects(self::never())->method('handleTeamStewardDeparture'); + $tableService->expects(self::once())->method('delete')->with(3, 'alice')->willReturn($personalTable); + $circleHelper = $this->createMock(CircleHelper::class); + $circleHelper->method('isCirclesEnabled')->willReturn(false); + $jobList = $this->createMock(IJobList::class); + $jobQueued = false; + $jobList->expects(self::once())->method('add')->with(RetryTeamTableHandover::class, ['teamId' => 'team', 'userId' => 'alice']) + ->willReturnCallback(static function () use (&$jobQueued): void { + $jobQueued = true; + }); + $listener = new UserDeletedListener($tableService, $this->createMock(LoggerInterface::class), $circleHelper, $jobList); + + $listener->handle(new BeforeUserDeletedEvent($user)); + self::assertFalse($jobQueued); + $listener->handle(new UserDeletedEvent($user)); + self::assertTrue($jobQueued); + } +} diff --git a/tests/unit/Service/PermissionsServiceTest.php b/tests/unit/Service/PermissionsServiceTest.php index d164e2b0fc..245bbbfce9 100644 --- a/tests/unit/Service/PermissionsServiceTest.php +++ b/tests/unit/Service/PermissionsServiceTest.php @@ -11,6 +11,7 @@ use OCA\Tables\Db\ContextMapper; use OCA\Tables\Db\ShareMapper; +use OCA\Tables\Db\Table; use OCA\Tables\Db\TableMapper; use OCA\Tables\Db\ViewMapper; use OCA\Tables\Errors\InternalError; @@ -40,6 +41,17 @@ public function testPreCheckUserIdGivenUser() { self::assertEquals($userId, $permissionsService->preCheckUserId($userId)); } + public function testTeamAttachmentDoesNotReplaceTheUserOwner(): void { + $table = new Table(); + $table->setOwnership('alice'); + $table->setTeamId('team'); + $permissions = $this->getPermissionServiceWithUserId('alice'); + + self::assertTrue($permissions->canManageTable($table, 'alice')); + self::assertTrue($permissions->canChangeElementOwner($table, 'alice')); + self::assertFalse($permissions->canChangeElementOwner($table, 'bob')); + } + public function testPreCheckUserIdNoUser() { $userId = null; $permissionsService = $this->getPermissionServiceWithUserId($userId); diff --git a/tests/unit/Service/TableServiceAuditLogTest.php b/tests/unit/Service/TableServiceAuditLogTest.php index 5445bbc6fa..ccd9d3a907 100644 --- a/tests/unit/Service/TableServiceAuditLogTest.php +++ b/tests/unit/Service/TableServiceAuditLogTest.php @@ -13,6 +13,10 @@ use OCA\Tables\AuditLog\Operation; use OCA\Tables\Db\Table; use OCA\Tables\Db\TableMapper; +use OCA\Tables\Errors\InternalError; +use OCA\Tables\Errors\PermissionError; +use OCA\Tables\Event\TableOwnershipTransferredEvent; +use OCA\Tables\Helper\CircleHelper; use OCA\Tables\Helper\UserHelper; use OCA\Tables\Service\ColumnService; use OCA\Tables\Service\ContextService; @@ -24,6 +28,7 @@ use OCA\Tables\Service\Support\AuditLogServiceInterface; use OCA\Tables\Service\TableService; use OCA\Tables\Service\TableTemplateService; +use OCA\Tables\Service\ValueObject\ShareCreate; use OCA\Tables\Service\ViewService; use OCP\App\IAppManager; use OCP\Defaults; @@ -38,6 +43,10 @@ final class TableServiceAuditLogTest extends TestCase { private PermissionsService&MockObject $permissionsService; private TableMapper&MockObject $mapper; private AuditLogServiceInterface&MockObject $auditLogService; + private CircleHelper&MockObject $circleHelper; + private ShareService&MockObject $shareService; + private IDBConnection&MockObject $connection; + private IEventDispatcher&MockObject $eventDispatcher; private TableService $service; protected function setUp(): void { @@ -47,6 +56,10 @@ protected function setUp(): void { $this->permissionsService->method('preCheckUserId')->willReturn('alice'); $this->mapper = $this->createMock(TableMapper::class); $this->auditLogService = $this->createMock(AuditLogServiceInterface::class); + $this->circleHelper = $this->createMock(CircleHelper::class); + $this->shareService = $this->createMock(ShareService::class); + $this->connection = $this->createMock(IDBConnection::class); + $this->eventDispatcher = $this->createMock(IEventDispatcher::class); $this->service = new TableService( $this->permissionsService, @@ -57,13 +70,14 @@ protected function setUp(): void { $this->createMock(ColumnService::class), $this->createMock(RowService::class), $this->createMock(ViewService::class), - $this->createMock(ShareService::class), + $this->shareService, $this->createMock(UserHelper::class), + $this->circleHelper, $this->createMock(FavoritesService::class), - $this->createMock(IEventDispatcher::class), + $this->eventDispatcher, $this->createMock(ContextService::class), $this->createMock(IAppManager::class), - $this->createMock(IDBConnection::class), + $this->connection, $this->createMock(IL10N::class), $this->createMock(Defaults::class), $this->createMock(ActivityManager::class), @@ -108,6 +122,157 @@ public function testUpdateLogsArchiving(): void { $this->service->update(5, null, null, null, true, 'alice'); } + public function testAnyTeamMemberCanCreateATeamTableWithAnOrdinaryRowShare(): void { + $this->circleHelper->method('isCirclesEnabled')->willReturn(true); + $this->circleHelper->method('circleExists')->with('team', 'alice')->willReturn(true); + $this->mapper->method('insert')->willReturnCallback(static function (Table $table): Table { + $table->setId(5); + return $table; + }); + $this->shareService->expects(self::once())->method('create')->with(self::callback( + static fn (ShareCreate $share): bool => $share->getNodeId() === 5 + && $share->getReceiver() === 'team' + && $share->getReceiverType() === 'circle' + && $share->getPermissionRead() && $share->getPermissionCreate() + && $share->getPermissionUpdate() && $share->getPermissionDelete() + && !$share->getPermissionManage(), + )); + $this->connection->expects(self::once())->method('commit'); + + $table = $this->service->create('Budget', 'custom', null, teamId: 'team'); + + self::assertSame('team', $table->getTeamId()); + self::assertSame('alice', $table->getOwnership()); + } + + public function testNonMemberCannotCreateATeamTable(): void { + $this->circleHelper->method('isCirclesEnabled')->willReturn(true); + $this->circleHelper->method('circleExists')->willReturn(false); + $this->mapper->expects(self::never())->method('insert'); + + $this->expectException(PermissionError::class); + $this->service->create('Budget', 'custom', null, teamId: 'team'); + } + + public function testTeamShareFailureRollsBackCreation(): void { + $this->circleHelper->method('isCirclesEnabled')->willReturn(true); + $this->circleHelper->method('circleExists')->willReturn(true); + $this->mapper->method('insert')->willReturn($this->createTable(false)); + $this->shareService->method('create')->willThrowException(new InternalError('share failed')); + $this->connection->expects(self::once())->method('rollBack'); + $this->connection->expects(self::never())->method('commit'); + + $this->expectException(InternalError::class); + $this->service->create('Budget', 'custom', null, teamId: 'team'); + } + + public function testOwnerDepartureTransfersTheUserOwnerWithoutDetachingTheTeam(): void { + $table = $this->createTable(false); + $table->setTeamId('team'); + $this->mapper->expects(self::exactly(2))->method('findAllByTeamId')->with('team', 'alice') + ->willReturnCallback(static fn (): array => $table->getOwnership() === 'alice' ? [$table] : []); + $this->mapper->method('findForUpdate')->with(5)->willReturn($table); + $this->mapper->expects(self::once())->method('update')->willReturnArgument(0); + $this->circleHelper->expects(self::once())->method('findSuccessorUserId')->with('team', 'alice')->willReturn('bob'); + $this->circleHelper->expects(self::never())->method('circleExists'); + $this->permissionsService->method('canChangeElementOwner')->with($table, 'alice')->willReturn(true); + $this->shareService->expects(self::once())->method('changeSenderForNode')->with('table', 5, 'bob', 'alice'); + $this->eventDispatcher->expects(self::once())->method('dispatchTyped')->with(self::callback( + static fn (TableOwnershipTransferredEvent $event): bool => $event->getFromUserId() === 'alice' + && $event->getToUserId() === 'bob', + )); + + $this->service->handleTeamStewardDeparture('team', 'alice'); + $this->service->handleTeamStewardDeparture('team', 'alice'); + + self::assertSame('team', $table->getTeamId()); + self::assertSame('bob', $table->getOwnership()); + } + + public function testManualTransferCannotMoveTeamTableToNonMember(): void { + $table = $this->createTable(false); + $table->setTeamId('team'); + $this->mapper->method('findForUpdate')->with(5)->willReturn($table); + $this->permissionsService->method('canChangeElementOwner')->with($table, 'alice')->willReturn(true); + $this->circleHelper->expects(self::once())->method('circleExists')->with('team', 'bob')->willReturn(false); + $this->mapper->expects(self::never())->method('update'); + $this->shareService->expects(self::never())->method('changeSenderForNode'); + $this->eventDispatcher->expects(self::never())->method('dispatchTyped'); + + $this->expectException(PermissionError::class); + $this->service->setOwner(5, 'bob', 'alice'); + } + + /** + * @dataProvider transferableTableProvider + */ + public function testManualTransferAllowsTeamMembersAndPersonalTables(?string $teamId): void { + $table = $this->createTable(false); + $table->setTeamId($teamId); + $this->mapper->method('findForUpdate')->with(5)->willReturn($table); + $this->permissionsService->method('canChangeElementOwner')->with($table, 'alice')->willReturn(true); + if ($teamId === null) { + $this->circleHelper->expects(self::never())->method('circleExists'); + } else { + $this->circleHelper->expects(self::once())->method('circleExists')->with($teamId, 'bob')->willReturn(true); + } + $this->mapper->expects(self::once())->method('update')->willReturnArgument(0); + $this->shareService->expects(self::once())->method('changeSenderForNode')->with('table', 5, 'bob', 'alice'); + + $transferred = $this->service->setOwner(5, 'bob', 'alice'); + + self::assertSame('bob', $transferred->getOwnership()); + self::assertSame($teamId, $transferred->getTeamId()); + } + + public static function transferableTableProvider(): array { + return [ + 'personal table' => [null], + 'team table with a member as recipient' => ['team'], + ]; + } + + public function testFailedSuccessorLookupDoesNotDeleteTables(): void { + $table = $this->createTable(false); + $table->setTeamId('team'); + $this->mapper->method('findAllByTeamId')->willReturn([$table]); + $this->circleHelper->method('findSuccessorUserId')->willThrowException(new InternalError('lookup failed')); + $this->mapper->expects(self::never())->method('delete'); + + $this->expectException(InternalError::class); + $this->service->handleTeamStewardDeparture('team', 'alice'); + } + + /** + * @dataProvider teamDeletionProvider + */ + public function testTeamCleanupDeletesNormallyWithoutChangingOwnershipMetadata(bool $teamDeleted): void { + $table = $this->createTable(false); + $table->setTeamId('team'); + $this->mapper->method('findAllByTeamId')->willReturn([$table]); + $this->mapper->method('findForUpdate')->with(5)->willReturn($table); + $this->mapper->method('find')->with(5)->willReturn($table); + $this->permissionsService->method('canManageTable')->with($table, 'alice')->willReturn(true); + $this->mapper->expects(self::never())->method('update'); + $this->mapper->expects(self::once())->method('delete')->with($table)->willReturnArgument(0); + $this->circleHelper->expects($teamDeleted ? self::never() : self::once())->method('findSuccessorUserId')->willReturn(null); + + if ($teamDeleted) { + $this->service->deleteTeamOwnedTables('team'); + } else { + $this->service->handleTeamStewardDeparture('team', 'alice'); + } + + self::assertSame('team', $table->getTeamId()); + } + + public static function teamDeletionProvider(): array { + return [ + 'team deleted' => [true], + 'last local member left' => [false], + ]; + } + public function testUpdateLogsUnarchiving(): void { $this->mapper->method('find')->with(5)->willReturn($this->createTable(true)); $this->mapper->method('update')->willReturnArgument(0);