RequestSharedSecret.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Côme Chilliet <come@chilliet.eu>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Robin Appelman <robin@icewind.nl>
  14. * @author Roeland Jago Douma <roeland@famdouma.nl>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OCA\Federation\BackgroundJob;
  32. use GuzzleHttp\Exception\ClientException;
  33. use GuzzleHttp\Exception\RequestException;
  34. use OCA\Federation\TrustedServers;
  35. use OCP\AppFramework\Http;
  36. use OCP\AppFramework\Utility\ITimeFactory;
  37. use OCP\BackgroundJob\IJobList;
  38. use OCP\BackgroundJob\Job;
  39. use OCP\Http\Client\IClient;
  40. use OCP\Http\Client\IClientService;
  41. use OCP\IURLGenerator;
  42. use OCP\OCS\IDiscoveryService;
  43. use Psr\Log\LoggerInterface;
  44. /**
  45. * Class RequestSharedSecret
  46. *
  47. * Ask remote Nextcloud to request a sharedSecret from this server
  48. *
  49. * @package OCA\Federation\Backgroundjob
  50. */
  51. class RequestSharedSecret extends Job {
  52. private IClient $httpClient;
  53. protected bool $retainJob = false;
  54. private string $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
  55. /** @var int 30 day = 2592000sec */
  56. private int $maxLifespan = 2592000;
  57. public function __construct(
  58. IClientService $httpClientService,
  59. private IURLGenerator $urlGenerator,
  60. private IJobList $jobList,
  61. private TrustedServers $trustedServers,
  62. private IDiscoveryService $ocsDiscoveryService,
  63. private LoggerInterface $logger,
  64. ITimeFactory $timeFactory,
  65. ) {
  66. parent::__construct($timeFactory);
  67. $this->httpClient = $httpClientService->newClient();
  68. }
  69. /**
  70. * run the job, then remove it from the joblist
  71. */
  72. public function start(IJobList $jobList): void {
  73. $target = $this->argument['url'];
  74. // only execute if target is still in the list of trusted domains
  75. if ($this->trustedServers->isTrustedServer($target)) {
  76. $this->parentStart($jobList);
  77. }
  78. $jobList->remove($this, $this->argument);
  79. if ($this->retainJob) {
  80. $this->reAddJob($this->argument);
  81. }
  82. }
  83. /**
  84. * Call start() method of parent
  85. * Useful for unit tests
  86. */
  87. protected function parentStart(IJobList $jobList): void {
  88. parent::start($jobList);
  89. }
  90. /**
  91. * @param array $argument
  92. * @return void
  93. */
  94. protected function run($argument) {
  95. $target = $argument['url'];
  96. $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
  97. $currentTime = $this->time->getTime();
  98. $source = $this->urlGenerator->getAbsoluteURL('/');
  99. $source = rtrim($source, '/');
  100. $token = $argument['token'];
  101. // kill job after 30 days of trying
  102. $deadline = $currentTime - $this->maxLifespan;
  103. if ($created < $deadline) {
  104. $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.");
  105. $this->retainJob = false;
  106. $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
  107. return;
  108. }
  109. $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
  110. $endPoint = $endPoints['shared-secret'] ?? $this->defaultEndPoint;
  111. // make sure that we have a well formatted url
  112. $url = rtrim($target, '/') . '/' . trim($endPoint, '/');
  113. try {
  114. $result = $this->httpClient->post(
  115. $url,
  116. [
  117. 'body' => [
  118. 'url' => $source,
  119. 'token' => $token,
  120. 'format' => 'json',
  121. ],
  122. 'timeout' => 3,
  123. 'connect_timeout' => 3,
  124. ]
  125. );
  126. $status = $result->getStatusCode();
  127. } catch (ClientException $e) {
  128. $status = $e->getCode();
  129. if ($status === Http::STATUS_FORBIDDEN) {
  130. $this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
  131. } else {
  132. $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
  133. }
  134. } catch (RequestException $e) {
  135. $status = -1; // There is no status code if we could not connect
  136. $this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
  137. } catch (\Throwable $e) {
  138. $status = Http::STATUS_INTERNAL_SERVER_ERROR;
  139. $this->logger->error($e->getMessage(), ['app' => 'federation', 'exception' => $e]);
  140. }
  141. // if we received a unexpected response we try again later
  142. if (
  143. $status !== Http::STATUS_OK
  144. && ($status !== Http::STATUS_FORBIDDEN || $this->getAttempt($argument) < 5)
  145. ) {
  146. $this->retainJob = true;
  147. }
  148. }
  149. /**
  150. * re-add background job
  151. */
  152. protected function reAddJob(array $argument): void {
  153. $url = $argument['url'];
  154. $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
  155. $token = $argument['token'];
  156. $attempt = $this->getAttempt($argument) + 1;
  157. $this->jobList->add(
  158. RequestSharedSecret::class,
  159. [
  160. 'url' => $url,
  161. 'token' => $token,
  162. 'created' => $created,
  163. 'attempt' => $attempt
  164. ]
  165. );
  166. }
  167. protected function getAttempt(array $argument): int {
  168. return $argument['attempt'] ?? 0;
  169. }
  170. }