1
0

RequestHandlerController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\FederatedFileSharing\Controller;
  8. use OCA\FederatedFileSharing\AddressHandler;
  9. use OCA\FederatedFileSharing\FederatedShareProvider;
  10. use OCA\FederatedFileSharing\Notifications;
  11. use OCP\App\IAppManager;
  12. use OCP\AppFramework\Http;
  13. use OCP\AppFramework\Http\Attribute\OpenAPI;
  14. use OCP\AppFramework\OCS\OCSBadRequestException;
  15. use OCP\AppFramework\OCS\OCSException;
  16. use OCP\AppFramework\OCSController;
  17. use OCP\Constants;
  18. use OCP\EventDispatcher\IEventDispatcher;
  19. use OCP\Federation\Exceptions\ProviderCouldNotAddShareException;
  20. use OCP\Federation\Exceptions\ProviderDoesNotExistsException;
  21. use OCP\Federation\ICloudFederationFactory;
  22. use OCP\Federation\ICloudFederationProviderManager;
  23. use OCP\Federation\ICloudIdManager;
  24. use OCP\IDBConnection;
  25. use OCP\IRequest;
  26. use OCP\IUserManager;
  27. use OCP\Log\Audit\CriticalActionPerformedEvent;
  28. use OCP\Share;
  29. use OCP\Share\Exceptions\ShareNotFound;
  30. use Psr\Log\LoggerInterface;
  31. #[OpenAPI(scope: OpenAPI::SCOPE_FEDERATION)]
  32. class RequestHandlerController extends OCSController {
  33. /** @var FederatedShareProvider */
  34. private $federatedShareProvider;
  35. /** @var IDBConnection */
  36. private $connection;
  37. /** @var Share\IManager */
  38. private $shareManager;
  39. /** @var Notifications */
  40. private $notifications;
  41. /** @var AddressHandler */
  42. private $addressHandler;
  43. /** @var IUserManager */
  44. private $userManager;
  45. /** @var string */
  46. private $shareTable = 'share';
  47. /** @var ICloudIdManager */
  48. private $cloudIdManager;
  49. /** @var LoggerInterface */
  50. private $logger;
  51. /** @var ICloudFederationFactory */
  52. private $cloudFederationFactory;
  53. /** @var ICloudFederationProviderManager */
  54. private $cloudFederationProviderManager;
  55. /** @var IEventDispatcher */
  56. private $eventDispatcher;
  57. public function __construct(string $appName,
  58. IRequest $request,
  59. FederatedShareProvider $federatedShareProvider,
  60. IDBConnection $connection,
  61. Share\IManager $shareManager,
  62. Notifications $notifications,
  63. AddressHandler $addressHandler,
  64. IUserManager $userManager,
  65. ICloudIdManager $cloudIdManager,
  66. LoggerInterface $logger,
  67. ICloudFederationFactory $cloudFederationFactory,
  68. ICloudFederationProviderManager $cloudFederationProviderManager,
  69. IEventDispatcher $eventDispatcher
  70. ) {
  71. parent::__construct($appName, $request);
  72. $this->federatedShareProvider = $federatedShareProvider;
  73. $this->connection = $connection;
  74. $this->shareManager = $shareManager;
  75. $this->notifications = $notifications;
  76. $this->addressHandler = $addressHandler;
  77. $this->userManager = $userManager;
  78. $this->cloudIdManager = $cloudIdManager;
  79. $this->logger = $logger;
  80. $this->cloudFederationFactory = $cloudFederationFactory;
  81. $this->cloudFederationProviderManager = $cloudFederationProviderManager;
  82. $this->eventDispatcher = $eventDispatcher;
  83. }
  84. /**
  85. * @NoCSRFRequired
  86. * @PublicPage
  87. *
  88. * create a new share
  89. *
  90. * @param string|null $remote Address of the remote
  91. * @param string|null $token Shared secret between servers
  92. * @param string|null $name Name of the shared resource
  93. * @param string|null $owner Display name of the receiver
  94. * @param string|null $sharedBy Display name of the sender
  95. * @param string|null $shareWith ID of the user that receives the share
  96. * @param int|null $remoteId ID of the remote
  97. * @param string|null $sharedByFederatedId Federated ID of the sender
  98. * @param string|null $ownerFederatedId Federated ID of the receiver
  99. * @return Http\DataResponse<Http::STATUS_OK, array<empty>, array{}>
  100. * @throws OCSException
  101. *
  102. * 200: Share created successfully
  103. */
  104. public function createShare(
  105. ?string $remote = null,
  106. ?string $token = null,
  107. ?string $name = null,
  108. ?string $owner = null,
  109. ?string $sharedBy = null,
  110. ?string $shareWith = null,
  111. ?int $remoteId = null,
  112. ?string $sharedByFederatedId = null,
  113. ?string $ownerFederatedId = null,
  114. ) {
  115. if ($ownerFederatedId === null) {
  116. $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
  117. }
  118. // if the owner of the share and the initiator are the same user
  119. // we also complete the federated share ID for the initiator
  120. if ($sharedByFederatedId === null && $owner === $sharedBy) {
  121. $sharedByFederatedId = $ownerFederatedId;
  122. }
  123. $share = $this->cloudFederationFactory->getCloudFederationShare(
  124. $shareWith,
  125. $name,
  126. '',
  127. $remoteId,
  128. $ownerFederatedId,
  129. $owner,
  130. $sharedByFederatedId,
  131. $sharedBy,
  132. $token,
  133. 'user',
  134. 'file'
  135. );
  136. try {
  137. $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
  138. $provider->shareReceived($share);
  139. if ($sharedByFederatedId === $ownerFederatedId) {
  140. $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('A new federated share with "%s" was created by "%s" and shared with "%s"', [$name, $ownerFederatedId, $shareWith]));
  141. } else {
  142. $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('A new federated share with "%s" was shared by "%s" (resource owner is: "%s") and shared with "%s"', [$name, $sharedByFederatedId, $ownerFederatedId, $shareWith]));
  143. }
  144. } catch (ProviderDoesNotExistsException $e) {
  145. throw new OCSException('Server does not support federated cloud sharing', 503);
  146. } catch (ProviderCouldNotAddShareException $e) {
  147. throw new OCSException($e->getMessage(), 400);
  148. } catch (\Exception $e) {
  149. throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
  150. }
  151. return new Http\DataResponse();
  152. }
  153. /**
  154. * @NoCSRFRequired
  155. * @PublicPage
  156. *
  157. * create re-share on behalf of another user
  158. *
  159. * @param int $id ID of the share
  160. * @param string|null $token Shared secret between servers
  161. * @param string|null $shareWith ID of the user that receives the share
  162. * @param int|null $remoteId ID of the remote
  163. * @return Http\DataResponse<Http::STATUS_OK, array{token: string, remoteId: string}, array{}>
  164. * @throws OCSBadRequestException Re-sharing is not possible
  165. * @throws OCSException
  166. *
  167. * 200: Remote share returned
  168. */
  169. public function reShare(int $id, ?string $token = null, ?string $shareWith = null, ?int $remoteId = 0) {
  170. if ($token === null ||
  171. $shareWith === null ||
  172. $remoteId === null
  173. ) {
  174. throw new OCSBadRequestException();
  175. }
  176. $notification = [
  177. 'sharedSecret' => $token,
  178. 'shareWith' => $shareWith,
  179. 'senderId' => $remoteId,
  180. 'message' => 'Recipient of a share ask the owner to reshare the file'
  181. ];
  182. try {
  183. $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
  184. [$newToken, $localId] = $provider->notificationReceived('REQUEST_RESHARE', $id, $notification);
  185. return new Http\DataResponse([
  186. 'token' => $newToken,
  187. 'remoteId' => $localId
  188. ]);
  189. } catch (ProviderDoesNotExistsException $e) {
  190. throw new OCSException('Server does not support federated cloud sharing', 503);
  191. } catch (ShareNotFound $e) {
  192. $this->logger->debug('Share not found: ' . $e->getMessage(), ['exception' => $e]);
  193. } catch (\Exception $e) {
  194. $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage(), ['exception' => $e]);
  195. }
  196. throw new OCSBadRequestException();
  197. }
  198. /**
  199. * @NoCSRFRequired
  200. * @PublicPage
  201. *
  202. * accept server-to-server share
  203. *
  204. * @param int $id ID of the remote share
  205. * @param string|null $token Shared secret between servers
  206. * @return Http\DataResponse<Http::STATUS_OK, array<empty>, array{}>
  207. * @throws OCSException
  208. * @throws ShareNotFound
  209. * @throws \OCP\HintException
  210. *
  211. * 200: Share accepted successfully
  212. */
  213. public function acceptShare(int $id, ?string $token = null) {
  214. $notification = [
  215. 'sharedSecret' => $token,
  216. 'message' => 'Recipient accept the share'
  217. ];
  218. try {
  219. $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
  220. $provider->notificationReceived('SHARE_ACCEPTED', $id, $notification);
  221. $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('Federated share with id "%s" was accepted', [$id]));
  222. } catch (ProviderDoesNotExistsException $e) {
  223. throw new OCSException('Server does not support federated cloud sharing', 503);
  224. } catch (ShareNotFound $e) {
  225. $this->logger->debug('Share not found: ' . $e->getMessage(), ['exception' => $e]);
  226. } catch (\Exception $e) {
  227. $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage(), ['exception' => $e]);
  228. }
  229. return new Http\DataResponse();
  230. }
  231. /**
  232. * @NoCSRFRequired
  233. * @PublicPage
  234. *
  235. * decline server-to-server share
  236. *
  237. * @param int $id ID of the remote share
  238. * @param string|null $token Shared secret between servers
  239. * @return Http\DataResponse<Http::STATUS_OK, array<empty>, array{}>
  240. * @throws OCSException
  241. *
  242. * 200: Share declined successfully
  243. */
  244. public function declineShare(int $id, ?string $token = null) {
  245. $notification = [
  246. 'sharedSecret' => $token,
  247. 'message' => 'Recipient declined the share'
  248. ];
  249. try {
  250. $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
  251. $provider->notificationReceived('SHARE_DECLINED', $id, $notification);
  252. $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('Federated share with id "%s" was declined', [$id]));
  253. } catch (ProviderDoesNotExistsException $e) {
  254. throw new OCSException('Server does not support federated cloud sharing', 503);
  255. } catch (ShareNotFound $e) {
  256. $this->logger->debug('Share not found: ' . $e->getMessage(), ['exception' => $e]);
  257. } catch (\Exception $e) {
  258. $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage(), ['exception' => $e]);
  259. }
  260. return new Http\DataResponse();
  261. }
  262. /**
  263. * @NoCSRFRequired
  264. * @PublicPage
  265. *
  266. * remove server-to-server share if it was unshared by the owner
  267. *
  268. * @param int $id ID of the share
  269. * @param string|null $token Shared secret between servers
  270. * @return Http\DataResponse<Http::STATUS_OK, array<empty>, array{}>
  271. * @throws OCSException
  272. *
  273. * 200: Share unshared successfully
  274. */
  275. public function unshare(int $id, ?string $token = null) {
  276. if (!$this->isS2SEnabled()) {
  277. throw new OCSException('Server does not support federated cloud sharing', 503);
  278. }
  279. try {
  280. $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
  281. $notification = ['sharedSecret' => $token];
  282. $provider->notificationReceived('SHARE_UNSHARED', $id, $notification);
  283. $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('Federated share with id "%s" was unshared', [$id]));
  284. } catch (\Exception $e) {
  285. $this->logger->debug('processing unshare notification failed: ' . $e->getMessage(), ['exception' => $e]);
  286. }
  287. return new Http\DataResponse();
  288. }
  289. private function cleanupRemote($remote) {
  290. $remote = substr($remote, strpos($remote, '://') + 3);
  291. return rtrim($remote, '/');
  292. }
  293. /**
  294. * @NoCSRFRequired
  295. * @PublicPage
  296. *
  297. * federated share was revoked, either by the owner or the re-sharer
  298. *
  299. * @param int $id ID of the share
  300. * @param string|null $token Shared secret between servers
  301. * @return Http\DataResponse<Http::STATUS_OK, array<empty>, array{}>
  302. * @throws OCSBadRequestException Revoking the share is not possible
  303. *
  304. * 200: Share revoked successfully
  305. */
  306. public function revoke(int $id, ?string $token = null) {
  307. try {
  308. $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
  309. $notification = ['sharedSecret' => $token];
  310. $provider->notificationReceived('RESHARE_UNDO', $id, $notification);
  311. return new Http\DataResponse();
  312. } catch (\Exception $e) {
  313. throw new OCSBadRequestException();
  314. }
  315. }
  316. /**
  317. * check if server-to-server sharing is enabled
  318. *
  319. * @param bool $incoming
  320. * @return bool
  321. */
  322. private function isS2SEnabled($incoming = false) {
  323. $result = \OCP\Server::get(IAppManager::class)->isEnabledForUser('files_sharing');
  324. if ($incoming) {
  325. $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
  326. } else {
  327. $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
  328. }
  329. return $result;
  330. }
  331. /**
  332. * @NoCSRFRequired
  333. * @PublicPage
  334. *
  335. * update share information to keep federated re-shares in sync
  336. *
  337. * @param int $id ID of the share
  338. * @param string|null $token Shared secret between servers
  339. * @param int|null $permissions New permissions
  340. * @return Http\DataResponse<Http::STATUS_OK, array<empty>, array{}>
  341. * @throws OCSBadRequestException Updating permissions is not possible
  342. *
  343. * 200: Permissions updated successfully
  344. */
  345. public function updatePermissions(int $id, ?string $token = null, ?int $permissions = null) {
  346. $ncPermissions = $permissions;
  347. try {
  348. $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
  349. $ocmPermissions = $this->ncPermissions2ocmPermissions((int)$ncPermissions);
  350. $notification = ['sharedSecret' => $token, 'permission' => $ocmPermissions];
  351. $provider->notificationReceived('RESHARE_CHANGE_PERMISSION', $id, $notification);
  352. $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('Federated share with id "%s" has updated permissions "%s"', [$id, implode(', ', $ocmPermissions)]));
  353. } catch (\Exception $e) {
  354. $this->logger->debug($e->getMessage(), ['exception' => $e]);
  355. throw new OCSBadRequestException();
  356. }
  357. return new Http\DataResponse();
  358. }
  359. /**
  360. * translate Nextcloud permissions to OCM Permissions
  361. *
  362. * @param $ncPermissions
  363. * @return array
  364. */
  365. protected function ncPermissions2ocmPermissions($ncPermissions) {
  366. $ocmPermissions = [];
  367. if ($ncPermissions & Constants::PERMISSION_SHARE) {
  368. $ocmPermissions[] = 'share';
  369. }
  370. if ($ncPermissions & Constants::PERMISSION_READ) {
  371. $ocmPermissions[] = 'read';
  372. }
  373. if (($ncPermissions & Constants::PERMISSION_CREATE) ||
  374. ($ncPermissions & Constants::PERMISSION_UPDATE)) {
  375. $ocmPermissions[] = 'write';
  376. }
  377. return $ocmPermissions;
  378. }
  379. /**
  380. * @NoCSRFRequired
  381. * @PublicPage
  382. *
  383. * change the owner of a server-to-server share
  384. *
  385. * @param int $id ID of the share
  386. * @param string|null $token Shared secret between servers
  387. * @param string|null $remote Address of the remote
  388. * @param string|null $remote_id ID of the remote
  389. * @return Http\DataResponse<Http::STATUS_OK, array{remote: string, owner: string}, array{}>
  390. * @throws OCSBadRequestException Moving share is not possible
  391. *
  392. * 200: Share moved successfully
  393. */
  394. public function move(int $id, ?string $token = null, ?string $remote = null, ?string $remote_id = null) {
  395. if (!$this->isS2SEnabled()) {
  396. throw new OCSException('Server does not support federated cloud sharing', 503);
  397. }
  398. $newRemoteId = (string) ($remote_id ?? $id);
  399. $cloudId = $this->cloudIdManager->resolveCloudId($remote);
  400. $qb = $this->connection->getQueryBuilder();
  401. $query = $qb->update('share_external')
  402. ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
  403. ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
  404. ->set('remote_id', $qb->createNamedParameter($newRemoteId))
  405. ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
  406. ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
  407. $affected = $query->executeStatement();
  408. if ($affected > 0) {
  409. return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
  410. } else {
  411. throw new OCSBadRequestException('Share not found or token invalid');
  412. }
  413. }
  414. }