You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RequestHandlerController.php 16KB

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