RequestHandlerController.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\CloudFederationAPI\Controller;
  7. use OCA\CloudFederationAPI\Config;
  8. use OCA\CloudFederationAPI\ResponseDefinitions;
  9. use OCP\AppFramework\Controller;
  10. use OCP\AppFramework\Http;
  11. use OCP\AppFramework\Http\Attribute\OpenAPI;
  12. use OCP\AppFramework\Http\JSONResponse;
  13. use OCP\Federation\Exceptions\ActionNotSupportedException;
  14. use OCP\Federation\Exceptions\AuthenticationFailedException;
  15. use OCP\Federation\Exceptions\BadRequestException;
  16. use OCP\Federation\Exceptions\ProviderCouldNotAddShareException;
  17. use OCP\Federation\Exceptions\ProviderDoesNotExistsException;
  18. use OCP\Federation\ICloudFederationFactory;
  19. use OCP\Federation\ICloudFederationProviderManager;
  20. use OCP\Federation\ICloudIdManager;
  21. use OCP\IGroupManager;
  22. use OCP\IRequest;
  23. use OCP\IURLGenerator;
  24. use OCP\IUserManager;
  25. use OCP\Share\Exceptions\ShareNotFound;
  26. use Psr\Log\LoggerInterface;
  27. /**
  28. * Open-Cloud-Mesh-API
  29. *
  30. * @package OCA\CloudFederationAPI\Controller
  31. *
  32. * @psalm-import-type CloudFederationAPIAddShare from ResponseDefinitions
  33. * @psalm-import-type CloudFederationAPIValidationError from ResponseDefinitions
  34. * @psalm-import-type CloudFederationAPIError from ResponseDefinitions
  35. */
  36. #[OpenAPI(scope: OpenAPI::SCOPE_FEDERATION)]
  37. class RequestHandlerController extends Controller {
  38. public function __construct(
  39. string $appName,
  40. IRequest $request,
  41. private LoggerInterface $logger,
  42. private IUserManager $userManager,
  43. private IGroupManager $groupManager,
  44. private IURLGenerator $urlGenerator,
  45. private ICloudFederationProviderManager $cloudFederationProviderManager,
  46. private Config $config,
  47. private ICloudFederationFactory $factory,
  48. private ICloudIdManager $cloudIdManager
  49. ) {
  50. parent::__construct($appName, $request);
  51. }
  52. /**
  53. * Add share
  54. *
  55. * @NoCSRFRequired
  56. * @PublicPage
  57. * @BruteForceProtection(action=receiveFederatedShare)
  58. *
  59. * @param string $shareWith The user who the share will be shared with
  60. * @param string $name The resource name (e.g. document.odt)
  61. * @param string|null $description Share description
  62. * @param string $providerId Resource UID on the provider side
  63. * @param string $owner Provider specific UID of the user who owns the resource
  64. * @param string|null $ownerDisplayName Display name of the user who shared the item
  65. * @param string|null $sharedBy Provider specific UID of the user who shared the resource
  66. * @param string|null $sharedByDisplayName Display name of the user who shared the resource
  67. * @param array{name: string[], options: array<string, mixed>} $protocol e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]]
  68. * @param string $shareType 'group' or 'user' share
  69. * @param string $resourceType 'file', 'calendar',...
  70. *
  71. * @return JSONResponse<Http::STATUS_CREATED, CloudFederationAPIAddShare, array{}>|JSONResponse<Http::STATUS_BAD_REQUEST, CloudFederationAPIValidationError, array{}>|JSONResponse<Http::STATUS_NOT_IMPLEMENTED, CloudFederationAPIError, array{}>
  72. * 201: The notification was successfully received. The display name of the recipient might be returned in the body
  73. * 400: Bad request due to invalid parameters, e.g. when `shareWith` is not found or required properties are missing
  74. * 501: Share type or the resource type is not supported
  75. */
  76. public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
  77. // check if all required parameters are set
  78. if ($shareWith === null ||
  79. $name === null ||
  80. $providerId === null ||
  81. $owner === null ||
  82. $resourceType === null ||
  83. $shareType === null ||
  84. !is_array($protocol) ||
  85. !isset($protocol['name']) ||
  86. !isset($protocol['options']) ||
  87. !is_array($protocol['options']) ||
  88. !isset($protocol['options']['sharedSecret'])
  89. ) {
  90. return new JSONResponse(
  91. [
  92. 'message' => 'Missing arguments',
  93. 'validationErrors' => [],
  94. ],
  95. Http::STATUS_BAD_REQUEST
  96. );
  97. }
  98. $supportedShareTypes = $this->config->getSupportedShareTypes($resourceType);
  99. if (!in_array($shareType, $supportedShareTypes)) {
  100. return new JSONResponse(
  101. ['message' => 'Share type "' . $shareType . '" not implemented'],
  102. Http::STATUS_NOT_IMPLEMENTED
  103. );
  104. }
  105. $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
  106. $shareWith = $cloudId->getUser();
  107. if ($shareType === 'user') {
  108. $shareWith = $this->mapUid($shareWith);
  109. if (!$this->userManager->userExists($shareWith)) {
  110. $response = new JSONResponse(
  111. [
  112. 'message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl(),
  113. 'validationErrors' => [],
  114. ],
  115. Http::STATUS_BAD_REQUEST
  116. );
  117. $response->throttle();
  118. return $response;
  119. }
  120. }
  121. if ($shareType === 'group') {
  122. if (!$this->groupManager->groupExists($shareWith)) {
  123. $response = new JSONResponse(
  124. [
  125. 'message' => 'Group "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl(),
  126. 'validationErrors' => [],
  127. ],
  128. Http::STATUS_BAD_REQUEST
  129. );
  130. $response->throttle();
  131. return $response;
  132. }
  133. }
  134. // if no explicit display name is given, we use the uid as display name
  135. $ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
  136. $sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
  137. // sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
  138. if ($sharedBy === null) {
  139. $sharedBy = $owner;
  140. $sharedByDisplayName = $ownerDisplayName;
  141. }
  142. try {
  143. $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
  144. $share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
  145. $share->setProtocol($protocol);
  146. $provider->shareReceived($share);
  147. } catch (ProviderDoesNotExistsException|ProviderCouldNotAddShareException $e) {
  148. return new JSONResponse(
  149. ['message' => $e->getMessage()],
  150. Http::STATUS_NOT_IMPLEMENTED
  151. );
  152. } catch (\Exception $e) {
  153. $this->logger->error($e->getMessage(), ['exception' => $e]);
  154. return new JSONResponse(
  155. [
  156. 'message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl(),
  157. 'validationErrors' => [],
  158. ],
  159. Http::STATUS_BAD_REQUEST
  160. );
  161. }
  162. $user = $this->userManager->get($shareWith);
  163. $recipientDisplayName = '';
  164. if ($user) {
  165. $recipientDisplayName = $user->getDisplayName();
  166. }
  167. return new JSONResponse(
  168. ['recipientDisplayName' => $recipientDisplayName],
  169. Http::STATUS_CREATED);
  170. }
  171. /**
  172. * Send a notification about an existing share
  173. *
  174. * @NoCSRFRequired
  175. * @PublicPage
  176. * @BruteForceProtection(action=receiveFederatedShareNotification)
  177. *
  178. * @param string $notificationType Notification type, e.g. SHARE_ACCEPTED
  179. * @param string $resourceType calendar, file, contact,...
  180. * @param string|null $providerId ID of the share
  181. * @param array<string, mixed>|null $notification The actual payload of the notification
  182. *
  183. * @return JSONResponse<Http::STATUS_CREATED, array<string, mixed>, array{}>|JSONResponse<Http::STATUS_BAD_REQUEST, CloudFederationAPIValidationError, array{}>|JSONResponse<Http::STATUS_FORBIDDEN|Http::STATUS_NOT_IMPLEMENTED, CloudFederationAPIError, array{}>
  184. * 201: The notification was successfully received
  185. * 400: Bad request due to invalid parameters, e.g. when `type` is invalid or missing
  186. * 403: Getting resource is not allowed
  187. * 501: The resource type is not supported
  188. */
  189. public function receiveNotification($notificationType, $resourceType, $providerId, ?array $notification) {
  190. // check if all required parameters are set
  191. if ($notificationType === null ||
  192. $resourceType === null ||
  193. $providerId === null ||
  194. !is_array($notification)
  195. ) {
  196. return new JSONResponse(
  197. [
  198. 'message' => 'Missing arguments',
  199. 'validationErrors' => [],
  200. ],
  201. Http::STATUS_BAD_REQUEST
  202. );
  203. }
  204. try {
  205. $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
  206. $result = $provider->notificationReceived($notificationType, $providerId, $notification);
  207. } catch (ProviderDoesNotExistsException $e) {
  208. return new JSONResponse(
  209. [
  210. 'message' => $e->getMessage(),
  211. 'validationErrors' => [],
  212. ],
  213. Http::STATUS_BAD_REQUEST
  214. );
  215. } catch (ShareNotFound $e) {
  216. $response = new JSONResponse(
  217. [
  218. 'message' => $e->getMessage(),
  219. 'validationErrors' => [],
  220. ],
  221. Http::STATUS_BAD_REQUEST
  222. );
  223. $response->throttle();
  224. return $response;
  225. } catch (ActionNotSupportedException $e) {
  226. return new JSONResponse(
  227. ['message' => $e->getMessage()],
  228. Http::STATUS_NOT_IMPLEMENTED
  229. );
  230. } catch (BadRequestException $e) {
  231. return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
  232. } catch (AuthenticationFailedException $e) {
  233. $response = new JSONResponse(['message' => 'RESOURCE_NOT_FOUND'], Http::STATUS_FORBIDDEN);
  234. $response->throttle();
  235. return $response;
  236. } catch (\Exception $e) {
  237. return new JSONResponse(
  238. [
  239. 'message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl(),
  240. 'validationErrors' => [],
  241. ],
  242. Http::STATUS_BAD_REQUEST
  243. );
  244. }
  245. return new JSONResponse($result, Http::STATUS_CREATED);
  246. }
  247. /**
  248. * map login name to internal LDAP UID if a LDAP backend is in use
  249. *
  250. * @param string $uid
  251. * @return string mixed
  252. */
  253. private function mapUid($uid) {
  254. // FIXME this should be a method in the user management instead
  255. $this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
  256. \OCP\Util::emitHook(
  257. '\OCA\Files_Sharing\API\Server2Server',
  258. 'preLoginNameUsedAsUserName',
  259. ['uid' => &$uid]
  260. );
  261. $this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
  262. return $uid;
  263. }
  264. }