GetSharedSecret.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Federation\BackgroundJob;
  8. use GuzzleHttp\Exception\ClientException;
  9. use GuzzleHttp\Exception\RequestException;
  10. use OCA\Federation\TrustedServers;
  11. use OCP\AppFramework\Http;
  12. use OCP\AppFramework\Utility\ITimeFactory;
  13. use OCP\BackgroundJob\IJobList;
  14. use OCP\BackgroundJob\Job;
  15. use OCP\Http\Client\IClient;
  16. use OCP\Http\Client\IClientService;
  17. use OCP\Http\Client\IResponse;
  18. use OCP\IURLGenerator;
  19. use OCP\OCS\IDiscoveryService;
  20. use Psr\Log\LoggerInterface;
  21. /**
  22. * Class GetSharedSecret
  23. *
  24. * Request shared secret from remote Nextcloud
  25. *
  26. * @package OCA\Federation\Backgroundjob
  27. */
  28. class GetSharedSecret extends Job {
  29. private IClient $httpClient;
  30. private IJobList $jobList;
  31. private IURLGenerator $urlGenerator;
  32. private TrustedServers $trustedServers;
  33. private IDiscoveryService $ocsDiscoveryService;
  34. private LoggerInterface $logger;
  35. protected bool $retainJob = false;
  36. private string $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
  37. /** 30 day = 2592000sec */
  38. private int $maxLifespan = 2592000;
  39. public function __construct(
  40. IClientService $httpClientService,
  41. IURLGenerator $urlGenerator,
  42. IJobList $jobList,
  43. TrustedServers $trustedServers,
  44. LoggerInterface $logger,
  45. IDiscoveryService $ocsDiscoveryService,
  46. ITimeFactory $timeFactory
  47. ) {
  48. parent::__construct($timeFactory);
  49. $this->logger = $logger;
  50. $this->httpClient = $httpClientService->newClient();
  51. $this->jobList = $jobList;
  52. $this->urlGenerator = $urlGenerator;
  53. $this->ocsDiscoveryService = $ocsDiscoveryService;
  54. $this->trustedServers = $trustedServers;
  55. }
  56. /**
  57. * Run the job, then remove it from the joblist
  58. */
  59. public function start(IJobList $jobList): void {
  60. $target = $this->argument['url'];
  61. // only execute if target is still in the list of trusted domains
  62. if ($this->trustedServers->isTrustedServer($target)) {
  63. $this->parentStart($jobList);
  64. }
  65. $jobList->remove($this, $this->argument);
  66. if ($this->retainJob) {
  67. $this->reAddJob($this->argument);
  68. }
  69. }
  70. protected function parentStart(IJobList $jobList): void {
  71. parent::start($jobList);
  72. }
  73. protected function run($argument) {
  74. $target = $argument['url'];
  75. $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
  76. $currentTime = $this->time->getTime();
  77. $source = $this->urlGenerator->getAbsoluteURL('/');
  78. $source = rtrim($source, '/');
  79. $token = $argument['token'];
  80. // kill job after 30 days of trying
  81. $deadline = $currentTime - $this->maxLifespan;
  82. if ($created < $deadline) {
  83. $this->retainJob = false;
  84. $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
  85. return;
  86. }
  87. $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
  88. $endPoint = $endPoints['shared-secret'] ?? $this->defaultEndPoint;
  89. // make sure that we have a well formatted url
  90. $url = rtrim($target, '/') . '/' . trim($endPoint, '/');
  91. $result = null;
  92. try {
  93. $result = $this->httpClient->get(
  94. $url,
  95. [
  96. 'query' =>
  97. [
  98. 'url' => $source,
  99. 'token' => $token,
  100. 'format' => 'json',
  101. ],
  102. 'timeout' => 3,
  103. 'connect_timeout' => 3,
  104. ]
  105. );
  106. $status = $result->getStatusCode();
  107. } catch (ClientException $e) {
  108. $status = $e->getCode();
  109. if ($status === Http::STATUS_FORBIDDEN) {
  110. $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
  111. } else {
  112. $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
  113. }
  114. } catch (RequestException $e) {
  115. $status = -1; // There is no status code if we could not connect
  116. $this->logger->info('Could not connect to ' . $target, [
  117. 'exception' => $e,
  118. ]);
  119. } catch (\Throwable $e) {
  120. $status = Http::STATUS_INTERNAL_SERVER_ERROR;
  121. $this->logger->error($e->getMessage(), [
  122. 'exception' => $e,
  123. ]);
  124. }
  125. // if we received a unexpected response we try again later
  126. if (
  127. $status !== Http::STATUS_OK
  128. && $status !== Http::STATUS_FORBIDDEN
  129. ) {
  130. $this->retainJob = true;
  131. }
  132. if ($status === Http::STATUS_OK && $result instanceof IResponse) {
  133. $body = $result->getBody();
  134. $result = json_decode($body, true);
  135. if (isset($result['ocs']['data']['sharedSecret'])) {
  136. $this->trustedServers->addSharedSecret(
  137. $target,
  138. $result['ocs']['data']['sharedSecret']
  139. );
  140. } else {
  141. $this->logger->error(
  142. 'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
  143. ['app' => 'federation']
  144. );
  145. $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
  146. }
  147. }
  148. }
  149. /**
  150. * Re-add background job
  151. *
  152. * @param array $argument
  153. */
  154. protected function reAddJob(array $argument): void {
  155. $url = $argument['url'];
  156. $created = $argument['created'] ?? $this->time->getTime();
  157. $token = $argument['token'];
  158. $this->jobList->add(
  159. GetSharedSecret::class,
  160. [
  161. 'url' => $url,
  162. 'token' => $token,
  163. 'created' => $created
  164. ]
  165. );
  166. }
  167. }