RequestHandlerController.php 11 KB

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