RequestSharedSecret.php 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OCA\Federation\BackgroundJob;
  9. use GuzzleHttp\Exception\ClientException;
  10. use GuzzleHttp\Exception\RequestException;
  11. use OCA\Federation\TrustedServers;
  12. use OCP\AppFramework\Http;
  13. use OCP\AppFramework\Utility\ITimeFactory;
  14. use OCP\BackgroundJob\IJobList;
  15. use OCP\BackgroundJob\Job;
  16. use OCP\Http\Client\IClient;
  17. use OCP\Http\Client\IClientService;
  18. use OCP\IURLGenerator;
  19. use OCP\OCS\IDiscoveryService;
  20. use Psr\Log\LoggerInterface;
  21. /**
  22. * Class RequestSharedSecret
  23. *
  24. * Ask remote Nextcloud to request a sharedSecret from this server
  25. *
  26. * @package OCA\Federation\Backgroundjob
  27. */
  28. class RequestSharedSecret extends Job {
  29. private IClient $httpClient;
  30. protected bool $retainJob = false;
  31. private string $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
  32. /** @var int 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 IDiscoveryService $ocsDiscoveryService,
  40. private LoggerInterface $logger,
  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. /**
  61. * Call start() method of parent
  62. * Useful for unit tests
  63. */
  64. protected function parentStart(IJobList $jobList): void {
  65. parent::start($jobList);
  66. }
  67. /**
  68. * @param array $argument
  69. * @return void
  70. */
  71. protected function run($argument) {
  72. $target = $argument['url'];
  73. $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
  74. $currentTime = $this->time->getTime();
  75. $source = $this->urlGenerator->getAbsoluteURL('/');
  76. $source = rtrim($source, '/');
  77. $token = $argument['token'];
  78. // kill job after 30 days of trying
  79. $deadline = $currentTime - $this->maxLifespan;
  80. if ($created < $deadline) {
  81. $this->retainJob = false;
  82. $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
  83. return;
  84. }
  85. $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
  86. $endPoint = $endPoints['shared-secret'] ?? $this->defaultEndPoint;
  87. // make sure that we have a well formatted url
  88. $url = rtrim($target, '/') . '/' . trim($endPoint, '/');
  89. try {
  90. $result = $this->httpClient->post(
  91. $url,
  92. [
  93. 'body' => [
  94. 'url' => $source,
  95. 'token' => $token,
  96. 'format' => 'json',
  97. ],
  98. 'timeout' => 3,
  99. 'connect_timeout' => 3,
  100. ]
  101. );
  102. $status = $result->getStatusCode();
  103. } catch (ClientException $e) {
  104. $status = $e->getCode();
  105. if ($status === Http::STATUS_FORBIDDEN) {
  106. $this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
  107. } else {
  108. $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
  109. }
  110. } catch (RequestException $e) {
  111. $status = -1; // There is no status code if we could not connect
  112. $this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
  113. } catch (\Throwable $e) {
  114. $status = Http::STATUS_INTERNAL_SERVER_ERROR;
  115. $this->logger->error($e->getMessage(), ['app' => 'federation', 'exception' => $e]);
  116. }
  117. // if we received a unexpected response we try again later
  118. if (
  119. $status !== Http::STATUS_OK
  120. && ($status !== Http::STATUS_FORBIDDEN || $this->getAttempt($argument) < 5)
  121. ) {
  122. $this->retainJob = true;
  123. }
  124. }
  125. /**
  126. * re-add background job
  127. */
  128. protected function reAddJob(array $argument): void {
  129. $url = $argument['url'];
  130. $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
  131. $token = $argument['token'];
  132. $attempt = $this->getAttempt($argument) + 1;
  133. $this->jobList->add(
  134. RequestSharedSecret::class,
  135. [
  136. 'url' => $url,
  137. 'token' => $token,
  138. 'created' => $created,
  139. 'attempt' => $attempt
  140. ]
  141. );
  142. }
  143. protected function getAttempt(array $argument): int {
  144. return $argument['attempt'] ?? 0;
  145. }
  146. }