-
-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathBackendService.php
More file actions
406 lines (366 loc) · 11.2 KB
/
Copy pathBackendService.php
File metadata and controls
406 lines (366 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
<?php
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_External\Service;
use OC\Files\Storage\Common;
use OCA\Files_External\AppInfo\Application;
use OCA\Files_External\Config\IConfigHandler;
use OCA\Files_External\Config\UserContext;
use OCA\Files_External\ConfigLexicon;
use OCA\Files_External\Lib\Auth\AuthMechanism;
use OCA\Files_External\Lib\Backend\Backend;
use OCA\Files_External\Lib\Config\IAuthMechanismProvider;
use OCA\Files_External\Lib\Config\IBackendProvider;
use OCP\EventDispatcher\GenericEvent;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\StorageNotAvailableException;
use OCP\IAppConfig;
use OCP\Server;
use Psr\Container\ContainerExceptionInterface;
use Psr\Log\LoggerInterface;
/**
* Service class to manage backend definitions
*/
class BackendService {
/** Visibility constants for VisibilityTrait */
public const VISIBILITY_NONE = 0;
public const VISIBILITY_PERSONAL = 1;
public const VISIBILITY_ADMIN = 2;
//const VISIBILITY_ALIENS = 4;
public const VISIBILITY_DEFAULT = 3; // PERSONAL | ADMIN
/** Priority constants for PriorityTrait */
public const PRIORITY_DEFAULT = 100;
private ?bool $userMountingAllowed = null;
/** @var string[] */
private array $userMountingBackends = [];
/** @var Backend[] */
private array $backends = [];
/** @var IBackendProvider[] */
private array $backendProviders = [];
/** @var AuthMechanism[] */
private array $authMechanisms = [];
/** @var IAuthMechanismProvider[] */
private array $authMechanismProviders = [];
/** @var callable[] */
private array $configHandlerLoaders = [];
/** @var IConfigHandler[] */
private array $configHandlers = [];
private bool $eventSent = false;
public function __construct(
protected readonly IAppConfig $appConfig,
private readonly LoggerInterface $logger,
) {
}
/**
* Register a backend provider
*
* @since 9.1.0
* @param IBackendProvider $provider
*/
public function registerBackendProvider(IBackendProvider $provider) {
$this->backendProviders[] = $provider;
}
private function callForRegistrations(): void {
$instance = Server::get(self::class);
if (!$instance->eventSent) {
Server::get(IEventDispatcher::class)->dispatch(
'OCA\\Files_External::loadAdditionalBackends',
new GenericEvent()
);
$instance->eventSent = true;
}
}
private function loadBackendProviders() {
$this->callForRegistrations();
foreach ($this->backendProviders as $provider) {
$this->registerBackends($provider->getBackends());
}
$this->backendProviders = [];
}
/**
* Register an auth mechanism provider
*
* @since 9.1.0
* @param IAuthMechanismProvider $provider
*/
public function registerAuthMechanismProvider(IAuthMechanismProvider $provider) {
$this->authMechanismProviders[] = $provider;
}
private function loadAuthMechanismProviders() {
$this->callForRegistrations();
foreach ($this->authMechanismProviders as $provider) {
$this->registerAuthMechanisms($provider->getAuthMechanisms());
}
$this->authMechanismProviders = [];
}
/**
* Register a backend
*
* @deprecated 9.1.0 use registerBackendProvider()
* @param Backend $backend
*/
public function registerBackend(Backend $backend) {
if (!$this->isAllowedUserBackend($backend)) {
$backend->removeVisibility(BackendService::VISIBILITY_PERSONAL);
}
foreach ($backend->getIdentifierAliases() as $alias) {
$this->backends[$alias] = $backend;
}
}
/**
* @deprecated 9.1.0 use registerBackendProvider()
* @param Backend[] $backends
*/
public function registerBackends(array $backends) {
foreach ($backends as $backend) {
$this->registerBackend($backend);
}
}
/**
* Register an authentication mechanism
*
* @deprecated 9.1.0 use registerAuthMechanismProvider()
* @param AuthMechanism $authMech
*/
public function registerAuthMechanism(AuthMechanism $authMech) {
if (!$this->isAllowedAuthMechanism($authMech)) {
$authMech->removeVisibility(BackendService::VISIBILITY_PERSONAL);
}
foreach ($authMech->getIdentifierAliases() as $alias) {
$this->authMechanisms[$alias] = $authMech;
}
}
/**
* @deprecated 9.1.0 use registerAuthMechanismProvider()
* @param AuthMechanism[] $mechanisms
*/
public function registerAuthMechanisms(array $mechanisms) {
foreach ($mechanisms as $mechanism) {
$this->registerAuthMechanism($mechanism);
}
}
/**
* Get all backends
*
* @return Backend[]
*/
public function getBackends() {
$this->loadBackendProviders();
// only return real identifiers, no aliases
$backends = [];
foreach ($this->backends as $backend) {
$backends[$backend->getIdentifier()] = $backend;
}
return $backends;
}
/**
* Get all available backends
*
* @return Backend[]
*/
public function getAvailableBackends() {
$backends = array_filter($this->getBackends(), fn (Backend $backend) => $backend->checkRequiredDependencies() === [] && $backend->getDeprecateTo() === null);
uasort($backends, [Backend::class, 'lexicalCompare']);
return $backends;
}
/**
* @param string $identifier
* @return Backend|null
*/
public function getBackend($identifier) {
$this->loadBackendProviders();
if (isset($this->backends[$identifier])) {
return $this->backends[$identifier];
}
return null;
}
/**
* Get all authentication mechanisms
*
* @return AuthMechanism[]
*/
public function getAuthMechanisms() {
$this->loadAuthMechanismProviders();
// only return real identifiers, no aliases
$mechanisms = [];
foreach ($this->authMechanisms as $mechanism) {
$mechanisms[$mechanism->getIdentifier()] = $mechanism;
}
return $mechanisms;
}
/**
* Get all authentication mechanisms for schemes
*
* @param string[] $schemes
* @return AuthMechanism[]
*/
public function getAuthMechanismsByScheme(array $schemes) {
return array_filter($this->getAuthMechanisms(), function ($authMech) use ($schemes) {
return in_array($authMech->getScheme(), $schemes, true);
});
}
/**
* @param string $identifier
* @return AuthMechanism|null
*/
public function getAuthMechanism($identifier) {
$this->loadAuthMechanismProviders();
if (isset($this->authMechanisms[$identifier])) {
return $this->authMechanisms[$identifier];
}
return null;
}
/**
* returns if user mounting is allowed.
* also initiate the list of available backends.
*
* @psalm-assert bool $this->userMountingAllowed
*/
public function isUserMountingAllowed(): bool {
if ($this->userMountingAllowed === null) {
// Load config values
$this->userMountingAllowed = $this->appConfig->getValueBool(Application::APP_ID, ConfigLexicon::ALLOW_USER_MOUNTING);
$this->userMountingBackends = explode(',', $this->appConfig->getValueString(Application::APP_ID, ConfigLexicon::USER_MOUNTING_BACKENDS));
// if no backend is in the list an empty string is in the array and user mounting is disabled
if ($this->userMountingBackends === ['']) {
$this->userMountingAllowed = false;
}
}
return $this->userMountingAllowed;
}
/**
* Check a backend if a user is allowed to mount it
*
* @param Backend $backend
* @return bool
*/
public function isAllowedUserBackend(Backend $backend): bool {
return ($this->isUserMountingAllowed() && array_intersect($backend->getIdentifierAliases(), $this->userMountingBackends));
}
/**
* Check an authentication mechanism if a user is allowed to use it
*
* @param AuthMechanism $authMechanism
* @return bool
*/
protected function isAllowedAuthMechanism(AuthMechanism $authMechanism) {
return true; // not implemented
}
/**
* registers a configuration handler
*
* The function of the provided $placeholder is mostly to act a sorting
* criteria, so longer placeholders are replaced first. This avoids
* "$user" overwriting parts of "$userMail" and "$userLang", for example.
* The provided value should not contain the $ prefix, only a-z0-9 are
* allowed. Upper case letters are lower cased, the replacement is case-
* insensitive.
*
* The configHandlerLoader should just instantiate the handler on demand.
* For now all handlers are instantiated when a mount is loaded, independent
* of whether the placeholder is present or not. This may change in future.
*
* @since 16.0.0
*/
public function registerConfigHandler(string $placeholder, callable $configHandlerLoader) {
$placeholder = trim(strtolower($placeholder));
if (!(bool)\preg_match('/^[a-z0-9]*$/', $placeholder)) {
throw new \RuntimeException(sprintf(
'Invalid placeholder %s, only [a-z0-9] are allowed', $placeholder
));
}
if ($placeholder === '') {
throw new \RuntimeException('Invalid empty placeholder');
}
if (isset($this->configHandlerLoaders[$placeholder]) || isset($this->configHandlers[$placeholder])) {
throw new \RuntimeException(sprintf('A handler is already registered for %s', $placeholder));
}
$this->configHandlerLoaders[$placeholder] = $configHandlerLoader;
}
protected function loadConfigHandlers():void {
$this->callForRegistrations();
$newLoaded = false;
foreach ($this->configHandlerLoaders as $placeholder => $loader) {
$handler = $loader();
if (!$handler instanceof IConfigHandler) {
throw new \RuntimeException(sprintf(
'Handler for %s is not an instance of IConfigHandler', $placeholder
));
}
$this->configHandlers[$placeholder] = $handler;
$newLoaded = true;
}
$this->configHandlerLoaders = [];
if ($newLoaded) {
// ensure those with longest placeholders come first,
// to avoid substring matches
uksort($this->configHandlers, function ($phA, $phB) {
return strlen($phB) <=> strlen($phA);
});
}
}
/**
* @since 16.0.0
* @return IConfigHandler[]
*/
public function getConfigHandlers(): array {
$this->loadConfigHandlers();
return $this->configHandlers;
}
/**
* @param mixed $input
* @return mixed
* @throws ContainerExceptionInterface
*/
public function applyConfigHandlers($input, ?string $userId = null) {
/** @var IConfigHandler[] $handlers */
$handlers = $this->getConfigHandlers();
foreach ($handlers as $handler) {
if ($handler instanceof UserContext && $userId !== null) {
$handler->setUserId($userId);
}
$input = $handler->handle($input);
}
return $input;
}
/**
* Test connecting using the given backend configuration
*
* @param string $class backend class name
* @param array $options backend configuration options
* @return StorageNotAvailableException::STATUS_*
* @throws \Exception
*/
public function getBackendStatus(string $class, array $options): int {
foreach ($options as $key => &$option) {
if ($key === 'password') {
// no replacements in passwords
continue;
}
$option = $this->applyConfigHandlers($option);
}
if (class_exists($class)) {
try {
/** @var Common $storage */
$storage = new $class($options);
try {
$result = $storage->test();
$storage->setAvailability($result);
if ($result) {
return StorageNotAvailableException::STATUS_SUCCESS;
}
} catch (\Exception $e) {
$storage->setAvailability(false);
throw $e;
}
} catch (\Exception $exception) {
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
throw $exception;
}
}
return StorageNotAvailableException::STATUS_ERROR;
}
}