migrate therinaldos.com data
Build & Deploy to DigitalOcean Space / build (push) Failing after 2m38s

This commit is contained in:
2024-05-05 15:50:45 -04:00
commit ef1ff240d4
23182 changed files with 3801898 additions and 0 deletions
@@ -0,0 +1,52 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Björn Schießle <bjoern@schiessle.org>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation\AppInfo;
use OCA\DAV\Events\SabrePluginAuthInitEvent;
use OCA\Federation\Listener\SabrePluginAuthInitListener;
use OCA\Federation\Middleware\AddServerMiddleware;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
class Application extends App implements IBootstrap {
/**
* @param array $urlParams
*/
public function __construct($urlParams = []) {
parent::__construct('federation', $urlParams);
}
public function register(IRegistrationContext $context): void {
$context->registerMiddleware(AddServerMiddleware::class);
$context->registerEventListener(SabrePluginAuthInitEvent::class, SabrePluginAuthInitListener::class);
}
public function boot(IBootContext $context): void {
}
}
@@ -0,0 +1,206 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation\BackgroundJob;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use OCA\Federation\TrustedServers;
use OCP\AppFramework\Http;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\Job;
use OCP\Http\Client\IClient;
use OCP\Http\Client\IClientService;
use OCP\Http\Client\IResponse;
use OCP\IURLGenerator;
use OCP\OCS\IDiscoveryService;
use Psr\Log\LoggerInterface;
/**
* Class GetSharedSecret
*
* Request shared secret from remote Nextcloud
*
* @package OCA\Federation\Backgroundjob
*/
class GetSharedSecret extends Job {
private IClient $httpClient;
private IJobList $jobList;
private IURLGenerator $urlGenerator;
private TrustedServers $trustedServers;
private IDiscoveryService $ocsDiscoveryService;
private LoggerInterface $logger;
protected bool $retainJob = false;
private string $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
/** 30 day = 2592000sec */
private int $maxLifespan = 2592000;
public function __construct(
IClientService $httpClientService,
IURLGenerator $urlGenerator,
IJobList $jobList,
TrustedServers $trustedServers,
LoggerInterface $logger,
IDiscoveryService $ocsDiscoveryService,
ITimeFactory $timeFactory
) {
parent::__construct($timeFactory);
$this->logger = $logger;
$this->httpClient = $httpClientService->newClient();
$this->jobList = $jobList;
$this->urlGenerator = $urlGenerator;
$this->ocsDiscoveryService = $ocsDiscoveryService;
$this->trustedServers = $trustedServers;
}
/**
* Run the job, then remove it from the joblist
*/
public function start(IJobList $jobList): void {
$target = $this->argument['url'];
// only execute if target is still in the list of trusted domains
if ($this->trustedServers->isTrustedServer($target)) {
$this->parentStart($jobList);
}
$jobList->remove($this, $this->argument);
if ($this->retainJob) {
$this->reAddJob($this->argument);
}
}
protected function parentStart(IJobList $jobList): void {
parent::start($jobList);
}
protected function run($argument) {
$target = $argument['url'];
$created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
$currentTime = $this->time->getTime();
$source = $this->urlGenerator->getAbsoluteURL('/');
$source = rtrim($source, '/');
$token = $argument['token'];
// kill job after 30 days of trying
$deadline = $currentTime - $this->maxLifespan;
if ($created < $deadline) {
$this->retainJob = false;
$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
return;
}
$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
$endPoint = $endPoints['shared-secret'] ?? $this->defaultEndPoint;
// make sure that we have a well formatted url
$url = rtrim($target, '/') . '/' . trim($endPoint, '/');
$result = null;
try {
$result = $this->httpClient->get(
$url,
[
'query' =>
[
'url' => $source,
'token' => $token,
'format' => 'json',
],
'timeout' => 3,
'connect_timeout' => 3,
]
);
$status = $result->getStatusCode();
} catch (ClientException $e) {
$status = $e->getCode();
if ($status === Http::STATUS_FORBIDDEN) {
$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
} else {
$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
}
} catch (RequestException $e) {
$status = -1; // There is no status code if we could not connect
$this->logger->info('Could not connect to ' . $target, [
'exception' => $e,
]);
} catch (\Throwable $e) {
$status = Http::STATUS_INTERNAL_SERVER_ERROR;
$this->logger->error($e->getMessage(), [
'exception' => $e,
]);
}
// if we received a unexpected response we try again later
if (
$status !== Http::STATUS_OK
&& $status !== Http::STATUS_FORBIDDEN
) {
$this->retainJob = true;
}
if ($status === Http::STATUS_OK && $result instanceof IResponse) {
$body = $result->getBody();
$result = json_decode($body, true);
if (isset($result['ocs']['data']['sharedSecret'])) {
$this->trustedServers->addSharedSecret(
$target,
$result['ocs']['data']['sharedSecret']
);
} else {
$this->logger->error(
'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
['app' => 'federation']
);
$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
}
}
}
/**
* Re-add background job
*
* @param array $argument
*/
protected function reAddJob(array $argument): void {
$url = $argument['url'];
$created = $argument['created'] ?? $this->time->getTime();
$token = $argument['token'];
$this->jobList->add(
GetSharedSecret::class,
[
'url' => $url,
'token' => $token,
'created' => $created
]
);
}
}
@@ -0,0 +1,186 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Côme Chilliet <come@chilliet.eu>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation\BackgroundJob;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use OCA\Federation\TrustedServers;
use OCP\AppFramework\Http;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\Job;
use OCP\Http\Client\IClient;
use OCP\Http\Client\IClientService;
use OCP\IURLGenerator;
use OCP\OCS\IDiscoveryService;
use Psr\Log\LoggerInterface;
/**
* Class RequestSharedSecret
*
* Ask remote Nextcloud to request a sharedSecret from this server
*
* @package OCA\Federation\Backgroundjob
*/
class RequestSharedSecret extends Job {
private IClient $httpClient;
protected bool $retainJob = false;
private string $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
/** @var int 30 day = 2592000sec */
private int $maxLifespan = 2592000;
public function __construct(
IClientService $httpClientService,
private IURLGenerator $urlGenerator,
private IJobList $jobList,
private TrustedServers $trustedServers,
private IDiscoveryService $ocsDiscoveryService,
private LoggerInterface $logger,
ITimeFactory $timeFactory,
) {
parent::__construct($timeFactory);
$this->httpClient = $httpClientService->newClient();
}
/**
* run the job, then remove it from the joblist
*/
public function start(IJobList $jobList): void {
$target = $this->argument['url'];
// only execute if target is still in the list of trusted domains
if ($this->trustedServers->isTrustedServer($target)) {
$this->parentStart($jobList);
}
$jobList->remove($this, $this->argument);
if ($this->retainJob) {
$this->reAddJob($this->argument);
}
}
/**
* Call start() method of parent
* Useful for unit tests
*/
protected function parentStart(IJobList $jobList): void {
parent::start($jobList);
}
/**
* @param array $argument
* @return void
*/
protected function run($argument) {
$target = $argument['url'];
$created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
$currentTime = $this->time->getTime();
$source = $this->urlGenerator->getAbsoluteURL('/');
$source = rtrim($source, '/');
$token = $argument['token'];
// kill job after 30 days of trying
$deadline = $currentTime - $this->maxLifespan;
if ($created < $deadline) {
$this->retainJob = false;
$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
return;
}
$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
$endPoint = $endPoints['shared-secret'] ?? $this->defaultEndPoint;
// make sure that we have a well formatted url
$url = rtrim($target, '/') . '/' . trim($endPoint, '/');
try {
$result = $this->httpClient->post(
$url,
[
'body' => [
'url' => $source,
'token' => $token,
'format' => 'json',
],
'timeout' => 3,
'connect_timeout' => 3,
]
);
$status = $result->getStatusCode();
} catch (ClientException $e) {
$status = $e->getCode();
if ($status === Http::STATUS_FORBIDDEN) {
$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
} else {
$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
}
} catch (RequestException $e) {
$status = -1; // There is no status code if we could not connect
$this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
} catch (\Throwable $e) {
$status = Http::STATUS_INTERNAL_SERVER_ERROR;
$this->logger->error($e->getMessage(), ['app' => 'federation', 'exception' => $e]);
}
// if we received a unexpected response we try again later
if (
$status !== Http::STATUS_OK
&& $status !== Http::STATUS_FORBIDDEN
) {
$this->retainJob = true;
}
}
/**
* re-add background job
*/
protected function reAddJob(array $argument): void {
$url = $argument['url'];
$created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
$token = $argument['token'];
$this->jobList->add(
RequestSharedSecret::class,
[
'url' => $url,
'token' => $token,
'created' => $created
]
);
}
}
@@ -0,0 +1,64 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation\Command;
use OCA\Federation\SyncFederationAddressBooks as SyncService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SyncFederationAddressBooks extends Command {
private SyncService $syncService;
public function __construct(SyncService $syncService) {
parent::__construct();
$this->syncService = $syncService;
}
protected function configure() {
$this
->setName('federation:sync-addressbooks')
->setDescription('Synchronizes addressbooks of all federated clouds');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$progress = new ProgressBar($output);
$progress->start();
$this->syncService->syncThemAll(function ($url, $ex) use ($progress, $output) {
if ($ex instanceof \Exception) {
$output->writeln("Error while syncing $url : " . $ex->getMessage());
} else {
$progress->advance();
}
});
$progress->finish();
$output->writeln('');
return 0;
}
}
@@ -0,0 +1,209 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation\Controller;
use OCA\Federation\DbHandler;
use OCA\Federation\TrustedServers;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\OpenAPI;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCSController;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\IRequest;
use OCP\Security\Bruteforce\IThrottler;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
/**
* Class OCSAuthAPI
*
* OCS API end-points to exchange shared secret between two connected Nextclouds
*
* @package OCA\Federation\Controller
*/
#[OpenAPI(scope: OpenAPI::SCOPE_FEDERATION)]
class OCSAuthAPIController extends OCSController {
private ISecureRandom $secureRandom;
private IJobList $jobList;
private TrustedServers $trustedServers;
private DbHandler $dbHandler;
private LoggerInterface $logger;
private ITimeFactory $timeFactory;
private IThrottler $throttler;
public function __construct(
string $appName,
IRequest $request,
ISecureRandom $secureRandom,
IJobList $jobList,
TrustedServers $trustedServers,
DbHandler $dbHandler,
LoggerInterface $logger,
ITimeFactory $timeFactory,
IThrottler $throttler
) {
parent::__construct($appName, $request);
$this->secureRandom = $secureRandom;
$this->jobList = $jobList;
$this->trustedServers = $trustedServers;
$this->dbHandler = $dbHandler;
$this->logger = $logger;
$this->timeFactory = $timeFactory;
$this->throttler = $throttler;
}
/**
* Request received to ask remote server for a shared secret, for legacy end-points
*
* @NoCSRFRequired
* @PublicPage
* @BruteForceProtection(action=federationSharedSecret)
*
* @param string $url URL of the server
* @param string $token Token of the server
* @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
* @throws OCSForbiddenException Requesting shared secret is not allowed
*
* 200: Shared secret requested successfully
*/
public function requestSharedSecretLegacy(string $url, string $token): DataResponse {
return $this->requestSharedSecret($url, $token);
}
/**
* Create shared secret and return it, for legacy end-points
*
* @NoCSRFRequired
* @PublicPage
* @BruteForceProtection(action=federationSharedSecret)
*
* @param string $url URL of the server
* @param string $token Token of the server
* @return DataResponse<Http::STATUS_OK, array{sharedSecret: string}, array{}>
* @throws OCSForbiddenException Getting shared secret is not allowed
*
* 200: Shared secret returned
*/
public function getSharedSecretLegacy(string $url, string $token): DataResponse {
return $this->getSharedSecret($url, $token);
}
/**
* Request received to ask remote server for a shared secret
*
* @NoCSRFRequired
* @PublicPage
* @BruteForceProtection(action=federationSharedSecret)
*
* @param string $url URL of the server
* @param string $token Token of the server
* @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
* @throws OCSForbiddenException Requesting shared secret is not allowed
*
* 200: Shared secret requested successfully
*/
public function requestSharedSecret(string $url, string $token): DataResponse {
if ($this->trustedServers->isTrustedServer($url) === false) {
$this->throttler->registerAttempt('federationSharedSecret', $this->request->getRemoteAddress());
$this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
throw new OCSForbiddenException();
}
// if both server initiated the exchange of the shared secret the greater
// token wins
$localToken = $this->dbHandler->getToken($url);
if (strcmp($localToken, $token) > 0) {
$this->logger->info(
'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
['app' => 'federation']
);
throw new OCSForbiddenException();
}
$this->jobList->add(
'OCA\Federation\BackgroundJob\GetSharedSecret',
[
'url' => $url,
'token' => $token,
'created' => $this->timeFactory->getTime()
]
);
return new DataResponse();
}
/**
* Create shared secret and return it
*
* @NoCSRFRequired
* @PublicPage
* @BruteForceProtection(action=federationSharedSecret)
*
* @param string $url URL of the server
* @param string $token Token of the server
* @return DataResponse<Http::STATUS_OK, array{sharedSecret: string}, array{}>
* @throws OCSForbiddenException Getting shared secret is not allowed
*
* 200: Shared secret returned
*/
public function getSharedSecret(string $url, string $token): DataResponse {
if ($this->trustedServers->isTrustedServer($url) === false) {
$this->throttler->registerAttempt('federationSharedSecret', $this->request->getRemoteAddress());
$this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
throw new OCSForbiddenException();
}
if ($this->isValidToken($url, $token) === false) {
$this->throttler->registerAttempt('federationSharedSecret', $this->request->getRemoteAddress());
$expectedToken = $this->dbHandler->getToken($url);
$this->logger->error(
'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
['app' => 'federation']
);
throw new OCSForbiddenException();
}
$sharedSecret = $this->secureRandom->generate(32);
$this->trustedServers->addSharedSecret($url, $sharedSecret);
return new DataResponse([
'sharedSecret' => $sharedSecret
]);
}
protected function isValidToken(string $url, string $token): bool {
$storedToken = $this->dbHandler->getToken($url);
return hash_equals($storedToken, $token);
}
}
@@ -0,0 +1,96 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation\Controller;
use OCA\Federation\TrustedServers;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\DataResponse;
use OCP\HintException;
use OCP\IL10N;
use OCP\IRequest;
class SettingsController extends Controller {
private IL10N $l;
private TrustedServers $trustedServers;
public function __construct(string $AppName,
IRequest $request,
IL10N $l10n,
TrustedServers $trustedServers
) {
parent::__construct($AppName, $request);
$this->l = $l10n;
$this->trustedServers = $trustedServers;
}
/**
* Add server to the list of trusted Nextclouds.
*
* @AuthorizedAdminSetting(settings=OCA\Federation\Settings\Admin)
* @throws HintException
*/
public function addServer(string $url): DataResponse {
$this->checkServer($url);
$id = $this->trustedServers->addServer($url);
return new DataResponse([
'url' => $url,
'id' => $id,
'message' => $this->l->t('Added to the list of trusted servers')
]);
}
/**
* Add server to the list of trusted Nextclouds.
*
* @AuthorizedAdminSetting(settings=OCA\Federation\Settings\Admin)
*/
public function removeServer(int $id): DataResponse {
$this->trustedServers->removeServer($id);
return new DataResponse();
}
/**
* Check if the server should be added to the list of trusted servers or not.
*
* @AuthorizedAdminSetting(settings=OCA\Federation\Settings\Admin)
* @throws HintException
*/
protected function checkServer(string $url): bool {
if ($this->trustedServers->isTrustedServer($url) === true) {
$message = 'Server is already in the list of trusted servers.';
$hint = $this->l->t('Server is already in the list of trusted servers.');
throw new HintException($message, $hint);
}
if ($this->trustedServers->isNextcloudServer($url) === false) {
$message = 'No server to federate with found';
$hint = $this->l->t('No server to federate with found');
throw new HintException($message, $hint);
}
return true;
}
}
@@ -0,0 +1,68 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation\DAV;
use OCA\Federation\DbHandler;
use Sabre\DAV\Auth\Backend\AbstractBasic;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
class FedAuth extends AbstractBasic {
/** @var DbHandler */
private $db;
/**
* FedAuth constructor.
*
* @param DbHandler $db
*/
public function __construct(DbHandler $db) {
$this->db = $db;
$this->principalPrefix = 'principals/system/';
// setup realm
$defaults = new \OCP\Defaults();
$this->realm = $defaults->getName();
}
/**
* Validates a username and password
*
* This method should return true or false depending on if login
* succeeded.
*
* @param string $username
* @param string $password
* @return bool
*/
protected function validateUserPass($username, $password) {
return $this->db->auth($username, $password);
}
/**
* @inheritdoc
*/
public function challenge(RequestInterface $request, ResponseInterface $response) {
}
}
@@ -0,0 +1,292 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation;
use OC\Files\Filesystem;
use OCP\DB\Exception as DBException;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\HintException;
use OCP\IDBConnection;
use OCP\IL10N;
/**
* Class DbHandler
*
* Handles all database calls for the federation app
*
* @todo Port to QBMapper
*
* @group DB
* @package OCA\Federation
*/
class DbHandler {
private IDBConnection $connection;
private IL10N $IL10N;
private string $dbTable = 'trusted_servers';
public function __construct(
IDBConnection $connection,
IL10N $il10n
) {
$this->connection = $connection;
$this->IL10N = $il10n;
}
/**
* Add server to the list of trusted servers
*
* @throws HintException
*/
public function addServer(string $url): int {
$hash = $this->hash($url);
$url = rtrim($url, '/');
$query = $this->connection->getQueryBuilder();
$query->insert($this->dbTable)
->values([
'url' => $query->createParameter('url'),
'url_hash' => $query->createParameter('url_hash'),
])
->setParameter('url', $url)
->setParameter('url_hash', $hash);
$result = $query->executeStatement();
if ($result) {
return $query->getLastInsertId();
}
$message = 'Internal failure, Could not add trusted server: ' . $url;
$message_t = $this->IL10N->t('Could not add server');
throw new HintException($message, $message_t);
return -1;
}
/**
* Remove server from the list of trusted servers
*/
public function removeServer(int $id): void {
$query = $this->connection->getQueryBuilder();
$query->delete($this->dbTable)
->where($query->expr()->eq('id', $query->createParameter('id')))
->setParameter('id', $id);
$query->executeStatement();
}
/**
* Get trusted server with given ID
*
* @return array{id: int, url: string, url_hash: string, token: ?string, shared_secret: ?string, status: int, sync_token: ?string}
* @throws \Exception
*/
public function getServerById(int $id): array {
$query = $this->connection->getQueryBuilder();
$query->select('*')->from($this->dbTable)
->where($query->expr()->eq('id', $query->createParameter('id')))
->setParameter('id', $id, IQueryBuilder::PARAM_INT);
$qResult = $query->executeQuery();
$result = $qResult->fetchAll();
$qResult->closeCursor();
if (empty($result)) {
throw new \Exception('No Server found with ID: ' . $id);
}
return $result[0];
}
/**
* Get all trusted servers
*
* @return list<array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}>
* @throws DBException
*/
public function getAllServer(): array {
$query = $this->connection->getQueryBuilder();
$query->select(['url', 'url_hash', 'id', 'status', 'shared_secret', 'sync_token'])
->from($this->dbTable);
$statement = $query->executeQuery();
$result = $statement->fetchAll();
$statement->closeCursor();
return $result;
}
/**
* Check if server already exists in the database table
*/
public function serverExists(string $url): bool {
$hash = $this->hash($url);
$query = $this->connection->getQueryBuilder();
$query->select('url')
->from($this->dbTable)
->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
->setParameter('url_hash', $hash);
$statement = $query->executeQuery();
$result = $statement->fetchAll();
$statement->closeCursor();
return !empty($result);
}
/**
* Write token to database. Token is used to exchange the secret
*/
public function addToken(string $url, string $token): void {
$hash = $this->hash($url);
$query = $this->connection->getQueryBuilder();
$query->update($this->dbTable)
->set('token', $query->createParameter('token'))
->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
->setParameter('url_hash', $hash)
->setParameter('token', $token);
$query->executeStatement();
}
/**
* Get token stored in database
* @throws \Exception
*/
public function getToken(string $url): string {
$hash = $this->hash($url);
$query = $this->connection->getQueryBuilder();
$query->select('token')->from($this->dbTable)
->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
->setParameter('url_hash', $hash);
$statement = $query->executeQuery();
$result = $statement->fetch();
$statement->closeCursor();
if (!isset($result['token'])) {
throw new \Exception('No token found for: ' . $url);
}
return $result['token'];
}
/**
* Add shared Secret to database
*/
public function addSharedSecret(string $url, string $sharedSecret): void {
$hash = $this->hash($url);
$query = $this->connection->getQueryBuilder();
$query->update($this->dbTable)
->set('shared_secret', $query->createParameter('sharedSecret'))
->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
->setParameter('url_hash', $hash)
->setParameter('sharedSecret', $sharedSecret);
$query->executeStatement();
}
/**
* Get shared secret from database
*/
public function getSharedSecret(string $url): string {
$hash = $this->hash($url);
$query = $this->connection->getQueryBuilder();
$query->select('shared_secret')->from($this->dbTable)
->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
->setParameter('url_hash', $hash);
$statement = $query->executeQuery();
$result = $statement->fetch();
$statement->closeCursor();
return (string)$result['shared_secret'];
}
/**
* Set server status
*/
public function setServerStatus(string $url, int $status, ?string $token = null): void {
$hash = $this->hash($url);
$query = $this->connection->getQueryBuilder();
$query->update($this->dbTable)
->set('status', $query->createNamedParameter($status))
->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash)));
if (!is_null($token)) {
$query->set('sync_token', $query->createNamedParameter($token));
}
$query->executeStatement();
}
/**
* Get server status
*/
public function getServerStatus(string $url): int {
$hash = $this->hash($url);
$query = $this->connection->getQueryBuilder();
$query->select('status')->from($this->dbTable)
->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
->setParameter('url_hash', $hash);
$statement = $query->executeQuery();
$result = $statement->fetch();
$statement->closeCursor();
return (int)$result['status'];
}
/**
* Create hash from URL
*/
protected function hash(string $url): string {
$normalized = $this->normalizeUrl($url);
return sha1($normalized);
}
/**
* Normalize URL, used to create the sha1 hash
*/
protected function normalizeUrl(string $url): string {
$normalized = $url;
if (strpos($url, 'https://') === 0) {
$normalized = substr($url, strlen('https://'));
} elseif (strpos($url, 'http://') === 0) {
$normalized = substr($url, strlen('http://'));
}
$normalized = Filesystem::normalizePath($normalized);
$normalized = trim($normalized, '/');
return $normalized;
}
public function auth(string $username, string $password): bool {
if ($username !== 'system') {
return false;
}
$query = $this->connection->getQueryBuilder();
$query->select('url')->from($this->dbTable)
->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password)));
$statement = $query->executeQuery();
$result = $statement->fetch();
$statement->closeCursor();
return !empty($result);
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, Morris Jobke <hey@morrisjobke.de>
*
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Federation\Listener;
use OCA\DAV\Events\SabrePluginAuthInitEvent;
use OCA\Federation\DAV\FedAuth;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use Sabre\DAV\Auth\Plugin;
/**
* @since 20.0.0
*/
class SabrePluginAuthInitListener implements IEventListener {
private FedAuth $fedAuth;
public function __construct(FedAuth $fedAuth) {
$this->fedAuth = $fedAuth;
}
public function handle(Event $event): void {
if (!($event instanceof SabrePluginAuthInitEvent)) {
return;
}
$server = $event->getServer();
$authPlugin = $server->getPlugin('auth');
if ($authPlugin instanceof Plugin) {
$authPlugin->addBackend($this->fedAuth);
}
}
}
@@ -0,0 +1,79 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation\Middleware;
use OCA\Federation\Controller\SettingsController;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Middleware;
use OCP\HintException;
use OCP\IL10N;
use Psr\Log\LoggerInterface;
class AddServerMiddleware extends Middleware {
protected string $appName;
protected IL10N $l;
protected LoggerInterface $logger;
public function __construct(string $appName, IL10N $l, LoggerInterface $logger) {
$this->appName = $appName;
$this->l = $l;
$this->logger = $logger;
}
/**
* Log error message and return a response which can be displayed to the user
*
* @param Controller $controller
* @param string $methodName
* @param \Exception $exception
* @return JSONResponse
* @throws \Exception
*/
public function afterException($controller, $methodName, \Exception $exception) {
if (($controller instanceof SettingsController) === false) {
throw $exception;
}
$this->logger->error($exception->getMessage(), [
'app' => $this->appName,
'exception' => $exception,
]);
if ($exception instanceof HintException) {
$message = $exception->getHint();
} else {
$message = $exception->getMessage();
}
return new JSONResponse(
['message' => $message],
Http::STATUS_BAD_REQUEST
);
}
}
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020 Joas Schilling <coding@schilljs.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Federation\Migration;
use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
class Version1010Date20200630191302 extends SimpleMigrationStep {
/**
* @param IOutput $output
* @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
* @param array $options
* @return null|ISchemaWrapper
*/
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options) {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
if (!$schema->hasTable('trusted_servers')) {
$table = $schema->createTable('trusted_servers');
$table->addColumn('id', Types::INTEGER, [
'autoincrement' => true,
'notnull' => true,
'length' => 4,
]);
$table->addColumn('url', Types::STRING, [
'notnull' => true,
'length' => 512,
]);
$table->addColumn('url_hash', Types::STRING, [
'notnull' => true,
'default' => '',
]);
$table->addColumn('token', Types::STRING, [
'notnull' => false,
'length' => 128,
]);
$table->addColumn('shared_secret', Types::STRING, [
'notnull' => false,
'length' => 256,
]);
$table->addColumn('status', Types::INTEGER, [
'notnull' => true,
'length' => 4,
'default' => 2,
]);
$table->addColumn('sync_token', Types::STRING, [
'notnull' => false,
'length' => 512,
]);
$table->setPrimaryKey(['id']);
$table->addUniqueIndex(['url_hash'], 'url_hash');
}
return $schema;
}
}
@@ -0,0 +1,75 @@
<?php
/**
* @copyright Copyright (c) 2016 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Federation\Settings;
use OCA\Federation\TrustedServers;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\IL10N;
use OCP\Settings\IDelegatedSettings;
class Admin implements IDelegatedSettings {
private TrustedServers $trustedServers;
private IL10N $l;
public function __construct(TrustedServers $trustedServers, IL10N $l) {
$this->trustedServers = $trustedServers;
$this->l = $l;
}
/**
* @return TemplateResponse
*/
public function getForm() {
$parameters = [
'trustedServers' => $this->trustedServers->getServers(),
];
return new TemplateResponse('federation', 'settings-admin', $parameters, '');
}
/**
* @return string the section ID, e.g. 'sharing'
*/
public function getSection() {
return 'sharing';
}
/**
* @return int whether the form should be rather on the top or bottom of
* the admin section. The forms are arranged in ascending order of the
* priority values. It is required to return a value between 0 and 100.
*
* E.g.: 70
*/
public function getPriority() {
return 30;
}
public function getName(): ?string {
return $this->l->t("Trusted servers");
}
public function getAuthorizedAppConfig(): array {
return []; // Handled by custom controller
}
}
@@ -0,0 +1,98 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation;
use OC\OCS\DiscoveryService;
use OCA\DAV\CardDAV\SyncService;
use OCP\AppFramework\Http;
use OCP\OCS\IDiscoveryService;
use Psr\Log\LoggerInterface;
class SyncFederationAddressBooks {
protected DbHandler $dbHandler;
private SyncService $syncService;
private DiscoveryService $ocsDiscoveryService;
private LoggerInterface $logger;
public function __construct(DbHandler $dbHandler,
SyncService $syncService,
IDiscoveryService $ocsDiscoveryService,
LoggerInterface $logger
) {
$this->syncService = $syncService;
$this->dbHandler = $dbHandler;
$this->ocsDiscoveryService = $ocsDiscoveryService;
$this->logger = $logger;
}
/**
* @param \Closure $callback
*/
public function syncThemAll(\Closure $callback) {
$trustedServers = $this->dbHandler->getAllServer();
foreach ($trustedServers as $trustedServer) {
$url = $trustedServer['url'];
$callback($url, null);
$sharedSecret = $trustedServer['shared_secret'];
$syncToken = $trustedServer['sync_token'];
$endPoints = $this->ocsDiscoveryService->discover($url, 'FEDERATED_SHARING');
$cardDavUser = $endPoints['carddav-user'] ?? 'system';
$addressBookUrl = isset($endPoints['system-address-book']) ? trim($endPoints['system-address-book'], '/') : 'remote.php/dav/addressbooks/system/system/system';
if (is_null($sharedSecret)) {
$this->logger->debug("Shared secret for $url is null");
continue;
}
$targetBookId = $trustedServer['url_hash'];
$targetPrincipal = "principals/system/system";
$targetBookProperties = [
'{DAV:}displayname' => $url
];
try {
$newToken = $this->syncService->syncRemoteAddressBook($url, $cardDavUser, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetBookProperties);
if ($newToken !== $syncToken) {
$this->dbHandler->setServerStatus($url, TrustedServers::STATUS_OK, $newToken);
} else {
$this->logger->debug("Sync Token for $url unchanged from previous sync");
}
} catch (\Exception $ex) {
if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
$this->dbHandler->setServerStatus($url, TrustedServers::STATUS_ACCESS_REVOKED);
$this->logger->error("Server sync for $url failed because of revoked access.", [
'exception' => $ex,
]);
} else {
$this->dbHandler->setServerStatus($url, TrustedServers::STATUS_FAILURE);
$this->logger->error("Server sync for $url failed.", [
'exception' => $ex,
]);
}
$callback($url, $ex);
}
}
}
}
@@ -0,0 +1,54 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use Psr\Log\LoggerInterface;
class SyncJob extends TimedJob {
protected SyncFederationAddressBooks $syncService;
protected LoggerInterface $logger;
public function __construct(SyncFederationAddressBooks $syncService, LoggerInterface $logger, ITimeFactory $timeFactory) {
parent::__construct($timeFactory);
// Run once a day
$this->setInterval(24 * 60 * 60);
$this->syncService = $syncService;
$this->logger = $logger;
}
protected function run($argument) {
$this->syncService->syncThemAll(function ($url, $ex) {
if ($ex instanceof \Exception) {
$this->logger->error("Error while syncing $url.", [
'app' => 'fed-sync',
'exception' => $ex,
]);
}
});
}
}
@@ -0,0 +1,216 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Federation;
use OCA\Federation\BackgroundJob\RequestSharedSecret;
use OCP\AppFramework\Http;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Federation\Events\TrustedServerRemovedEvent;
use OCP\HintException;
use OCP\Http\Client\IClientService;
use OCP\IConfig;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
class TrustedServers {
/** after a user list was exchanged at least once successfully */
public const STATUS_OK = 1;
/** waiting for shared secret or initial user list exchange */
public const STATUS_PENDING = 2;
/** something went wrong, misconfigured server, software bug,... user interaction needed */
public const STATUS_FAILURE = 3;
/** remote server revoked access */
public const STATUS_ACCESS_REVOKED = 4;
private DbHandler $dbHandler;
private IClientService $httpClientService;
private LoggerInterface $logger;
private IJobList $jobList;
private ISecureRandom $secureRandom;
private IConfig $config;
private IEventDispatcher $dispatcher;
private ITimeFactory $timeFactory;
public function __construct(
DbHandler $dbHandler,
IClientService $httpClientService,
LoggerInterface $logger,
IJobList $jobList,
ISecureRandom $secureRandom,
IConfig $config,
IEventDispatcher $dispatcher,
ITimeFactory $timeFactory
) {
$this->dbHandler = $dbHandler;
$this->httpClientService = $httpClientService;
$this->logger = $logger;
$this->jobList = $jobList;
$this->secureRandom = $secureRandom;
$this->config = $config;
$this->dispatcher = $dispatcher;
$this->timeFactory = $timeFactory;
}
/**
* Add server to the list of trusted servers
*/
public function addServer(string $url): int {
$url = $this->updateProtocol($url);
$result = $this->dbHandler->addServer($url);
if ($result) {
$token = $this->secureRandom->generate(16);
$this->dbHandler->addToken($url, $token);
$this->jobList->add(
RequestSharedSecret::class,
[
'url' => $url,
'token' => $token,
'created' => $this->timeFactory->getTime()
]
);
}
return $result;
}
/**
* Get shared secret for the given server
*/
public function getSharedSecret(string $url): string {
return $this->dbHandler->getSharedSecret($url);
}
/**
* Add shared secret for the given server
*/
public function addSharedSecret(string $url, string $sharedSecret): void {
$this->dbHandler->addSharedSecret($url, $sharedSecret);
}
/**
* Remove server from the list of trusted servers
*/
public function removeServer(int $id): void {
$server = $this->dbHandler->getServerById($id);
$this->dbHandler->removeServer($id);
$this->dispatcher->dispatchTyped(new TrustedServerRemovedEvent($server['url_hash']));
}
/**
* Get all trusted servers
* @return list<array{id: int, url: string, url_hash: string, shared_secret: string, status: int, sync_token: string}>
*/
public function getServers() {
return $this->dbHandler->getAllServer();
}
/**
* Check if given server is a trusted Nextcloud server
*/
public function isTrustedServer(string $url): bool {
return $this->dbHandler->serverExists($url);
}
/**
* Set server status
*/
public function setServerStatus(string $url, int $status): void {
$this->dbHandler->setServerStatus($url, $status);
}
/**
* Get server status
*/
public function getServerStatus(string $url): int {
return $this->dbHandler->getServerStatus($url);
}
/**
* Check if URL point to a ownCloud/Nextcloud server
*/
public function isNextcloudServer(string $url): bool {
$isValidNextcloud = false;
$client = $this->httpClientService->newClient();
try {
$result = $client->get(
$url . '/status.php',
[
'timeout' => 3,
'connect_timeout' => 3,
]
);
if ($result->getStatusCode() === Http::STATUS_OK) {
$body = $result->getBody();
if (is_resource($body)) {
$body = stream_get_contents($body) ?: '';
}
$isValidNextcloud = $this->checkNextcloudVersion($body);
}
} catch (\Exception $e) {
$this->logger->error('No Nextcloud server.', [
'app' => 'federation',
'exception' => $e,
]);
return false;
}
return $isValidNextcloud;
}
/**
* Check if ownCloud/Nextcloud version is >= 9.0
* @throws HintException
*/
protected function checkNextcloudVersion(string $status): bool {
$decoded = json_decode($status, true);
if (!empty($decoded) && isset($decoded['version'])) {
if (!version_compare($decoded['version'], '9.0.0', '>=')) {
throw new HintException('Remote server version is too low. 9.0 is required.');
}
return true;
}
return false;
}
/**
* Check if the URL contain a protocol, if not add https
*/
protected function updateProtocol(string $url): string {
if (
strpos($url, 'https://') === 0
|| strpos($url, 'http://') === 0
) {
return $url;
}
return 'https://' . $url;
}
}