Merge pull request #34728 from nextcloud/backport/33945/stable25

[stable25] LDAP to not register new users when outside of fair use or over limits
This commit is contained in:
Simon L 2022-10-24 10:42:47 +02:00 committed by GitHub
commit dc2fe31250
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 261 additions and 59 deletions

View file

@ -35,7 +35,7 @@ $subject = (string)$_POST['ldap_clear_mapping'];
$mapping = null;
try {
if ($subject === 'user') {
$mapping = new UserMapping(\OC::$server->getDatabaseConnection());
$mapping = \OCP\Server::get(UserMapping::class);
$result = $mapping->clearCb(
function ($uid) {
\OC::$server->getUserManager()->emit('\OC\User', 'preUnassignedUserId', [$uid]);

View file

@ -34,18 +34,32 @@ use OCP\Group\Backend\INamedBackend;
class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend, INamedBackend, IDeleteGroupBackend {
private $backends = [];
private $refBackend = null;
private ?Group_LDAP $refBackend = null;
private Helper $helper;
private GroupPluginManager $groupPluginManager;
private bool $isSetUp = false;
public function __construct(Helper $helper, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) {
parent::__construct($ldap);
$serverConfigPrefixes = $helper->getServerConfigurationPrefixes(true);
$this->helper = $helper;
$this->groupPluginManager = $groupPluginManager;
}
protected function setup(): void {
if ($this->isSetUp) {
return;
}
$serverConfigPrefixes = $this->helper->getServerConfigurationPrefixes(true);
foreach ($serverConfigPrefixes as $configPrefix) {
$this->backends[$configPrefix] =
new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager);
new Group_LDAP($this->getAccess($configPrefix), $this->groupPluginManager);
if (is_null($this->refBackend)) {
$this->refBackend = &$this->backends[$configPrefix];
}
}
$this->isSetUp = true;
}
/**
@ -57,6 +71,8 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet
* @return mixed the result of the method or false
*/
protected function walkBackends($id, $method, $parameters) {
$this->setup();
$gid = $id;
$cacheKey = $this->getGroupCacheKey($gid);
foreach ($this->backends as $configPrefix => $backend) {
@ -80,6 +96,8 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet
* @return mixed the result of the method or false
*/
protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen) {
$this->setup();
$gid = $id;
$cacheKey = $this->getGroupCacheKey($gid);
$prefix = $this->getFromCache($cacheKey);
@ -105,6 +123,7 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet
}
protected function activeBackends(): int {
$this->setup();
return count($this->backends);
}
@ -131,8 +150,9 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet
* if the user exists at all.
*/
public function getUserGroups($uid) {
$groups = [];
$this->setup();
$groups = [];
foreach ($this->backends as $backend) {
$backendGroups = $backend->getUserGroups($uid);
if (is_array($backendGroups)) {
@ -149,8 +169,9 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet
* @return string[] with user ids
*/
public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
$users = [];
$this->setup();
$users = [];
foreach ($this->backends as $backend) {
$backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
if (is_array($backendUsers)) {
@ -237,8 +258,9 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet
* Returns a list with all groups
*/
public function getGroups($search = '', $limit = -1, $offset = 0) {
$groups = [];
$this->setup();
$groups = [];
foreach ($this->backends as $backend) {
$backendGroups = $backend->getGroups($search, $limit, $offset);
if (is_array($backendGroups)) {
@ -269,6 +291,7 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet
* compared with \OCP\GroupInterface::CREATE_GROUP etc.
*/
public function implementsActions($actions) {
$this->setup();
//it's the same across all our user backends obviously
return $this->refBackend->implementsActions($actions);
}

View file

@ -107,7 +107,7 @@ class CleanUp extends TimedJob {
if (isset($arguments['mapping'])) {
$this->mapping = $arguments['mapping'];
} else {
$this->mapping = new UserMapping($this->db);
$this->mapping = \OCP\Server::get(UserMapping::class);
}
if (isset($arguments['deletedUsersIndex'])) {

View file

@ -357,7 +357,7 @@ class Sync extends TimedJob {
if (isset($argument['mapper'])) {
$this->mapper = $argument['mapper'];
} else {
$this->mapper = new UserMapping($this->dbc);
$this->mapper = \OCP\Server::get(UserMapping::class);
}
if (isset($argument['connectionFactory'])) {

View file

@ -22,12 +22,51 @@
*/
namespace OCA\User_LDAP\Mapping;
use OCP\HintException;
use OCP\IDBConnection;
use OCP\IRequest;
use OCP\Server;
use OCP\Support\Subscription\IAssertion;
/**
* Class UserMapping
*
* @package OCA\User_LDAP\Mapping
*/
class UserMapping extends AbstractMapping {
private IAssertion $assertion;
protected const PROV_API_REGEX = '/\/ocs\/v[1-9].php\/cloud\/(groups|users)/';
public function __construct(IDBConnection $dbc, IAssertion $assertion) {
$this->assertion = $assertion;
parent::__construct($dbc);
}
/**
* @throws HintException
*/
public function map($fdn, $name, $uuid): bool {
try {
$this->assertion->createUserIsLegit();
} catch (HintException $e) {
static $isProvisioningApi = null;
if ($isProvisioningApi === null) {
$request = Server::get(IRequest::class);
$isProvisioningApi = \preg_match(self::PROV_API_REGEX, $request->getRequestUri()) === 1;
}
if ($isProvisioningApi) {
// only throw when prov API is being used, since functionality
// should not break for end users (e.g. when sharing).
// On direct API usage, e.g. on users page, this is desired.
throw $e;
}
return false;
}
return parent::map($fdn, $name, $uuid);
}
/**
* returns the DB table name which holds the mappings
* @return string

View file

@ -35,7 +35,9 @@ namespace OCA\User_LDAP;
use OCA\User_LDAP\Mapping\GroupMapping;
use OCA\User_LDAP\Mapping\UserMapping;
use OCA\User_LDAP\User\Manager;
use OCP\Share\IManager;
use OCP\IConfig;
use OCP\IUserManager;
use OCP\Server;
use Psr\Log\LoggerInterface;
abstract class Proxy {
@ -61,34 +63,18 @@ abstract class Proxy {
/**
* @param string $configPrefix
*/
private function addAccess($configPrefix) {
static $ocConfig;
static $fs;
static $log;
static $avatarM;
static $userMap;
static $groupMap;
static $shareManager;
static $coreUserManager;
static $coreNotificationManager;
static $logger;
if ($fs === null) {
$ocConfig = \OC::$server->getConfig();
$fs = new FilesystemHelper();
$avatarM = \OC::$server->getAvatarManager();
$db = \OC::$server->getDatabaseConnection();
$userMap = new UserMapping($db);
$groupMap = new GroupMapping($db);
$coreUserManager = \OC::$server->getUserManager();
$coreNotificationManager = \OC::$server->getNotificationManager();
$shareManager = \OC::$server->get(IManager::class);
$logger = \OC::$server->get(LoggerInterface::class);
}
$userManager =
new Manager($ocConfig, $fs, $logger, $avatarM, new \OCP\Image(),
$coreUserManager, $coreNotificationManager, $shareManager);
private function addAccess(string $configPrefix): void {
$ocConfig = Server::get(IConfig::class);
$userMap = Server::get(UserMapping::class);
$groupMap = Server::get(GroupMapping::class);
$coreUserManager = Server::get(IUserManager::class);
$logger = Server::get(LoggerInterface::class);
$helper = Server::get(Helper::class);
$userManager = Server::get(Manager::class);
$connector = new Connection($this->ldap, $configPrefix);
$access = new Access($connector, $this->ldap, $userManager, new Helper($ocConfig, \OC::$server->getDatabaseConnection()), $ocConfig, $coreUserManager, $logger);
$access = new Access($connector, $this->ldap, $userManager, $helper, $ocConfig, $coreUserManager, $logger);
$access->setUserMapper($userMap);
$access->setGroupMapper($groupMap);
self::$accesses[$configPrefix] = $access;

View file

@ -42,6 +42,13 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
/** @var User_LDAP */
private $refBackend = null;
private bool $isSetUp = false;
private Helper $helper;
private IConfig $ocConfig;
private INotificationManager $notificationManager;
private IUserSession $userSession;
private UserPluginManager $userPluginManager;
public function __construct(
Helper $helper,
ILDAPWrapper $ldap,
@ -51,15 +58,29 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
UserPluginManager $userPluginManager
) {
parent::__construct($ldap);
$serverConfigPrefixes = $helper->getServerConfigurationPrefixes(true);
$this->helper = $helper;
$this->ocConfig = $ocConfig;
$this->notificationManager = $notificationManager;
$this->userSession = $userSession;
$this->userPluginManager = $userPluginManager;
}
protected function setup(): void {
if ($this->isSetUp) {
return;
}
$serverConfigPrefixes = $this->helper->getServerConfigurationPrefixes(true);
foreach ($serverConfigPrefixes as $configPrefix) {
$this->backends[$configPrefix] =
new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager, $userSession, $userPluginManager);
new User_LDAP($this->getAccess($configPrefix), $this->ocConfig, $this->notificationManager, $this->userSession, $this->userPluginManager);
if (is_null($this->refBackend)) {
$this->refBackend = &$this->backends[$configPrefix];
}
}
$this->isSetUp = true;
}
/**
@ -71,6 +92,8 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
* @return mixed the result of the method or false
*/
protected function walkBackends($id, $method, $parameters) {
$this->setup();
$uid = $id;
$cacheKey = $this->getUserCacheKey($uid);
foreach ($this->backends as $configPrefix => $backend) {
@ -99,6 +122,8 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
* @return mixed the result of the method or false
*/
protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen) {
$this->setup();
$uid = $id;
$cacheKey = $this->getUserCacheKey($uid);
$prefix = $this->getFromCache($cacheKey);
@ -129,6 +154,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
}
protected function activeBackends(): int {
$this->setup();
return count($this->backends);
}
@ -142,6 +168,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
* compared with \OC\User\Backend::CREATE_USER etc.
*/
public function implementsActions($actions) {
$this->setup();
//it's the same across all our user backends obviously
return $this->refBackend->implementsActions($actions);
}
@ -152,6 +179,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
* @return string the name of the backend to be shown
*/
public function getBackendName() {
$this->setup();
return $this->refBackend->getBackendName();
}
@ -164,6 +192,8 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
* @return string[] an array of all uids
*/
public function getUsers($search = '', $limit = 10, $offset = 0) {
$this->setup();
//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
$users = [];
foreach ($this->backends as $backend) {
@ -296,6 +326,8 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
* @return array an array of all displayNames (value) and the corresponding uids (key)
*/
public function getDisplayNames($search = '', $limit = null, $offset = null) {
$this->setup();
//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
$users = [];
foreach ($this->backends as $backend) {
@ -335,6 +367,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
* @return bool
*/
public function hasUserListings() {
$this->setup();
return $this->refBackend->hasUserListings();
}
@ -344,6 +377,8 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface,
* @return int|bool
*/
public function countUsers() {
$this->setup();
$users = false;
foreach ($this->backends as $backend) {
$backendUsers = $backend->countUsers();

View file

@ -24,6 +24,7 @@
namespace OCA\User_LDAP\Tests\Mapping;
use OCA\User_LDAP\Mapping\UserMapping;
use OCP\Support\Subscription\IAssertion;
/**
* Class UserMappingTest
@ -34,6 +35,6 @@ use OCA\User_LDAP\Mapping\UserMapping;
*/
class UserMappingTest extends AbstractMappingTest {
public function getMapper(\OCP\IDBConnection $dbMock) {
return new UserMapping($dbMock);
return new UserMapping($dbMock, $this->createMock(IAssertion::class));
}
}

View file

@ -567,6 +567,7 @@ return array(
'OCP\\Support\\CrashReport\\IRegistry' => $baseDir . '/lib/public/Support/CrashReport/IRegistry.php',
'OCP\\Support\\CrashReport\\IReporter' => $baseDir . '/lib/public/Support/CrashReport/IReporter.php',
'OCP\\Support\\Subscription\\Exception\\AlreadyRegisteredException' => $baseDir . '/lib/public/Support/Subscription/Exception/AlreadyRegisteredException.php',
'OCP\\Support\\Subscription\\IAssertion' => $baseDir . '/lib/public/Support/Subscription/IAssertion.php',
'OCP\\Support\\Subscription\\IRegistry' => $baseDir . '/lib/public/Support/Subscription/IRegistry.php',
'OCP\\Support\\Subscription\\ISubscription' => $baseDir . '/lib/public/Support/Subscription/ISubscription.php',
'OCP\\Support\\Subscription\\ISupportedApps' => $baseDir . '/lib/public/Support/Subscription/ISupportedApps.php',
@ -1553,6 +1554,7 @@ return array(
'OC\\Streamer' => $baseDir . '/lib/private/Streamer.php',
'OC\\SubAdmin' => $baseDir . '/lib/private/SubAdmin.php',
'OC\\Support\\CrashReport\\Registry' => $baseDir . '/lib/private/Support/CrashReport/Registry.php',
'OC\\Support\\Subscription\\Assertion' => $baseDir . '/lib/private/Support/Subscription/Assertion.php',
'OC\\Support\\Subscription\\Registry' => $baseDir . '/lib/private/Support/Subscription/Registry.php',
'OC\\SystemConfig' => $baseDir . '/lib/private/SystemConfig.php',
'OC\\SystemTag\\ManagerFactory' => $baseDir . '/lib/private/SystemTag/ManagerFactory.php',

View file

@ -600,6 +600,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OCP\\Support\\CrashReport\\IRegistry' => __DIR__ . '/../../..' . '/lib/public/Support/CrashReport/IRegistry.php',
'OCP\\Support\\CrashReport\\IReporter' => __DIR__ . '/../../..' . '/lib/public/Support/CrashReport/IReporter.php',
'OCP\\Support\\Subscription\\Exception\\AlreadyRegisteredException' => __DIR__ . '/../../..' . '/lib/public/Support/Subscription/Exception/AlreadyRegisteredException.php',
'OCP\\Support\\Subscription\\IAssertion' => __DIR__ . '/../../..' . '/lib/public/Support/Subscription/IAssertion.php',
'OCP\\Support\\Subscription\\IRegistry' => __DIR__ . '/../../..' . '/lib/public/Support/Subscription/IRegistry.php',
'OCP\\Support\\Subscription\\ISubscription' => __DIR__ . '/../../..' . '/lib/public/Support/Subscription/ISubscription.php',
'OCP\\Support\\Subscription\\ISupportedApps' => __DIR__ . '/../../..' . '/lib/public/Support/Subscription/ISupportedApps.php',
@ -1586,6 +1587,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\Streamer' => __DIR__ . '/../../..' . '/lib/private/Streamer.php',
'OC\\SubAdmin' => __DIR__ . '/../../..' . '/lib/private/SubAdmin.php',
'OC\\Support\\CrashReport\\Registry' => __DIR__ . '/../../..' . '/lib/private/Support/CrashReport/Registry.php',
'OC\\Support\\Subscription\\Assertion' => __DIR__ . '/../../..' . '/lib/private/Support/Subscription/Assertion.php',
'OC\\Support\\Subscription\\Registry' => __DIR__ . '/../../..' . '/lib/private/Support/Subscription/Registry.php',
'OC\\SystemConfig' => __DIR__ . '/../../..' . '/lib/private/SystemConfig.php',
'OC\\SystemTag\\ManagerFactory' => __DIR__ . '/../../..' . '/lib/private/SystemTag/ManagerFactory.php',

View file

@ -794,6 +794,7 @@ class Server extends ServerContainer implements IServerContainer {
$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
$this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
$this->registerService(\OC\Log::class, function (Server $c) {
$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');

View file

@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 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 <https://www.gnu.org/licenses/>.
*
*/
namespace OC\Support\Subscription;
use OCP\HintException;
use OCP\L10N\IFactory;
use OCP\Notification\IManager;
use OCP\Support\Subscription\IAssertion;
use OCP\Support\Subscription\IRegistry;
class Assertion implements IAssertion {
private IRegistry $registry;
private IFactory $l10nFactory;
private IManager $notificationManager;
public function __construct(IRegistry $registry, IFactory $l10nFactory, IManager $notificationManager) {
$this->registry = $registry;
$this->l10nFactory = $l10nFactory;
$this->notificationManager = $notificationManager;
}
/**
* @inheritDoc
*/
public function createUserIsLegit(): void {
if ($this->registry->delegateIsHardUserLimitReached($this->notificationManager)) {
$l = $this->l10nFactory->get('lib');
throw new HintException($l->t('The user limit has been reached and the user was not created. Check your notifications to learn more.'));
}
}
}

View file

@ -215,19 +215,38 @@ class Registry implements IRegistry {
return $userCount;
}
private function notifyAboutReachedUserLimit(IManager $notificationManager) {
private function notifyAboutReachedUserLimit(IManager $notificationManager): void {
$admins = $this->groupManager->get('admin')->getUsers();
foreach ($admins as $admin) {
$notification = $notificationManager->createNotification();
$notification->setApp('core')
->setUser($admin->getUID())
->setDateTime(new \DateTime())
->setObject('user_limit_reached', '1')
->setSubject('user_limit_reached');
$notification = $notificationManager->createNotification();
$notification->setApp('core')
->setObject('user_limit_reached', '1')
->setSubject('user_limit_reached');
if ($notificationManager->getCount($notification) > 0
&& !$this->reIssue()
) {
return;
}
$notificationManager->markProcessed($notification);
$notification->setDateTime(new \DateTime());
foreach ($admins as $admin) {
$notification->setUser($admin->getUID());
$notificationManager->notify($notification);
}
$this->logger->warning('The user limit was reached and the new user was not created', ['app' => 'lib']);
}
protected function reIssue(): bool {
$lastNotification = (int)$this->config->getAppValue('lib', 'last_subscription_reminder', '0');
if ((time() - $lastNotification) >= 86400) {
$this->config->setAppValue('lib', 'last_subscription_reminder', (string)time());
return true;
}
return false;
}
}

View file

@ -44,8 +44,7 @@ use OCP\IGroup;
use OCP\IUser;
use OCP\IUserBackend;
use OCP\IUserManager;
use OCP\Notification\IManager;
use OCP\Support\Subscription\IRegistry;
use OCP\Support\Subscription\IAssertion;
use OCP\User\Backend\IGetRealUIDBackend;
use OCP\User\Backend\ISearchKnownUsersBackend;
use OCP\User\Backend\ICheckPasswordBackend;
@ -386,19 +385,15 @@ class Manager extends PublicEmitter implements IUserManager {
/**
* @param string $uid
* @param string $password
* @throws \InvalidArgumentException
* @return false|IUser the created user or false
* @throws \InvalidArgumentException
* @throws HintException
*/
public function createUser($uid, $password) {
// DI injection is not used here as IRegistry needs the user manager itself for user count and thus it would create a cyclic dependency
/** @var IRegistry $registry */
$registry = \OC::$server->get(IRegistry::class);
/** @var IManager $notificationManager */
$notificationManager = \OC::$server->get(IManager::class);
if ($registry->delegateIsHardUserLimitReached($notificationManager)) {
$l = \OC::$server->getL10N('lib');
throw new HintException($l->t('The user limit has been reached and the user was not created.'));
}
/** @var IAssertion $assertion */
$assertion = \OC::$server->get(IAssertion::class);
$assertion->createUserIsLegit();
$localBackends = [];
foreach ($this->backends as $backend) {

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 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 <https://www.gnu.org/licenses/>.
*
*/
namespace OCP\Support\Subscription;
use OCP\HintException;
/**
* @since 26.0.0
*/
interface IAssertion {
/**
* This method throws a localized exception when user limits are exceeded,
* if applicable. Notifications are also created in that case. It is a
* shorthand for a check against IRegistry::delegateIsHardUserLimitReached().
*
* @throws HintException
* @since 26.0.0
*/
public function createUserIsLegit(): void;
}