RequestHandlerController.php 16 KB

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