Completed
Pull Request — master (#551)
by Maxence
02:35
created

CirclesRemote::verifyGSInstances()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
6
/**
7
 * Circles - Bring cloud-users closer together.
8
 *
9
 * This file is licensed under the Affero General Public License version 3 or
10
 * later. See the COPYING file.
11
 *
12
 * @author Maxence Lange <[email protected]>
13
 * @copyright 2021
14
 * @license GNU AGPL version 3 or any later version
15
 *
16
 * This program is free software: you can redistribute it and/or modify
17
 * it under the terms of the GNU Affero General Public License as
18
 * published by the Free Software Foundation, either version 3 of the
19
 * License, or (at your option) any later version.
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
27
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
28
 *
29
 */
30
31
32
namespace OCA\Circles\Command;
33
34
use daita\MySmallPhpTools\Exceptions\RequestContentException;
35
use daita\MySmallPhpTools\Exceptions\RequestNetworkException;
36
use daita\MySmallPhpTools\Exceptions\SignatoryException;
37
use daita\MySmallPhpTools\Exceptions\SignatureException;
38
use daita\MySmallPhpTools\Exceptions\WellKnownLinkNotFoundException;
39
use daita\MySmallPhpTools\Model\Nextcloud\nc21\NC21Request;
40
use daita\MySmallPhpTools\Model\Nextcloud\nc21\NC21SignedRequest;
41
use daita\MySmallPhpTools\Traits\Nextcloud\nc21\TNC21WellKnown;
42
use daita\MySmallPhpTools\Traits\TStringTools;
43
use Exception;
44
use OC\Core\Command\Base;
45
use OCA\Circles\AppInfo\Application;
46
use OCA\Circles\Db\RemoteRequest;
47
use OCA\Circles\Exceptions\RemoteNotFoundException;
48
use OCA\Circles\Exceptions\RemoteUidException;
49
use OCA\Circles\Model\Federated\RemoteInstance;
50
use OCA\Circles\Service\ConfigService;
51
use OCA\Circles\Service\GlobalScaleService;
52
use OCA\Circles\Service\RemoteStreamService;
53
use Symfony\Component\Console\Helper\Table;
54
use Symfony\Component\Console\Input\InputArgument;
55
use Symfony\Component\Console\Input\InputInterface;
56
use Symfony\Component\Console\Input\InputOption;
57
use Symfony\Component\Console\Output\ConsoleOutput;
58
use Symfony\Component\Console\Output\OutputInterface;
59
use Symfony\Component\Console\Question\ConfirmationQuestion;
60
61
62
/**
63
 * Class CirclesRemote
64
 *
65
 * @package OCA\Circles\Command
66
 */
67
class CirclesRemote extends Base {
68
69
70
	use TNC21WellKnown;
71
	use TStringTools;
72
73
74
	/** @var RemoteRequest */
75
	private $remoteRequest;
76
77
	/** @var GlobalScaleService */
78
	private $globalScaleService;
79
80
	/** @var RemoteStreamService */
81
	private $remoteStreamService;
82
83
	/** @var ConfigService */
84
	private $configService;
85
86
87
	/** @var InputInterface */
88
	private $input;
89
90
	/** @var OutputInterface */
91
	private $output;
92
93
94
	/**
95
	 * CirclesRemote constructor.
96
	 *
97
	 * @param RemoteRequest $remoteRequest
98
	 * @param GlobalScaleService $globalScaleService
99
	 * @param RemoteStreamService $remoteStreamService
100
	 * @param ConfigService $configService
101
	 */
102
	public function __construct(
103
		RemoteRequest $remoteRequest, GlobalScaleService $globalScaleService, RemoteStreamService $remoteStreamService,
104
		ConfigService $configService
105
	) {
106
		parent::__construct();
107
108
		$this->remoteRequest = $remoteRequest;
109
		$this->globalScaleService = $globalScaleService;
110
		$this->remoteStreamService = $remoteStreamService;
111
		$this->configService = $configService;
112
113
		$this->setup('app', 'circles');
114
	}
115
116
117
	/**
118
	 *
119
	 */
120
	protected function configure() {
121
		parent::configure();
122
		$this->setName('circles:remote')
123
			 ->setDescription('remote features')
124
			 ->addArgument('host', InputArgument::OPTIONAL, 'host of the remote instance of Nextcloud')
125
			 ->addOption('all', '', InputOption::VALUE_NONE, 'display all information');
126
	}
127
128
129
	/**
130
	 * @param InputInterface $input
131
	 * @param OutputInterface $output
132
	 *
133
	 * @return int
134
	 * @throws Exception
135
	 */
136
	protected function execute(InputInterface $input, OutputInterface $output): int {
137
		$host = $input->getArgument('host');
138
139
		$this->input = $input;
140
		$this->output = $output;
141
142
		if ($host) {
143
			$this->requestInstance($host);
144
		} else {
145
			$this->checkKnownInstance();
146
		}
147
148
		return 0;
149
	}
150
151
152
	/**
153
	 * @param string $host
154
	 *
155
	 * @throws RemoteUidException
156
	 * @throws RequestNetworkException
157
	 * @throws SignatoryException
158
	 * @throws SignatureException
159
	 * @throws RequestContentException
160
	 * @throws WellKnownLinkNotFoundException
161
	 */
162
	private function requestInstance(string $host): void {
163
		$webfinger = $this->getWebfinger($host, Application::APP_SUBJECT);
164 View Code Duplication
		if ($this->input->getOption('all')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
165
			$this->output->writeln('- Webfinger on <info>' . $host . '</info>');
166
			$this->output->writeln(json_encode($webfinger, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
167
			$this->output->writeln('');
168
		}
169
170 View Code Duplication
		if ($this->input->getOption('all')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
171
			$circleLink = $this->extractLink(Application::APP_REL, $webfinger);
172
			$this->output->writeln('- Information about Circles app on <info>' . $host . '</info>');
173
			$this->output->writeln(json_encode($circleLink, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
174
			$this->output->writeln('');
175
		}
176
177
		$this->output->writeln('- Available services on <info>' . $host . '</info>');
178
		foreach ($webfinger->getLinks() as $link) {
179
			$app = $link->getProperty('name');
180
			$ver = $link->getProperty('version');
181
			if ($app !== '') {
182
				$app .= ' ';
183
			}
184
			if ($ver !== '') {
185
				$ver = 'v' . $ver;
186
			}
187
188
			$this->output->writeln(' * ' . $link->getRel() . ' ' . $app . $ver);
189
		}
190
		$this->output->writeln('');
191
192
		$this->output->writeln('- Resources related to Circles on <info>' . $host . '</info>');
193
		$resource = $this->getResourceData($host, Application::APP_SUBJECT, Application::APP_REL);
194
		$this->output->writeln(json_encode($resource, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
195
		$this->output->writeln('');
196
197
198
		$tempUid = $resource->g('uid');
199
		$this->output->writeln(
200
			'- Confirming UID=' . $tempUid . ' from parsed Signatory at <info>' . $host . '</info>'
201
		);
202
203
		try {
204
			$remoteSignatory = $this->remoteStreamService->retrieveSignatory($resource->g('id'), true);
205
			$this->output->writeln(' * No SignatureException: <info>Identity authed</info>');
206
		} catch (SignatureException $e) {
207
			$this->output->writeln(
208
				'<error>' . $host . ' cannot auth its identity: ' . $e->getMessage() . '</error>'
209
			);
210
211
			return;
212
		}
213
214
		$this->output->writeln(' * Found <info>' . $remoteSignatory->getUid() . '</info>');
215
		if ($remoteSignatory->getUid(true) !== $tempUid) {
216
			$this->output->writeln('<error>looks like ' . $host . ' is faking its identity');
217
218
			return;
219
		}
220
221
		$this->output->writeln('');
222
223
		$testUrl = $resource->g('test');
224
		$this->output->writeln('- Testing signed payload on <info>' . $testUrl . '</info>');
225
226
		try {
227
			$localSignatory = $this->remoteStreamService->getAppSignatory();
228
		} catch (SignatoryException $e) {
229
			$this->output->writeln(
230
				'<error>Federated Circles not enabled locally. Please run ./occ circles:remote:init</error>'
231
			);
232
233
			return;
234
		}
235
236
		$payload = [
237
			'test'  => 42,
238
			'token' => $this->uuid()
239
		];
240
		$signedRequest = $this->outgoingTest($testUrl, $payload);
241
		$this->output->writeln(' * Payload: ');
242
		$this->output->writeln(json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
243
		$this->output->writeln('');
244
245
		$this->output->writeln(' * Clear Signature: ');
246
		$this->output->writeln('<comment>' . $signedRequest->getClearSignature() . '</comment>');
247
		$this->output->writeln('');
248
249
		$this->output->writeln(' * Signed Signature (base64 encoded): ');
250
		$this->output->writeln(
251
			'<comment>' . base64_encode($signedRequest->getSignedSignature()) . '</comment>'
252
		);
253
		$this->output->writeln('');
254
255
		$result = $signedRequest->getOutgoingRequest()->getResult();
256
		$code = $result->getStatusCode();
257
		$this->output->writeln(' * Result: ' . (($code === 200) ? '<info>' . $code . '</info>' : $code));
258
		$this->output->writeln(
259
			json_encode(json_decode($result->getContent(), true), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
260
		);
261
		$this->output->writeln('');
262
263 View Code Duplication
		if ($this->input->getOption('all')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
264
			$this->output->writeln('');
265
			$this->output->writeln('<info>### Complete report ###</info>');
266
			$this->output->writeln(json_encode($signedRequest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
267
			$this->output->writeln('');
268
		}
269
270
		if ($remoteSignatory->getUid() !== $localSignatory->getUid()) {
271
			$remoteSignatory->setInstance($host);
272
			try {
273
				$stored = new RemoteInstance();
274
				$this->remoteStreamService->confirmValidRemote($remoteSignatory, $stored);
275
				$this->output->writeln(
276
					'<info>The remote instance ' . $host
277
					. ' is already known with this current identity</info>'
278
				);
279
280 View Code Duplication
				if ($remoteSignatory->getInstance() !== $stored->getInstance()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
281
					$this->output->writeln(
282
						'- updating host from ' . $stored->getInstance() . ' to '
283
						. $remoteSignatory->getInstance()
284
					);
285
					$this->remoteStreamService->update($remoteSignatory, RemoteStreamService::UPDATE_INSTANCE);
286
				}
287 View Code Duplication
				if ($remoteSignatory->getId() !== $stored->getId()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
288
					$this->output->writeln(
289
						'- updating href/Id from ' . $stored->getId() . ' to '
290
						. $remoteSignatory->getId()
291
					);
292
					$this->remoteStreamService->update($remoteSignatory, RemoteStreamService::UPDATE_HREF);
293
				}
294
295
			} catch (RemoteUidException $e) {
296
				$this->updateRemote($remoteSignatory);
297
			} catch (RemoteNotFoundException $e) {
298
				$this->saveRemote($remoteSignatory);
299
			}
300
		}
301
302
	}
303
304
305
	/**
306
	 * @param RemoteInstance $remoteSignatory
307
	 *
308
	 * @throws RemoteUidException
309
	 */
310 View Code Duplication
	private function saveRemote(RemoteInstance $remoteSignatory) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
311
		$this->output->writeln('');
312
		$helper = $this->getHelper('question');
313
314
		$this->output->writeln(
315
			'The remote instance <info>' . $remoteSignatory->getInstance() . '</info> looks good.'
316
		);
317
		$question = new ConfirmationQuestion(
318
			'Would you like to allow the sharing of your circles with this remote instance ? (y/N) ',
319
			false,
320
			'/^(y|Y)/i'
321
		);
322
323
		if ($helper->ask($this->input, $this->output, $question)) {
324
			$this->remoteRequest->save($remoteSignatory);
325
			$this->output->writeln('<info>remote instance saved</info>');
326
		}
327
	}
328
329
330
	/**
331
	 * @param RemoteInstance $remoteSignatory
332
	 *
333
	 * @throws RemoteUidException
334
	 */
335 View Code Duplication
	private function updateRemote(RemoteInstance $remoteSignatory): void {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
336
		$this->output->writeln('');
337
		$helper = $this->getHelper('question');
338
339
		$this->output->writeln(
340
			'The remote instance <info>' . $remoteSignatory->getInstance()
341
			. '</info> is known but <error>its identity has changed.</error>'
342
		);
343
		$this->output->writeln(
344
			'<comment>If you are not sure on why identity changed, please say No to the next question and contact the admin of the remote instance</comment>'
345
		);
346
		$question = new ConfirmationQuestion(
347
			'Do you consider this new identity as valid and update the entry in the database? (y/N) ',
348
			false,
349
			'/^(y|Y)/i'
350
		);
351
352
		if ($helper->ask($this->input, $this->output, $question)) {
353
			$this->remoteStreamService->update($remoteSignatory);
354
			$this->output->writeln('remote instance updated');
355
		}
356
	}
357
358
359
	/**
360
	 * @param string $remote
361
	 * @param array $payload
362
	 *
363
	 * @return NC21SignedRequest
364
	 * @throws RequestNetworkException
365
	 * @throws SignatoryException
366
	 */
367
	private function outgoingTest(string $remote, array $payload): NC21SignedRequest {
368
		$request = new NC21Request();
369
		$request->basedOnUrl($remote);
370
		$request->setFollowLocation(true);
371
		$request->setLocalAddressAllowed(true);
372
		$request->setTimeout(5);
373
		$request->setData($payload);
374
375
		$app = $this->remoteStreamService->getAppSignatory();
376
		$signedRequest = $this->remoteStreamService->signOutgoingRequest($request, $app);
377
		$this->doRequest($signedRequest->getOutgoingRequest());
378
379
		return $signedRequest;
380
	}
381
382
383
	/**
384
	 *
385
	 */
386
	private function checkKnownInstance(): void {
387
		$this->verifyGSInstances();
388
		$this->checkRemoteInstances();
389
	}
390
391
392
	/**
393
	 *
394
	 */
395
	private function verifyGSInstances(): void {
396
		$instances = $this->globalScaleService->getGlobalScaleInstances();
397
		$known = array_map(
398
			function(RemoteInstance $instance): string {
399
				return $instance->getInstance();
400
			}, $this->remoteRequest->getFromType(RemoteInstance::TYPE_GLOBAL_SCALE)
401
		);
402
403
		$missing = array_diff($instances, $known);
404
		foreach ($missing as $instance) {
405
			$this->syncGSInstance($instance);
406
		}
407
	}
408
409
410
	/**
411
	 * @param string $instance
412
	 */
413
	private function syncGSInstance(string $instance): void {
414
		if ($this->configService->isLocalInstance($instance)) {
415
			return;
416
		}
417
		$this->output->write('Adding <comment>' . $instance . '</comment>: ');
418
		try {
419
			$this->remoteStreamService->addRemoteInstance($instance, RemoteInstance::TYPE_GLOBAL_SCALE, true);
420
			$this->output->writeln('<info>ok</info>');
421
		} catch (Exception $e) {
422
			$msg = ($e->getMessage() === '') ? '' : ' (' . $e->getMessage() . ')';
423
			$this->output->writeln('<error>' . get_class($e) . $msg . '</error>');
424
		}
425
	}
426
427
428
	private function checkRemoteInstances(): void {
429
		$instances = $this->remoteRequest->getAllInstances();
430
431
		$output = new ConsoleOutput();
432
		$output = $output->section();
433
		$table = new Table($output);
434
		$table->setHeaders(['instance', 'type', 'UID', 'Authed']);
435
		$table->render();
436
437
		foreach ($instances as $instance) {
438
			try {
439
				$current = $this->remoteStreamService->retrieveRemoteInstance($instance->getInstance());
440
				if ($current->getUid(true) === $instance->getUid(true)) {
441
					$currentUid = '<info>' . $current->getUid(true) . '</info>';
442
				} else {
443
					$currentUid = '<error>' . $current->getUid(true) . '</error>';
444
				}
445
			} catch (Exception $e) {
446
				$currentUid = '<error>' . $e->getMessage() . '</error>';
447
			}
448
449
			$table->appendRow(
450
				[
451
					$instance->getInstance(),
452
					$instance->getType(),
453
					$instance->getUid(),
454
					$currentUid
455
				]
456
			);
457
		}
458
	}
459
460
}
461
462