GetSharedSecret.php 5.0 KB

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