Completed
Push — master ( cf0b70...b4302f )
by
unknown
21:27 queued 15s
created
apps/federation/lib/TrustedServers.php 2 patches
Indentation   +184 added lines, -184 removed lines patch added patch discarded remove patch
@@ -22,188 +22,188 @@
 block discarded – undo
22 22
 
23 23
 class TrustedServers {
24 24
 
25
-	/** after a user list was exchanged at least once successfully */
26
-	public const STATUS_OK = 1;
27
-	/** waiting for shared secret or initial user list exchange */
28
-	public const STATUS_PENDING = 2;
29
-	/** something went wrong, misconfigured server, software bug,... user interaction needed */
30
-	public const STATUS_FAILURE = 3;
31
-	/** remote server revoked access */
32
-	public const STATUS_ACCESS_REVOKED = 4;
33
-
34
-	/** @var list<array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}>|null */
35
-	private ?array $trustedServersCache = null;
36
-
37
-	public function __construct(
38
-		private DbHandler $dbHandler,
39
-		private IClientService $httpClientService,
40
-		private LoggerInterface $logger,
41
-		private IJobList $jobList,
42
-		private ISecureRandom $secureRandom,
43
-		private IConfig $config,
44
-		private IEventDispatcher $dispatcher,
45
-		private ITimeFactory $timeFactory,
46
-	) {
47
-	}
48
-
49
-	/**
50
-	 * Add server to the list of trusted servers
51
-	 */
52
-	public function addServer(string $url): int {
53
-		$url = $this->updateProtocol($url);
54
-		$result = $this->dbHandler->addServer($url);
55
-		if ($result) {
56
-			$token = $this->secureRandom->generate(16);
57
-			$this->dbHandler->addToken($url, $token);
58
-			$this->jobList->add(
59
-				RequestSharedSecret::class,
60
-				[
61
-					'url' => $url,
62
-					'token' => $token,
63
-					'created' => $this->timeFactory->getTime()
64
-				]
65
-			);
66
-		}
67
-
68
-		return $result;
69
-	}
70
-
71
-	/**
72
-	 * Get shared secret for the given server
73
-	 */
74
-	public function getSharedSecret(string $url): string {
75
-		return $this->dbHandler->getSharedSecret($url);
76
-	}
77
-
78
-	/**
79
-	 * Add shared secret for the given server
80
-	 */
81
-	public function addSharedSecret(string $url, string $sharedSecret): void {
82
-		$this->dbHandler->addSharedSecret($url, $sharedSecret);
83
-	}
84
-
85
-	/**
86
-	 * Remove server from the list of trusted servers
87
-	 */
88
-	public function removeServer(int $id): void {
89
-		$server = $this->dbHandler->getServerById($id);
90
-		$this->dbHandler->removeServer($id);
91
-		$this->dispatcher->dispatchTyped(new TrustedServerRemovedEvent($server['url_hash']));
92
-
93
-	}
94
-
95
-	/**
96
-	 * Get all trusted servers
97
-	 *
98
-	 * @return list<array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}>
99
-	 * @throws \Exception
100
-	 */
101
-	public function getServers(): ?array {
102
-		if ($this->trustedServersCache === null) {
103
-			$this->trustedServersCache = $this->dbHandler->getAllServer();
104
-		}
105
-		return $this->trustedServersCache;
106
-	}
107
-
108
-	/**
109
-	 * Get a trusted server
110
-	 *
111
-	 * @return array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}
112
-	 * @throws Exception
113
-	 */
114
-	public function getServer(int $id): ?array {
115
-		if ($this->trustedServersCache === null) {
116
-			$this->trustedServersCache = $this->dbHandler->getAllServer();
117
-		}
118
-
119
-		foreach ($this->trustedServersCache as $server) {
120
-			if ($server['id'] === $id) {
121
-				return $server;
122
-			}
123
-		}
124
-
125
-		throw new \Exception('No server found with ID: ' . $id);
126
-	}
127
-
128
-	/**
129
-	 * Check if given server is a trusted Nextcloud server
130
-	 */
131
-	public function isTrustedServer(string $url): bool {
132
-		return $this->dbHandler->serverExists($url);
133
-	}
134
-
135
-	/**
136
-	 * Set server status
137
-	 */
138
-	public function setServerStatus(string $url, int $status): void {
139
-		$this->dbHandler->setServerStatus($url, $status);
140
-	}
141
-
142
-	/**
143
-	 * Get server status
144
-	 */
145
-	public function getServerStatus(string $url): int {
146
-		return $this->dbHandler->getServerStatus($url);
147
-	}
148
-
149
-	/**
150
-	 * Check if URL point to a ownCloud/Nextcloud server
151
-	 */
152
-	public function isNextcloudServer(string $url): bool {
153
-		$isValidNextcloud = false;
154
-		$client = $this->httpClientService->newClient();
155
-		try {
156
-			$result = $client->get(
157
-				$url . '/status.php',
158
-				[
159
-					'timeout' => 3,
160
-					'connect_timeout' => 3,
161
-					'verify' => !$this->config->getSystemValue('sharing.federation.allowSelfSignedCertificates', false),
162
-				]
163
-			);
164
-			if ($result->getStatusCode() === Http::STATUS_OK) {
165
-				$body = $result->getBody();
166
-				if (is_resource($body)) {
167
-					$body = stream_get_contents($body) ?: '';
168
-				}
169
-				$isValidNextcloud = $this->checkNextcloudVersion($body);
170
-			}
171
-		} catch (\Exception $e) {
172
-			$this->logger->error('No Nextcloud server.', [
173
-				'exception' => $e,
174
-			]);
175
-			return false;
176
-		}
177
-
178
-		return $isValidNextcloud;
179
-	}
180
-
181
-	/**
182
-	 * Check if ownCloud/Nextcloud version is >= 9.0
183
-	 * @throws HintException
184
-	 */
185
-	protected function checkNextcloudVersion(string $status): bool {
186
-		$decoded = json_decode($status, true);
187
-		if (!empty($decoded) && isset($decoded['version'])) {
188
-			if (!version_compare($decoded['version'], '9.0.0', '>=')) {
189
-				throw new HintException('Remote server version is too low. 9.0 is required.');
190
-			}
191
-			return true;
192
-		}
193
-		return false;
194
-	}
195
-
196
-	/**
197
-	 * Check if the URL contain a protocol, if not add https
198
-	 */
199
-	protected function updateProtocol(string $url): string {
200
-		if (
201
-			strpos($url, 'https://') === 0
202
-			|| strpos($url, 'http://') === 0
203
-		) {
204
-			return $url;
205
-		}
206
-
207
-		return 'https://' . $url;
208
-	}
25
+    /** after a user list was exchanged at least once successfully */
26
+    public const STATUS_OK = 1;
27
+    /** waiting for shared secret or initial user list exchange */
28
+    public const STATUS_PENDING = 2;
29
+    /** something went wrong, misconfigured server, software bug,... user interaction needed */
30
+    public const STATUS_FAILURE = 3;
31
+    /** remote server revoked access */
32
+    public const STATUS_ACCESS_REVOKED = 4;
33
+
34
+    /** @var list<array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}>|null */
35
+    private ?array $trustedServersCache = null;
36
+
37
+    public function __construct(
38
+        private DbHandler $dbHandler,
39
+        private IClientService $httpClientService,
40
+        private LoggerInterface $logger,
41
+        private IJobList $jobList,
42
+        private ISecureRandom $secureRandom,
43
+        private IConfig $config,
44
+        private IEventDispatcher $dispatcher,
45
+        private ITimeFactory $timeFactory,
46
+    ) {
47
+    }
48
+
49
+    /**
50
+     * Add server to the list of trusted servers
51
+     */
52
+    public function addServer(string $url): int {
53
+        $url = $this->updateProtocol($url);
54
+        $result = $this->dbHandler->addServer($url);
55
+        if ($result) {
56
+            $token = $this->secureRandom->generate(16);
57
+            $this->dbHandler->addToken($url, $token);
58
+            $this->jobList->add(
59
+                RequestSharedSecret::class,
60
+                [
61
+                    'url' => $url,
62
+                    'token' => $token,
63
+                    'created' => $this->timeFactory->getTime()
64
+                ]
65
+            );
66
+        }
67
+
68
+        return $result;
69
+    }
70
+
71
+    /**
72
+     * Get shared secret for the given server
73
+     */
74
+    public function getSharedSecret(string $url): string {
75
+        return $this->dbHandler->getSharedSecret($url);
76
+    }
77
+
78
+    /**
79
+     * Add shared secret for the given server
80
+     */
81
+    public function addSharedSecret(string $url, string $sharedSecret): void {
82
+        $this->dbHandler->addSharedSecret($url, $sharedSecret);
83
+    }
84
+
85
+    /**
86
+     * Remove server from the list of trusted servers
87
+     */
88
+    public function removeServer(int $id): void {
89
+        $server = $this->dbHandler->getServerById($id);
90
+        $this->dbHandler->removeServer($id);
91
+        $this->dispatcher->dispatchTyped(new TrustedServerRemovedEvent($server['url_hash']));
92
+
93
+    }
94
+
95
+    /**
96
+     * Get all trusted servers
97
+     *
98
+     * @return list<array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}>
99
+     * @throws \Exception
100
+     */
101
+    public function getServers(): ?array {
102
+        if ($this->trustedServersCache === null) {
103
+            $this->trustedServersCache = $this->dbHandler->getAllServer();
104
+        }
105
+        return $this->trustedServersCache;
106
+    }
107
+
108
+    /**
109
+     * Get a trusted server
110
+     *
111
+     * @return array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}
112
+     * @throws Exception
113
+     */
114
+    public function getServer(int $id): ?array {
115
+        if ($this->trustedServersCache === null) {
116
+            $this->trustedServersCache = $this->dbHandler->getAllServer();
117
+        }
118
+
119
+        foreach ($this->trustedServersCache as $server) {
120
+            if ($server['id'] === $id) {
121
+                return $server;
122
+            }
123
+        }
124
+
125
+        throw new \Exception('No server found with ID: ' . $id);
126
+    }
127
+
128
+    /**
129
+     * Check if given server is a trusted Nextcloud server
130
+     */
131
+    public function isTrustedServer(string $url): bool {
132
+        return $this->dbHandler->serverExists($url);
133
+    }
134
+
135
+    /**
136
+     * Set server status
137
+     */
138
+    public function setServerStatus(string $url, int $status): void {
139
+        $this->dbHandler->setServerStatus($url, $status);
140
+    }
141
+
142
+    /**
143
+     * Get server status
144
+     */
145
+    public function getServerStatus(string $url): int {
146
+        return $this->dbHandler->getServerStatus($url);
147
+    }
148
+
149
+    /**
150
+     * Check if URL point to a ownCloud/Nextcloud server
151
+     */
152
+    public function isNextcloudServer(string $url): bool {
153
+        $isValidNextcloud = false;
154
+        $client = $this->httpClientService->newClient();
155
+        try {
156
+            $result = $client->get(
157
+                $url . '/status.php',
158
+                [
159
+                    'timeout' => 3,
160
+                    'connect_timeout' => 3,
161
+                    'verify' => !$this->config->getSystemValue('sharing.federation.allowSelfSignedCertificates', false),
162
+                ]
163
+            );
164
+            if ($result->getStatusCode() === Http::STATUS_OK) {
165
+                $body = $result->getBody();
166
+                if (is_resource($body)) {
167
+                    $body = stream_get_contents($body) ?: '';
168
+                }
169
+                $isValidNextcloud = $this->checkNextcloudVersion($body);
170
+            }
171
+        } catch (\Exception $e) {
172
+            $this->logger->error('No Nextcloud server.', [
173
+                'exception' => $e,
174
+            ]);
175
+            return false;
176
+        }
177
+
178
+        return $isValidNextcloud;
179
+    }
180
+
181
+    /**
182
+     * Check if ownCloud/Nextcloud version is >= 9.0
183
+     * @throws HintException
184
+     */
185
+    protected function checkNextcloudVersion(string $status): bool {
186
+        $decoded = json_decode($status, true);
187
+        if (!empty($decoded) && isset($decoded['version'])) {
188
+            if (!version_compare($decoded['version'], '9.0.0', '>=')) {
189
+                throw new HintException('Remote server version is too low. 9.0 is required.');
190
+            }
191
+            return true;
192
+        }
193
+        return false;
194
+    }
195
+
196
+    /**
197
+     * Check if the URL contain a protocol, if not add https
198
+     */
199
+    protected function updateProtocol(string $url): string {
200
+        if (
201
+            strpos($url, 'https://') === 0
202
+            || strpos($url, 'http://') === 0
203
+        ) {
204
+            return $url;
205
+        }
206
+
207
+        return 'https://' . $url;
208
+    }
209 209
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 			}
123 123
 		}
