Completed
Push — master ( a1bada...5f4a81 )
by Julius
14s queued 10s
created

FederationService::isTrustedRemote()   B

Complexity

Conditions 11
Paths 18

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 0
cts 30
cp 0
rs 7.3166
c 0
b 0
f 0
cc 11
nc 18
nop 1
crap 132

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2019 Julius Härtl <[email protected]>
4
 *
5
 * @author Julius Härtl <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 * This program is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License as
11
 * published by the Free Software Foundation, either version 3 of the
12
 * License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License
20
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OCA\Richdocuments\Service;
25
26
27
use OCA\Federation\TrustedServers;
28
use OCA\Files_Sharing\External\Storage as SharingExternalStorage;
29
use OCA\Richdocuments\TokenManager;
30
use OCP\AppFramework\Http\RedirectResponse;
31
use OCP\AppFramework\QueryException;
32
use OCP\Files\File;
33
use OCP\Files\InvalidPathException;
34
use OCP\Files\NotFoundException;
35
use OCP\Http\Client\IClientService;
36
use OCP\ICache;
37
use OCP\ICacheFactory;
38
use OCP\IConfig;
39
use OCP\ILogger;
40
41
class FederationService {
42
43
	/** @var ICache */
44
	private $cache;
45
	/** @var IClientService */
46
	private $clientService;
47
	/** @var ILogger  */
48
	private $logger;
49
	/** @var TrustedServers */
50
	private $trustedServers;
51
	/** @var IConfig */
52
	private $config;
53
	/** @var TokenManager */
54
	private $tokenManager;
55
56
	public function __construct(ICacheFactory $cacheFactory, IClientService $clientService, ILogger $logger, TokenManager $tokenManager, IConfig $config) {
57
		$this->cache = $cacheFactory->createLocal('richdocuments_remote/');
58
		$this->clientService = $clientService;
59
		$this->logger = $logger;
60
		$this->tokenManager = $tokenManager;
61
		$this->config = $config;
62
		try {
63
			$this->trustedServers = \OC::$server->query( \OCA\Federation\TrustedServers::class);
64
		} catch (QueryException $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
65
	}
66
67
	/**
68
	 * @param $remote
69
	 * @return string
70
	 * @throws \Exception
71
	 */
72
	public function getRemoteCollaboraURL($remote) {
73
		if (!$this->isTrustedRemote($remote)) {
74
			throw new \Exception('Unable to determine collabora URL of remote server ' . $remote . ' - Remote is not a trusted server');
75
		}
76
		if ($remoteCollabora = $this->cache->get('richdocuments_remote/' . $remote)) {
77
			return $remoteCollabora;
78
		}
79
		try {
80
			$client = $this->clientService->newClient();
81
			$response = $client->get($remote . '/ocs/v2.php/apps/richdocuments/api/v1/federation?format=json', ['timeout' => 5]);
82
			$data = \json_decode($response->getBody(), true);
83
			$remoteCollabora = $data['ocs']['data']['wopi_url'];
84
			$this->cache->set('richdocuments_remote/' . $remote, $remoteCollabora, 3600);
85
			return $remoteCollabora;
86
		} catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
87
			$this->logger->info('Unable to determine collabora URL of remote server ' . $remote);
88
			$this->cache->set('richdocuments_remote/' . $remote, '', 300);
89
		}
90
		return '';
91
	}
92
93
	public function isTrustedRemote($domainWithPort) {
94
		if (strpos($domainWithPort, 'http://') === 0 || strpos($domainWithPort, 'https://') === 0) {
95
			$port = parse_url($domainWithPort, PHP_URL_PORT);
96
			$domainWithPort = parse_url($domainWithPort, PHP_URL_HOST) . ($port ? ':' . $port : '');
97
		}
98
99
		if ($this->trustedServers !== null && $this->trustedServers->isTrustedServer($domainWithPort)) {
100
			return true;
101
		}
102
103
		$domain = $this->getDomainWithoutPort($domainWithPort);
104
105
		$trustedList = $this->config->getSystemValue('gs.trustedHosts', []);
106
		if (!is_array($trustedList)) {
107
			return false;
108
		}
109
110
		foreach ($trustedList as $trusted) {
111
			if (!is_string($trusted)) {
112
				break;
113
			}
114
			$regex = '/^' . implode('[-\.a-zA-Z0-9]*', array_map(function ($v) {
115
					return preg_quote($v, '/');
116
				}, explode('*', $trusted))) . '$/i';
117
			if (preg_match($regex, $domain) || preg_match($regex, $domainWithPort)) {
118
				return true;
119
			}
120
		}
121
122
		return false;
123
	}
124
125
	/**
126
	 * Strips a potential port from a domain (in format domain:port)
127
	 * @param string $host
128
	 * @return string $host without appended port
129
	 */
130
	private function getDomainWithoutPort($host) {
131
		$pos = strrpos($host, ':');
132
		if ($pos !== false) {
133
			$port = substr($host, $pos + 1);
134
			if (is_numeric($port)) {
135
				$host = substr($host, 0, $pos);
136
			}
137
		}
138
		return $host;
139
	}
140
141
	public function getRemoteDirectUrl($remote, $shareToken, $filePath) {
142
		if ($this->getRemoteCollaboraURL() === '') {
0 ignored issues
show
Bug introduced by
The call to getRemoteCollaboraURL() misses a required argument $remote.

This check looks for function calls that miss required arguments.

Loading history...
143
			return '';
144
		}
145
		try {
146
			$client = $this->clientService->newClient();
147
			$response = $client->post($remote . '/ocs/v2.php/apps/richdocuments/api/v1/federation/direct?format=json', [
148
				'timeout' => 5,
149
				'body' => [
150
					'shareToken' => $shareToken,
151
					'filePath' => $filePath
152
				]
153
			]);
154
			$data = \json_decode($response->getBody(), true);
155
			return $data['ocs']['data'];
156
		} catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
157
			$this->logger->info('Unable to determine collabora URL of remote server ' . $remote);
158
		}
159
		return null;
160
	}
