RequestHandlerController.php 10 KB

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