124 124
 
125
-		throw new \Exception('No server found with ID: ' . $id);
125
+		throw new \Exception('No server found with ID: '.$id);
126 126
 	}
127 127
 
128 128
 	/**
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 		$client = $this->httpClientService->newClient();
155 155
 		try {
156 156
 			$result = $client->get(
157
-				$url . '/status.php',
157
+				$url.'/status.php',
158 158
 				[
159 159
 					'timeout' => 3,
160 160
 					'connect_timeout' => 3,
@@ -204,6 +204,6 @@  discard block
 block discarded – undo
204 204
 			return $url;
205 205
 		}
206 206
 
207
-		return 'https://' . $url;
207
+		return 'https://'.$url;
208 208
 	}
209 209
 }
Please login to merge, or discard this patch.
apps/federation/tests/TrustedServersTest.php 2 patches
Indentation   +310 added lines, -310 removed lines patch added patch discarded remove patch
@@ -26,314 +26,314 @@
 block discarded – undo
26 26
 use Test\TestCase;
27 27
 
28 28
 class TrustedServersTest extends TestCase {
29
-	private TrustedServers $trustedServers;
30
-	private DbHandler&MockObject $dbHandler;
31
-	private IClientService&MockObject $httpClientService;
32
-	private IClient&MockObject $httpClient;
33
-	private IResponse&MockObject $response;
34
-	private LoggerInterface&MockObject $logger;
35
-	private IJobList&MockObject $jobList;
36
-	private ISecureRandom&MockObject $secureRandom;
37
-	private IConfig&MockObject $config;
38
-	private IEventDispatcher&MockObject $dispatcher;
39
-	private ITimeFactory&MockObject $timeFactory;
40
-
41
-	protected function setUp(): void {
42
-		parent::setUp();
43
-
44
-		$this->dbHandler = $this->createMock(DbHandler::class);
45
-		$this->dispatcher = $this->createMock(IEventDispatcher::class);
46
-		$this->httpClientService = $this->createMock(IClientService::class);
47
-		$this->httpClient = $this->createMock(IClient::class);
48
-		$this->response = $this->createMock(IResponse::class);
49
-		$this->logger = $this->createMock(LoggerInterface::class);
50
-		$this->jobList = $this->createMock(IJobList::class);
51
-		$this->secureRandom = $this->createMock(ISecureRandom::class);
52
-		$this->config = $this->createMock(IConfig::class);
53
-		$this->timeFactory = $this->createMock(ITimeFactory::class);
54
-
55
-		$this->trustedServers = new TrustedServers(
56
-			$this->dbHandler,
57
-			$this->httpClientService,
58
-			$this->logger,
59
-			$this->jobList,
60
-			$this->secureRandom,
61
-			$this->config,
62
-			$this->dispatcher,
63
-			$this->timeFactory
64
-		);
65
-	}
66
-
67
-	public function testAddServer(): void {
68
-		/** @var TrustedServers&MockObject $trustedServers */
69
-		$trustedServers = $this->getMockBuilder(TrustedServers::class)
70
-			->setConstructorArgs(
71
-				[
72
-					$this->dbHandler,
73
-					$this->httpClientService,
74
-					$this->logger,
75
-					$this->jobList,
76
-					$this->secureRandom,
77
-					$this->config,
78
-					$this->dispatcher,
79
-					$this->timeFactory
80
-				]
81
-			)
82
-			->onlyMethods(['updateProtocol'])
83
-			->getMock();
84
-		$trustedServers->expects($this->once())->method('updateProtocol')
85
-			->with('url')->willReturn('https://url');
86
-		$this->timeFactory->method('getTime')
87
-			->willReturn(1234567);
88
-		$this->dbHandler->expects($this->once())->method('addServer')->with('https://url')
89
-			->willReturn(1);
90
-
91
-		$this->secureRandom->expects($this->once())->method('generate')
92
-			->willReturn('token');
93
-		$this->dbHandler->expects($this->once())->method('addToken')->with('https://url', 'token');
94
-		$this->jobList->expects($this->once())->method('add')
95
-			->with(RequestSharedSecret::class,
96
-				['url' => 'https://url', 'token' => 'token', 'created' => 1234567]);
97
-
98
-		$this->assertSame(
99
-			1,
100
-			$trustedServers->addServer('url')
101
-		);
102
-	}
103
-
104
-	public function testAddSharedSecret(): void {
105
-		$this->dbHandler->expects($this->once())->method('addSharedSecret')
106
-			->with('url', 'secret');
107
-		$this->trustedServers->addSharedSecret('url', 'secret');
108
-	}
109
-
110
-	public function testGetSharedSecret(): void {
111
-		$this->dbHandler->expects($this->once())
112
-			->method('getSharedSecret')
113
-			->with('url')
114
-			->willReturn('secret');
115
-		$this->assertSame(
116
-			$this->trustedServers->getSharedSecret('url'),
117
-			'secret'
118
-		);
119
-	}
120
-
121
-	public function testRemoveServer(): void {
122
-		$id = 42;
123
-		$server = ['url_hash' => 'url_hash'];
124
-		$this->dbHandler->expects($this->once())->method('removeServer')->with($id);
125
-		$this->dbHandler->expects($this->once())->method('getServerById')->with($id)
126
-			->willReturn($server);
127
-		$this->dispatcher->expects($this->once())->method('dispatchTyped')
128
-			->willReturnCallback(
129
-				function ($event): void {
130
-					$this->assertSame(get_class($event), TrustedServerRemovedEvent::class);
131
-					/** @var \OCP\Federated\Events\TrustedServerRemovedEvent $event */
132
-					$this->assertSame('url_hash', $event->getUrlHash());
133
-				}
134
-			);
135
-		$this->trustedServers->removeServer($id);
136
-	}
137
-
138
-	public function testGetServers(): void {
139
-		$this->dbHandler->expects($this->once())->method('getAllServer')->willReturn(['servers']);
140
-
141
-		$this->assertEquals(
142
-			['servers'],
143
-			$this->trustedServers->getServers()
144
-		);
145
-	}
146
-
147
-	public static function dataTestGetServer() {
148
-		return [
149
-			[
150
-				15,
151
-				[
152
-					'id' => 15,
153
-					'otherData' => 'first server',
154
-				]
155
-			],
156
-			[
157
-				16,
158
-				[
159
-					'id' => 16,
160
-					'otherData' => 'second server',
161
-				]
162
-			],
163
-			[
164
-				42,
165
-				[
166
-					'id' => 42,
167
-					'otherData' => 'last server',
168
-				]
169
-			],
170
-			[
171
-				108,
172
-				null
173
-			],
174
-		];
175
-	}
176
-
177
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetServer')]
178
-	public function testGetServer(int $id, ?array $expectedServer): void {
179
-		$servers = [
180
-			[
181
-				'id' => 15,
182
-				'otherData' => 'first server',
183
-			],
184
-			[
185
-				'id' => 16,
186
-				'otherData' => 'second server',
187
-			],
188
-			[
189
-				'id' => 42,
190
-				'otherData' => 'last server',
191
-			],
192
-		];
193
-		$this->dbHandler->expects($this->once())->method('getAllServer')->willReturn($servers);
194
-
195
-		if ($expectedServer === null) {
196
-			$this->expectException(\Exception::class);
197
-			$this->expectExceptionMessage('No server found with ID: ' . $id);
198
-		}
199
-
200
-		$this->assertEquals(
201
-			$expectedServer,
202
-			$this->trustedServers->getServer($id)
203
-		);
204
-	}
205
-
206
-	public function testIsTrustedServer(): void {
207
-		$this->dbHandler->expects($this->once())
208
-			->method('serverExists')->with('url')
209
-			->willReturn(true);
210
-
211
-		$this->assertTrue(
212
-			$this->trustedServers->isTrustedServer('url')
213
-		);
214
-	}
215
-
216
-	public function testSetServerStatus(): void {
217
-		$this->dbHandler->expects($this->once())->method('setServerStatus')
218
-			->with('url', 1);
219
-		$this->trustedServers->setServerStatus('url', 1);
220
-	}
221
-
222
-	public function testGetServerStatus(): void {
223
-		$this->dbHandler->expects($this->once())->method('getServerStatus')
224
-			->with('url')->willReturn(1);
225
-		$this->assertSame(
226
-			$this->trustedServers->getServerStatus('url'),
227
-			1
228
-		);
229
-	}
230
-
231
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsNextcloudServer')]
232
-	public function testIsNextcloudServer(int $statusCode, bool $isValidNextcloudVersion, bool $expected): void {
233
-		$server = 'server1';
234
-
235
-		/** @var TrustedServers&MockObject $trustedServers */
236
-		$trustedServers = $this->getMockBuilder(TrustedServers::class)
237
-			->setConstructorArgs(
238
-				[
239
-					$this->dbHandler,
240
-					$this->httpClientService,
241
-					$this->logger,
242
-					$this->jobList,
243
-					$this->secureRandom,
244
-					$this->config,
245
-					$this->dispatcher,
246
-					$this->timeFactory
247
-				]
248
-			)
249
-			->onlyMethods(['checkNextcloudVersion'])
250
-			->getMock();
251
-
252
-		$this->httpClientService->expects($this->once())->method('newClient')
253
-			->willReturn($this->httpClient);
254
-
255
-		$this->httpClient->expects($this->once())->method('get')->with($server . '/status.php')
256
-			->willReturn($this->response);
257
-
258
-		$this->response->expects($this->once())->method('getStatusCode')
259
-			->willReturn($statusCode);
260
-
261
-		if ($statusCode === 200) {
262
-			$this->response->expects($this->once())->method('getBody')
263
-				->willReturn('');
264
-			$trustedServers->expects($this->once())->method('checkNextcloudVersion')
265
-				->willReturn($isValidNextcloudVersion);
266
-		} else {
267
-			$trustedServers->expects($this->never())->method('checkNextcloudVersion');
268
-		}
269
-
270
-		$this->assertSame($expected,
271
-			$trustedServers->isNextcloudServer($server)
272
-		);
273
-	}
274
-
275
-	public static function dataTestIsNextcloudServer(): array {
276
-		return [
277
-			[200, true, true],
278
-			[200, false, false],
279
-			[404, true, false],
280
-		];
281
-	}
282
-
283
-	public function testIsNextcloudServerFail(): void {
284
-		$server = 'server1';
285
-
286
-		$this->httpClientService->expects($this->once())
287
-			->method('newClient')
288
-			->willReturn($this->httpClient);
289
-
290
-		$this->httpClient->expects($this->once())
291
-			->method('get')
292
-			->with($server . '/status.php')
293
-			->willThrowException(new \Exception('simulated exception'));
294
-
295
-		$this->assertFalse($this->trustedServers->isNextcloudServer($server));
296
-	}
297
-
298
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataTestCheckNextcloudVersion')]
299
-	public function testCheckNextcloudVersion(string $status): void {
300
-		$this->assertTrue(self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status]));
301
-	}
302
-
303
-	public static function dataTestCheckNextcloudVersion(): array {
304
-		return [
305
-			['{"version":"9.0.0"}'],
306
-			['{"version":"9.1.0"}']
307
-		];
308
-	}
309
-
310
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataTestCheckNextcloudVersionTooLow')]
311
-	public function testCheckNextcloudVersionTooLow(string $status): void {
312
-		$this->expectException(HintException::class);
313
-		$this->expectExceptionMessage('Remote server version is too low. 9.0 is required.');
314
-
315
-		self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status]);
316
-	}
317
-
318
-	public static function dataTestCheckNextcloudVersionTooLow(): array {
319
-		return [
320
-			['{"version":"8.2.3"}'],
321
-		];
322
-	}
323
-
324
-	#[\PHPUnit\Framework\Attributes\DataProvider('dataTestUpdateProtocol')]
325
-	public function testUpdateProtocol(string $url, string $expected): void {
326
-		$this->assertSame($expected,
327
-			self::invokePrivate($this->trustedServers, 'updateProtocol', [$url])
328
-		);
329
-	}
330
-
331
-	public static function dataTestUpdateProtocol(): array {
332
-		return [
333
-			['http://owncloud.org', 'http://owncloud.org'],
334
-			['https://owncloud.org', 'https://owncloud.org'],
335
-			['owncloud.org', 'https://owncloud.org'],
336
-			['httpserver', 'https://httpserver'],
337
-		];
338
-	}
29
+    private TrustedServers $trustedServers;
30
+    private DbHandler&MockObject $dbHandler;
31
+    private IClientService&MockObject $httpClientService;
32
+    private IClient&MockObject $httpClient;
33
+    private IResponse&MockObject $response;
34
+    private LoggerInterface&MockObject $logger;
35
+    private IJobList&MockObject $jobList;
36
+    private ISecureRandom&MockObject $secureRandom;
37
+    private IConfig&MockObject $config;
38
+    private IEventDispatcher&MockObject $dispatcher;
39
+    private ITimeFactory&MockObject $timeFactory;
40
+
41
+    protected function setUp(): void {
42
+        parent::setUp();
43
+
44
+        $this->dbHandler = $this->createMock(DbHandler::class);
45
+        $this->dispatcher = $this->createMock(IEventDispatcher::class);
46
+        $this->httpClientService = $this->createMock(IClientService::class);
47
+        $this->httpClient = $this->createMock(IClient::class);
48
+        $this->response = $this->createMock(IResponse::class);
49
+        $this->logger = $this->createMock(LoggerInterface::class);
50
+        $this->jobList = $this->createMock(IJobList::class);
51
+        $this->secureRandom = $this->createMock(ISecureRandom::class);
52
+        $this->config = $this->createMock(IConfig::class);
53
+        $this->timeFactory = $this->createMock(ITimeFactory::class);
54
+
55
+        $this->trustedServers = new TrustedServers(
56
+            $this->dbHandler,
57
+            $this->httpClientService,
58
+            $this->logger,
59
+            $this->jobList,
60
+            $this->secureRandom,
61
+            $this->config,
62
+            $this->dispatcher,
63
+            $this->timeFactory
64
+        );
65
+    }
66
+
67
+    public function testAddServer(): void {
68
+        /** @var TrustedServers&MockObject $trustedServers */
69
+        $trustedServers = $this->getMockBuilder(TrustedServers::class)
70
+            ->setConstructorArgs(
71
+                [
72
+                    $this->dbHandler,
73
+                    $this->httpClientService,
74
+                    $this->logger,
75
+                    $this->jobList,
76
+                    $this->secureRandom,
77
+                    $this->config,
78
+                    $this->dispatcher,
79
+                    $this->timeFactory
80
+                ]
81
+            )
82
+            ->onlyMethods(['updateProtocol'])
83
+            ->getMock();
84
+        $trustedServers->expects($this->once())->method('updateProtocol')
85
+            ->with('url')->willReturn('https://url');
86
+        $this->timeFactory->method('getTime')
87
+            ->willReturn(1234567);
88
+        $this->dbHandler->expects($this->once())->method('addServer')->with('https://url')
89
+            ->willReturn(1);
90
+
91
+        $this->secureRandom->expects($this->once())->method('generate')
92
+            ->willReturn('token');
93
+        $this->dbHandler->expects($this->once())->method('addToken')->with('https://url', 'token');
94
+        $this->jobList->expects($this->once())->method('add')
95
+            ->with(RequestSharedSecret::class,
96
+                ['url' => 'https://url', 'token' => 'token', 'created' => 1234567]);
97
+
98
+        $this->assertSame(
99
+            1,
100
+            $trustedServers->addServer('url')
101
+        );
102
+    }
103
+
104
+    public function testAddSharedSecret(): void {
105
+        $this->dbHandler->expects($this->once())->method('addSharedSecret')
106
+            ->with('url', 'secret');
107
+        $this->trustedServers->addSharedSecret('url', 'secret');
108
+    }
109
+
110
+    public function testGetSharedSecret(): void {
111
+        $this->dbHandler->expects($this->once())
112
+            ->method('getSharedSecret')
113
+            ->with('url')
114
+            ->willReturn('secret');
115
+        $this->assertSame(
116
+            $this->trustedServers->getSharedSecret('url'),
117
+            'secret'
118
+        );
119
+    }
120
+
121
+    public function testRemoveServer(): void {
122
+        $id = 42;
123
+        $server = ['url_hash' => 'url_hash'];
124
+        $this->dbHandler->expects($this->once())->method('removeServer')->with($id);
125
+        $this->dbHandler->expects($this->once())->method('getServerById')->with($id)
126
+            ->willReturn($server);
127
+        $this->dispatcher->expects($this->once())->method('dispatchTyped')
128
+            ->willReturnCallback(
129
+                function ($event): void {
130
+                    $this->assertSame(get_class($event), TrustedServerRemovedEvent::class);
131
+                    /** @var \OCP\Federated\Events\TrustedServerRemovedEvent $event */
132
+                    $this->assertSame('url_hash', $event->getUrlHash());
133
+                }
134
+            );
135
+        $this->trustedServers->removeServer($id);
136
+    }
137
+
138
+    public function testGetServers(): void {
139
+        $this->dbHandler->expects($this->once())->method('getAllServer')->willReturn(['servers']);
140
+
141
+        $this->assertEquals(
142
+            ['servers'],
143
+            $this->trustedServers->getServers()
144
+        );
145
+    }
146
+
147
+    public static function dataTestGetServer() {
148
+        return [
149
+            [
150
+                15,
151
+                [
152
+                    'id' => 15,
153
+                    'otherData' => 'first server',
154
+                ]
155
+            ],
156
+            [
157
+                16,
158
+                [
159
+                    'id' => 16,
160
+                    'otherData' => 'second server',
161
+                ]
162
+            ],
163
+            [
164
+                42,
165
+                [
166
+                    'id' => 42,
167
+                    'otherData' => 'last server',
168
+                ]
169
+            ],
170
+            [
171
+                108,
172
+                null
173
+            ],
174
+        ];
175
+    }
176
+
177
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetServer')]
178
+    public function testGetServer(int $id, ?array $expectedServer): void {
179
+        $servers = [
180
+            [
181
+                'id' => 15,
182
+                'otherData' => 'first server',
183
+            ],
184
+            [
185
+                'id' => 16,
186
+                'otherData' => 'second server',
187
+            ],
188
+            [
189
+                'id' => 42,
190
+                'otherData' => 'last server',
191
+            ],
192
+        ];
193
+        $this->dbHandler->expects($this->once())->method('getAllServer')->willReturn($servers);
194
+
195
+        if ($expectedServer === null) {
196
+            $this->expectException(\Exception::class);
197
+            $this->expectExceptionMessage('No server found with ID: ' . $id);
198
+        }
199
+
200
+        $this->assertEquals(
201
+            $expectedServer,
202
+            $this->trustedServers->getServer($id)
203
+        );
204
+    }
205
+
206
+    public function testIsTrustedServer(): void {
207
+        $this->dbHandler->expects($this->once())
208
+            ->method('serverExists')->with('url')
209
+            ->willReturn(true);
210
+
211
+        $this->assertTrue(
212
+            $this->trustedServers->isTrustedServer('url')
213
+        );
214
+    }
215
+
216
+    public function testSetServerStatus(): void {
217
+        $this->dbHandler->expects($this->once())->method('setServerStatus')
218
+            ->with('url', 1);
219
+        $this->trustedServers->setServerStatus('url', 1);
220
+    }
221
+
222
+    public function testGetServerStatus(): void {
223
+        $this->dbHandler->expects($this->once())->method('getServerStatus')
224
+            ->with('url')->willReturn(1);
225
+        $this->assertSame(
226
+            $this->trustedServers->getServerStatus('url'),
227
+            1
228
+        );
229
+    }
230
+
231
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsNextcloudServer')]
232
+    public function testIsNextcloudServer(int $statusCode, bool $isValidNextcloudVersion, bool $expected): void {
233
+        $server = 'server1';
234
+
235
+        /** @var TrustedServers&MockObject $trustedServers */
236
+        $trustedServers = $this->getMockBuilder(TrustedServers::class)
237
+            ->setConstructorArgs(
238
+                [
239
+                    $this->dbHandler,
240
+                    $this->httpClientService,
241
+                    $this->logger,
242
+                    $this->jobList,
243
+                    $this->secureRandom,
244
+                    $this->config,
245
+                    $this->dispatcher,
246
+                    $this->timeFactory
247
+                ]
248
+            )
249
+            ->onlyMethods(['checkNextcloudVersion'])
250
+            ->getMock();
251
+
252
+        $this->httpClientService->expects($this->once())->method('newClient')
253
+            ->willReturn($this->httpClient);
254
+
255
+        $this->httpClient->expects($this->once())->method('get')->with($server . '/status.php')
256
+            ->willReturn($this->response);
257
+
258
+        $this->response->expects($this->once())->method('getStatusCode')
259
+            ->willReturn($statusCode);
260
+
261
+        if ($statusCode === 200) {
262
+            $this->response->expects($this->once())->method('getBody')
263
+                ->willReturn('');
264
+            $trustedServers->expects($this->once())->method('checkNextcloudVersion')
265
+                ->willReturn($isValidNextcloudVersion);
266
+        } else {
267
+            $trustedServers->expects($this->never())->method('checkNextcloudVersion');
268
+        }
269
+
270
+        $this->assertSame($expected,
271
+            $trustedServers->isNextcloudServer($server)
272
+        );
273
+    }
274
+
275
+    public static function dataTestIsNextcloudServer(): array {
276
+        return [
277
+            [200, true, true],
278
+            [200, false, false],
279
+            [404, true, false],
280
+        ];
281
+    }
282
+
283
+    public function testIsNextcloudServerFail(): void {
284
+        $server = 'server1';
285
+
286
+        $this->httpClientService->expects($this->once())
287
+            ->method('newClient')
288
+            ->willReturn($this->httpClient);
289
+
290
+        $this->httpClient->expects($this->once())
291
+            ->method('get')
292
+            ->with($server . '/status.php')
293
+            ->willThrowException(new \Exception('simulated exception'));
294
+
295
+        $this->assertFalse($this->trustedServers->isNextcloudServer($server));
296
+    }
297
+
298
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCheckNextcloudVersion')]
299
+    public function testCheckNextcloudVersion(string $status): void {
300
+        $this->assertTrue(self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status]));
301
+    }
302
+
303
+    public static function dataTestCheckNextcloudVersion(): array {
304
+        return [
305
+            ['{"version":"9.0.0"}'],
306
+            ['{"version":"9.1.0"}']
307
+        ];
308
+    }
309
+
310
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCheckNextcloudVersionTooLow')]
311
+    public function testCheckNextcloudVersionTooLow(string $status): void {
312
+        $this->expectException(HintException::class);
313
+        $this->expectExceptionMessage('Remote server version is too low. 9.0 is required.');
314
+
315
+        self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status]);
316
+    }
317
+
318
+    public static function dataTestCheckNextcloudVersionTooLow(): array {
319
+        return [
320
+            ['{"version":"8.2.3"}'],
321
+        ];
322
+    }
323
+
324
+    #[\PHPUnit\Framework\Attributes\DataProvider('dataTestUpdateProtocol')]
325
+    public function testUpdateProtocol(string $url, string $expected): void {
326
+        $this->assertSame($expected,
327
+            self::invokePrivate($this->trustedServers, 'updateProtocol', [$url])
328
+        );
329
+    }
330
+
331
+    public static function dataTestUpdateProtocol(): array {
332
+        return [
333
+            ['http://owncloud.org', 'http://owncloud.org'],
334
+            ['https://owncloud.org', 'https://owncloud.org'],
335
+            ['owncloud.org', 'https://owncloud.org'],
336
+            ['httpserver', 'https://httpserver'],
337
+        ];
338
+    }
339 339
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 			->willReturn($server);
127 127
 		$this->dispatcher->expects($this->once())->method('dispatchTyped')
