RequestHandlerController.php 10.0 KB

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