GetSharedSecret.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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->logger->warning("The job to get the shared secret job is too old and gets stopped now without retention. Setting server status of '{$target}' to failure.");
  84. $this->retainJob = false;
  85. $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
  86. return;
  87. }
  88. $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
  89. $endPoint = $endPoints['shared-secret'] ?? $this->defaultEndPoint;
  90. // make sure that we have a well formatted url
  91. $url = rtrim($target, '/') . '/' . trim($endPoint, '/');
  92. $result = null;
  93. try {
  94. $result = $this->httpClient->get(
  95. $url,
  96. [
  97. 'query' =>
  98. [
  99. 'url' => $source,
  100. 'token' => $token,
  101. 'format' => 'json',
  102. ],
  103. 'timeout' => 3,
  104. 'connect_timeout' => 3,
  105. ]
  106. );
  107. $status = $result->getStatusCode();
  108. } catch (ClientException $e) {
  109. $status = $e->getCode();
  110. if ($status === Http::STATUS_FORBIDDEN) {
  111. $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
  112. } else {
  113. $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
  114. }
  115. } catch (RequestException $e) {
  116. $status = -1; // There is no status code if we could not connect
  117. $this->logger->info('Could not connect to ' . $target, [
  118. 'exception' => $e,
  119. ]);
  120. } catch (\Throwable $e) {
  121. $status = Http::STATUS_INTERNAL_SERVER_ERROR;
  122. $this->logger->error($e->getMessage(), [
  123. 'exception' => $e,
  124. ]);
  125. }
  126. // if we received a unexpected response we try again later
  127. if (
  128. $status !== Http::STATUS_OK
  129. && $status !== Http::STATUS_FORBIDDEN
  130. ) {
  131. $this->retainJob = true;
  132. }
  133. if ($status === Http::STATUS_OK && $result instanceof IResponse) {
  134. $body = $result->getBody();
  135. $result = json_decode($body, true);
  136. if (isset($result['ocs']['data']['sharedSecret'])) {
  137. $this->trustedServers->addSharedSecret(
  138. $target,
  139. $result['ocs']['data']['sharedSecret']
  140. );
  141. } else {
  142. $this->logger->error(
  143. 'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
  144. ['app' => 'federation']
  145. );
  146. $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
  147. }
  148. }
  149. }
  150. /**
  151. * Re-add background job
  152. *
  153. * @param array $argument
  154. */
  155. protected function reAddJob(array $argument): void {
  156. $url = $argument['url'];
  157. $created = $argument['created'] ?? $this->time->getTime();
  158. $token = $argument['token'];
  159. $this->jobList->add(
  160. GetSharedSecret::class,
  161. [
  162. 'url' => $url,
  163. 'token' => $token,
  164. 'created' => $created
  165. ]
  166. );
  167. }
  168. }