128 128
 			->willReturnCallback(
129
-				function ($event): void {
129
+				function($event): void {
130 130
 					$this->assertSame(get_class($event), TrustedServerRemovedEvent::class);
131 131
 					/** @var \OCP\Federated\Events\TrustedServerRemovedEvent $event */
132 132
 					$this->assertSame('url_hash', $event->getUrlHash());
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 
195 195
 		if ($expectedServer === null) {
196 196
 			$this->expectException(\Exception::class);
197
-			$this->expectExceptionMessage('No server found with ID: ' . $id);
197
+			$this->expectExceptionMessage('No server found with ID: '.$id);
198 198
 		}
199 199
 
200 200
 		$this->assertEquals(
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 		$this->httpClientService->expects($this->once())->method('newClient')
253 253
 			->willReturn($this->httpClient);
254 254
 
255
-		$this->httpClient->expects($this->once())->method('get')->with($server . '/status.php')
255
+		$this->httpClient->expects($this->once())->method('get')->with($server.'/status.php')
256 256
 			->willReturn($this->response);
257 257
 
258 258
 		$this->response->expects($this->once())->method('getStatusCode')
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
 
290 290
 		$this->httpClient->expects($this->once())
291 291
 			->method('get')
292
-			->with($server . '/status.php')
292
+			->with($server.'/status.php')
293 293
 			->willThrowException(new \Exception('simulated exception'));
294 294
 
295 295
 		$this->assertFalse($this->trustedServers->isNextcloudServer($server));
Please login to merge, or discard this patch.