RequestSharedSecret.php 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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->logger->warning("The job to request the shared secret job is too old and gets stopped now without retention. Setting server status of '{$target}' to failure.");
  82. $this->retainJob = false;
  83. $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
  84. return;
  85. }
  86. $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
  87. $endPoint = $endPoints['shared-secret'] ?? $this->defaultEndPoint;
  88. // make sure that we have a well formatted url
  89. $url = rtrim($target, '/') . '/' . trim($endPoint, '/');
  90. try {
  91. $result = $this->httpClient->post(
  92. $url,
  93. [
  94. 'body' => [
  95. 'url' => $source,
  96. 'token' => $token,
  97. 'format' => 'json',
  98. ],
  99. 'timeout' => 3,
  100. 'connect_timeout' => 3,
  101. ]
  102. );
  103. $status = $result->getStatusCode();
  104. } catch (ClientException $e) {
  105. $status = $e->getCode();
  106. if ($status === Http::STATUS_FORBIDDEN) {
  107. $this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
  108. } else {
  109. $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
  110. }
  111. } catch (RequestException $e) {
  112. $status = -1; // There is no status code if we could not connect
  113. $this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
  114. } catch (\Throwable $e) {
  115. $status = Http::STATUS_INTERNAL_SERVER_ERROR;
  116. $this->logger->error($e->getMessage(), ['app' => 'federation', 'exception' => $e]);
  117. }
  118. // if we received a unexpected response we try again later
  119. if (
  120. $status !== Http::STATUS_OK
  121. && ($status !== Http::STATUS_FORBIDDEN || $this->getAttempt($argument) < 5)
  122. ) {
  123. $this->retainJob = true;
  124. }
  125. }
  126. /**
  127. * re-add background job
  128. */
  129. protected function reAddJob(array $argument): void {
  130. $url = $argument['url'];
  131. $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
  132. $token = $argument['token'];
  133. $attempt = $this->getAttempt($argument) + 1;
  134. $this->jobList->add(
  135. RequestSharedSecret::class,
  136. [
  137. 'url' => $url,
  138. 'token' => $token,
  139. 'created' => $created,
  140. 'attempt' => $attempt
  141. ]
  142. );
  143. }
  144. protected function getAttempt(array $argument): int {
  145. return $argument['attempt'] ?? 0;
  146. }
  147. }