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.

193 lines
6.2 KiB

  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\OCM;
  8. use GuzzleHttp\Exception\ConnectException;
  9. use JsonException;
  10. use NCU\Security\Signature\Exceptions\IdentityNotFoundException;
  11. use NCU\Security\Signature\Exceptions\SignatoryException;
  12. use OC\Core\AppInfo\ConfigLexicon;
  13. use OC\OCM\Model\OCMProvider;
  14. use OCP\AppFramework\Http;
  15. use OCP\EventDispatcher\IEventDispatcher;
  16. use OCP\Http\Client\IClientService;
  17. use OCP\IAppConfig;
  18. use OCP\ICache;
  19. use OCP\ICacheFactory;
  20. use OCP\IConfig;
  21. use OCP\IURLGenerator;
  22. use OCP\OCM\Events\ResourceTypeRegisterEvent;
  23. use OCP\OCM\Exceptions\OCMProviderException;
  24. use OCP\OCM\ICapabilityAwareOCMProvider;
  25. use OCP\OCM\IOCMDiscoveryService;
  26. use Psr\Log\LoggerInterface;
  27. /**
  28. * @since 28.0.0
  29. */
  30. class OCMDiscoveryService implements IOCMDiscoveryService {
  31. private ICache $cache;
  32. public const API_VERSION = '1.1.0';
  33. private ?ICapabilityAwareOCMProvider $localProvider = null;
  34. /** @var array<string, ICapabilityAwareOCMProvider> */
  35. private array $remoteProviders = [];
  36. public function __construct(
  37. ICacheFactory $cacheFactory,
  38. private IClientService $clientService,
  39. private IEventDispatcher $eventDispatcher,
  40. protected IConfig $config,
  41. private IAppConfig $appConfig,
  42. private IURLGenerator $urlGenerator,
  43. private OCMSignatoryManager $ocmSignatoryManager,
  44. private LoggerInterface $logger,
  45. ) {
  46. $this->cache = $cacheFactory->createDistributed('ocm-discovery');
  47. }
  48. /**
  49. * @param string $remote
  50. * @param bool $skipCache
  51. *
  52. * @return ICapabilityAwareOCMProvider
  53. * @throws OCMProviderException
  54. */
  55. public function discover(string $remote, bool $skipCache = false): ICapabilityAwareOCMProvider {
  56. $remote = rtrim($remote, '/');
  57. if (!str_starts_with($remote, 'http://') && !str_starts_with($remote, 'https://')) {
  58. // if scheme not specified, we test both;
  59. try {
  60. return $this->discover('https://' . $remote, $skipCache);
  61. } catch (OCMProviderException|ConnectException) {
  62. return $this->discover('http://' . $remote, $skipCache);
  63. }
  64. }
  65. if (array_key_exists($remote, $this->remoteProviders)) {
  66. return $this->remoteProviders[$remote];
  67. }
  68. $provider = new OCMProvider();
  69. if (!$skipCache) {
  70. try {
  71. $cached = $this->cache->get($remote);
  72. if ($cached === false) {
  73. throw new OCMProviderException('Previous discovery failed.');
  74. }
  75. if ($cached !== null) {
  76. $provider->import(json_decode($cached, true, 8, JSON_THROW_ON_ERROR) ?? []);
  77. $this->remoteProviders[$remote] = $provider;
  78. return $provider;
  79. }
  80. } catch (JsonException|OCMProviderException $e) {
  81. $this->logger->warning('cache issue on ocm discovery', ['exception' => $e]);
  82. }
  83. }
  84. $client = $this->clientService->newClient();
  85. try {
  86. $options = [
  87. 'timeout' => 10,
  88. 'connect_timeout' => 10,
  89. ];
  90. if ($this->config->getSystemValueBool('sharing.federation.allowSelfSignedCertificates') === true) {
  91. $options['verify'] = false;
  92. }
  93. $response = $client->get($remote . '/ocm-provider/', $options);
  94. $body = null;
  95. if ($response->getStatusCode() === Http::STATUS_OK) {
  96. $body = $response->getBody();
  97. // update provider with data returned by the request
  98. $provider->import(json_decode($body, true, 8, JSON_THROW_ON_ERROR) ?? []);
  99. $this->cache->set($remote, $body, 60 * 60 * 24);
  100. $this->remoteProviders[$remote] = $provider;
  101. return $provider;
  102. }
  103. throw new OCMProviderException('invalid remote ocm endpoint');
  104. } catch (JsonException|OCMProviderException) {
  105. $this->cache->set($remote, false, 5 * 60);
  106. throw new OCMProviderException('data returned by remote seems invalid - status:' . $response->getStatusCode() . ' - ' . ($body ?? ''));
  107. } catch (\Exception $e) {
  108. $this->cache->set($remote, false, 5 * 60);
  109. $this->logger->warning('error while discovering ocm provider', [
  110. 'exception' => $e,
  111. 'remote' => $remote
  112. ]);
  113. throw new OCMProviderException('error while requesting remote ocm provider');
  114. }
  115. }
  116. /**
  117. * @return ICapabilityAwareOCMProvider
  118. */
  119. public function getLocalOCMProvider(bool $fullDetails = true): ICapabilityAwareOCMProvider {
  120. if ($this->localProvider !== null) {
  121. return $this->localProvider;
  122. }
  123. $provider = new OCMProvider('Nextcloud ' . $this->config->getSystemValue('version'));
  124. if (!$this->appConfig->getValueBool('core', ConfigLexicon::OCM_DISCOVERY_ENABLED)) {
  125. return $provider;
  126. }
  127. $url = $this->urlGenerator->linkToRouteAbsolute('cloud_federation_api.requesthandlercontroller.addShare');
  128. $pos = strrpos($url, '/');
  129. if ($pos === false) {
  130. $this->logger->debug('generated route should contain a slash character');
  131. return $provider;
  132. }
  133. $provider->setEnabled(true);
  134. $provider->setApiVersion(self::API_VERSION);
  135. $provider->setEndPoint(substr($url, 0, $pos));
  136. $provider->setCapabilities(['/invite-accepted', '/notifications', '/shares']);
  137. // The inviteAcceptDialog is available from the contacts app, if this config value is set
  138. $inviteAcceptDialog = $this->appConfig->getValueString('core', ConfigLexicon::OCM_INVITE_ACCEPT_DIALOG);
  139. if ($inviteAcceptDialog !== '') {
  140. $provider->setInviteAcceptDialog($this->urlGenerator->linkToRouteAbsolute($inviteAcceptDialog));
  141. }
  142. $resource = $provider->createNewResourceType();
  143. $resource->setName('file')
  144. ->setShareTypes(['user', 'group'])
  145. ->setProtocols(['webdav' => '/public.php/webdav/']);
  146. $provider->addResourceType($resource);
  147. if ($fullDetails) {
  148. // Adding a public key to the ocm discovery
  149. try {
  150. if (!$this->appConfig->getValueBool('core', OCMSignatoryManager::APPCONFIG_SIGN_DISABLED, lazy: true)) {
  151. /**
  152. * @experimental 31.0.0
  153. * @psalm-suppress UndefinedInterfaceMethod
  154. */
  155. $provider->setSignatory($this->ocmSignatoryManager->getLocalSignatory());
  156. } else {
  157. $this->logger->debug('ocm public key feature disabled');
  158. }
  159. } catch (SignatoryException|IdentityNotFoundException $e) {
  160. $this->logger->warning('cannot generate local signatory', ['exception' => $e]);
  161. }
  162. }
  163. $event = new ResourceTypeRegisterEvent($provider);
  164. $this->eventDispatcher->dispatchTyped($event);
  165. $this->localProvider = $provider;
  166. return $provider;
  167. }
  168. }