GetSharedSecret.php 6.1 KB

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