161
162
	public function getRemoteFileDetails($remote, $remoteToken) {
163
		if (!$this->isTrustedRemote($remote)) {
164
			$this->logger->info('Unable to determine collabora URL of remote server ' . $remote . ' - Remote is not a trusted server');
165
			return null;
166
		}
167
		try {
168
			$client = $this->clientService->newClient();
169
			$response = $client->post($remote . '/ocs/v2.php/apps/richdocuments/api/v1/federation?format=json', [
170
				'timeout' => 5,
171
				'body' => [
172
					'token' => $remoteToken
173
				]
174
			]);
175
			$data = \json_decode($response->getBody(), true);
176
			return $data['ocs']['data'];
177
		} catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
178
			$this->logger->info('Unable to determine collabora URL of remote server ' . $remote);
179
		}
180
		return null;
181
	}
182
183
	/**
184
	 * @param File $item
185
	 * @return string|null
186
	 * @throws NotFoundException
187
	 * @throws InvalidPathException
188
	 */
189
	public function getRemoteRedirectURL(File $item, $direct = null) {
190
		if ($item->getStorage()->instanceOfStorage(SharingExternalStorage::class)) {
191
			$remote = $item->getStorage()->getRemote();
0 ignored issues
show
Bug introduced by
The method getRemote() does not seem to exist on object<OCP\Files\Storage>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
192
			$remoteCollabora = $this->getRemoteCollaboraURL($remote);
193
			if ($remoteCollabora !== '') {
194
				if ($direct === null) {
195
					$wopi = $this->tokenManager->getRemoteToken($item);
196
				} else {
197
					$wopi = $this->tokenManager->getRemoteTokenFromDirect($item, $direct->getUid());
198
				}
199
				$url = $remote . 'index.php/apps/richdocuments/remote?shareToken=' . $item->getStorage()->getToken() .
0 ignored issues
show
Bug introduced by
The method getToken() does not seem to exist on object<OCP\Files\Storage>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
200
					'&remoteServer=' . $wopi->getServerHost() .
201
					'&remoteServerToken=' . $wopi->getToken();
202
				if ($item->getInternalPath() !== '') {
203
					$url .= '&filePath=' . $item->getInternalPath();
204
				}
205
				return $url;
206
			}
207
			throw new NotFoundException('Failed to connect to remote collabora instance for ' . $item->getId());
208
		}
209
		return null;
210
	}
211
}
212