GetSharedSecret.php 7.1 KB

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