Merge pull request #508 from nextcloud/fix/noid/userids-not-sanitized

sanitize and test user id received from IdP, if original does not match
This commit is contained in:
blizzz 2021-03-01 14:09:38 +01:00 committed by GitHub
commit e37fee7f38
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 647 additions and 523 deletions

View file

@ -45,6 +45,12 @@ $samlSettings = new \OCA\User_SAML\SAMLSettings(
$session
);
$userData = new \OCA\User_SAML\UserData(
new \OCA\User_SAML\UserResolver(\OC::$server->getUserManager()),
$samlSettings,
$config
);
$userBackend = new \OCA\User_SAML\UserBackend(
$config,
$urlGenerator,
@ -53,7 +59,8 @@ $userBackend = new \OCA\User_SAML\UserBackend(
\OC::$server->getUserManager(),
\OC::$server->getGroupManager(),
$samlSettings,
\OC::$server->getLogger()
\OC::$server->getLogger(),
$userData
);
$userBackend->registerBackends(\OC::$server->getUserManager()->getBackends());
OC_User::useBackend($userBackend);

View file

@ -28,6 +28,8 @@ use OC\Core\Controller\ClientFlowLoginV2Controller;
use OCA\User_SAML\Exceptions\NoUserFoundException;
use OCA\User_SAML\SAMLSettings;
use OCA\User_SAML\UserBackend;
use OCA\User_SAML\UserData;
use OCA\User_SAML\UserResolver;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\IConfig;
@ -58,12 +60,14 @@ class SAMLController extends Controller {
private $config;
/** @var IURLGenerator */
private $urlGenerator;
/** @var IUserManager */
private $userManager;
/** @var ILogger */
private $logger;
/** @var IL10N */
private $l;
/** @var UserResolver */
private $userResolver;
/** @var UserData */
private $userData;
/**
* @var ICrypto
*/
@ -78,22 +82,24 @@ class SAMLController extends Controller {
* @param UserBackend $userBackend
* @param IConfig $config
* @param IURLGenerator $urlGenerator
* @param IUserManager $userManager
* @param ILogger $logger
* @param IL10N $l
*/
public function __construct($appName,
IRequest $request,
ISession $session,
IUserSession $userSession,
SAMLSettings $SAMLSettings,
UserBackend $userBackend,
IConfig $config,
IURLGenerator $urlGenerator,
IUserManager $userManager,
ILogger $logger,
IL10N $l,
ICrypto $crypto) {
public function __construct(
$appName,
IRequest $request,
ISession $session,
IUserSession $userSession,
SAMLSettings $SAMLSettings,
UserBackend $userBackend,
IConfig $config,
IURLGenerator $urlGenerator,
ILogger $logger,
IL10N $l,
UserResolver $userResolver,
UserData $userData,
ICrypto $crypto
) {
parent::__construct($appName, $request);
$this->session = $session;
$this->userSession = $userSession;
@ -101,71 +107,56 @@ class SAMLController extends Controller {
$this->userBackend = $userBackend;
$this->config = $config;
$this->urlGenerator = $urlGenerator;
$this->userManager = $userManager;
$this->logger = $logger;
$this->l = $l;
$this->userResolver = $userResolver;
$this->userData = $userData;
$this->crypto = $crypto;
}
/**
* @param array $auth
* @throws NoUserFoundException
*/
private function autoprovisionIfPossible(array $auth) {
private function autoprovisionIfPossible() {
$auth = $this->userData->getAttributes();
$prefix = $this->SAMLSettings->getPrefix();
$uidMapping = $this->config->getAppValue('user_saml', $prefix . 'general-uid_mapping');
if(isset($auth[$uidMapping])) {
if(is_array($auth[$uidMapping])) {
$uid = $auth[$uidMapping][0];
} else {
$uid = $auth[$uidMapping];
}
// make sure that a valid UID is given
if (empty($uid)) {
$this->logger->error('Uid "' . $uid . '" is not a valid uid please check your attribute mapping', ['app' => $this->appName]);
throw new \InvalidArgumentException('No valid uid given, please check your attribute mapping. Given uid: ' . $uid);
}
$uid = $this->userBackend->testEncodedObjectGUID($uid);
// if this server acts as a global scale master and the user is not
// a local admin of the server we just create the user and continue
// no need to update additional attributes
$isGsEnabled = $this->config->getSystemValue('gs.enabled', false);
$isGsMaster = $this->config->getSystemValue('gss.mode', 'slave') === 'master';
$isGsMasterAdmin = in_array($uid, $this->config->getSystemValue('gss.master.admin', []));
if ($isGsEnabled && $isGsMaster && !$isGsMasterAdmin) {
$this->userBackend->createUserIfNotExists($uid);
return;
}
$userExists = $this->userManager->userExists($uid);
$autoProvisioningAllowed = $this->userBackend->autoprovisionAllowed();
if($userExists === true) {
if($autoProvisioningAllowed) {
$this->userBackend->updateAttributes($uid, $auth);
}
return;
}
if(!$userExists && !$autoProvisioningAllowed) {
// it is possible that the user was not logged in before and
// thus is not known to the original backend. A search can
// help with it and make the user known
$this->userManager->search($uid);
if($this->userManager->userExists($uid)) {
return;
}
throw new NoUserFoundException('Auto provisioning not allowed and user ' . $uid . ' does not exist');
} elseif(!$userExists && $autoProvisioningAllowed) {
$this->userBackend->createUserIfNotExists($uid, $auth);
$this->userBackend->updateAttributes($uid, $auth);
return;
}
if(!$this->userData->hasUidMappingAttribute()) {
throw new NoUserFoundException('IDP parameter for the UID not found. Possible parameters are: ' . json_encode(array_keys($auth)));
}
throw new NoUserFoundException('IDP parameter for the UID (' . $uidMapping . ') not found. Possible parameters are: ' . json_encode(array_keys($auth)));
if ($this->userData->getOriginalUid() === '') {
$this->logger->error('Uid is not a valid uid please check your attribute mapping', ['app' => $this->appName]);
throw new \InvalidArgumentException('No valid uid given, please check your attribute mapping.');
}
$uid = $this->userData->getEffectiveUid();
$userExists = $uid !== '';
// if this server acts as a global scale master and the user is not
// a local admin of the server we just create the user and continue
// no need to update additional attributes
$isGsEnabled = $this->config->getSystemValue('gs.enabled', false);
$isGsMaster = $this->config->getSystemValue('gss.mode', 'slave') === 'master';
$isGsMasterAdmin = in_array($uid, $this->config->getSystemValue('gss.master.admin', []));
if ($isGsEnabled && $isGsMaster && !$isGsMasterAdmin) {
$this->userBackend->createUserIfNotExists($this->userData->getOriginalUid());
return;
}
$autoProvisioningAllowed = $this->userBackend->autoprovisionAllowed();
if($userExists) {
if($autoProvisioningAllowed) {
$this->userBackend->updateAttributes($uid, $auth);
}
return;
}
$uid = $this->userData->getOriginalUid();
if(!$userExists && !$autoProvisioningAllowed) {
throw new NoUserFoundException('Auto provisioning not allowed and user ' . $uid . ' does not exist');
} elseif(!$userExists && $autoProvisioningAllowed) {
$this->userBackend->createUserIfNotExists($uid, $auth);
$this->userBackend->updateAttributes($uid, $auth);
return;
}
}
/**
@ -221,11 +212,9 @@ class SAMLController extends Controller {
}
$this->session->set('user_saml.samlUserData', $_SERVER);
try {
$this->autoprovisionIfPossible($this->session->get('user_saml.samlUserData'));
$user = $this->userManager->get($this->userBackend->getCurrentUserId());
if(!($user instanceof IUser)) {
throw new NoUserFoundException('User' . $this->userBackend->getCurrentUserId() . ' not valid or not found');
}
$this->userData->setAttributes($this->session->get('user_saml.samlUserData'));
$this->autoprovisionIfPossible();
$user = $this->userResolver->findExistingUser($this->userBackend->getCurrentUserId());
$user->updateLastLoginTimestamp();
} catch (NoUserFoundException $e) {
if ($e->getMessage()) {
@ -342,7 +331,8 @@ class SAMLController extends Controller {
// Check whether the user actually exists, if not redirect to an error page
// explaining the issue.
try {
$this->autoprovisionIfPossible($auth->getAttributes());
$this->userData->setAttributes($auth->getAttributes());
$this->autoprovisionIfPossible();
} catch (NoUserFoundException $e) {
$this->logger->error($e->getMessage(), ['app' => $this->appName]);
$response = new Http\RedirectResponse($this->urlGenerator->linkToRouteAbsolute('user_saml.SAML.notProvisioned'));
@ -358,14 +348,13 @@ class SAMLController extends Controller {
$this->session->set('user_saml.samlSessionIndex', $auth->getSessionIndex());
$this->session->set('user_saml.samlSessionExpiration', $auth->getSessionExpiration());
try {
$user = $this->userManager->get($this->userBackend->getCurrentUserId());
if (!($user instanceof IUser)) {
throw new \InvalidArgumentException('User "' . $this->userBackend->getCurrentUserId() . '" is not valid');
}
$user = $this->userResolver->findExistingUser($this->userBackend->getCurrentUserId());
$firstLogin = $user->updateLastLoginTimestamp();
if($firstLogin) {
if ($firstLogin) {
$this->userBackend->initializeHomeDir($user->getUID());
}
} catch (NoUserFoundException $e) {
throw new \InvalidArgumentException('User "' . $this->userBackend->getCurrentUserId() . '" is not valid');
} catch (\Exception $e) {
$this->logger->logException($e, ['app' => $this->appName]);
$response = new Http\RedirectResponse($this->urlGenerator->linkToRouteAbsolute('user_saml.SAML.notProvisioned'));

View file

@ -56,25 +56,20 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend {
private $settings;
/** @var ILogger */
private $logger;
/** @var UserData */
private $userData;
/**
* @param IConfig $config
* @param IURLGenerator $urlGenerator
* @param ISession $session
* @param IDBConnection $db
* @param IUserManager $userManager
* @param IGroupManager $groupManager
* @param SAMLSettings $settings
* @param ILogger $logger
*/
public function __construct(IConfig $config,
IURLGenerator $urlGenerator,
ISession $session,
IDBConnection $db,
IUserManager $userManager,
IGroupManager $groupManager,
SAMLSettings $settings,
ILogger $logger) {
public function __construct(
IConfig $config,
IURLGenerator $urlGenerator,
ISession $session,
IDBConnection $db,
IUserManager $userManager,
IGroupManager $groupManager,
SAMLSettings $settings,
ILogger $logger,
UserData $userData
) {
$this->config = $config;
$this->urlGenerator = $urlGenerator;
$this->session = $session;
@ -83,6 +78,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend {
$this->groupManager = $groupManager;
$this->settings = $settings;
$this->logger = $logger;
$this->userData = $userData;
}
/**
@ -393,10 +389,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend {
* @since 6.0.0
*/
public function isSessionActive() {
if($this->getCurrentUserId() !== '') {
return true;
}
return false;
return $this->session->get('user_saml.samlUserData') !== null;
}
/**
@ -441,9 +434,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend {
throw new \InvalidArgumentException('No valid uid given, please check your attribute mapping. Got uid: ' . $userData['uid']);
}
return $userData;
}
/**
@ -453,6 +444,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend {
* @return array
*/
private function formatUserData($attributes) {
$this->userData->setAttributes($attributes);
$result = ['formatted' => [], 'raw' => $attributes];
@ -481,12 +473,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend {
$result['formatted']['groups'] = null;
}
$prefix = $this->settings->getPrefix();
$uidMapping = $this->config->getAppValue('user_saml', $prefix . 'general-uid_mapping');
$result['formatted']['uid'] = '';
if (isset($attributes[$uidMapping])) {
$result['formatted']['uid'] = $attributes[$uidMapping][0];
}
$result['formatted']['uid'] = $this->userData->getEffectiveUid();
return $result;
}
@ -497,24 +484,21 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend {
* @since 6.0.0
*/
public function getCurrentUserId() {
$samlData = $this->session->get('user_saml.samlUserData');
$prefix = $this->settings->getPrefix();
$uidMapping = $this->config->getAppValue('user_saml', $prefix . 'general-uid_mapping', '');
$user = \OC::$server->getUserSession()->getUser();
if($uidMapping !== '' && isset($samlData[$uidMapping])) {
if(is_array($samlData[$uidMapping])) {
$uid = $samlData[$uidMapping][0];
} else {
$uid = $samlData[$uidMapping];
}
$uid = $this->testEncodedObjectGUID($uid);
if($this->userExists($uid)) {
$this->session->set('last-password-confirm', strtotime('+4 year', time()));
return $uid;
}
if($user instanceof IUser && $this->session->get('user_saml.samlUserData')) {
$uid = $user->getUID();
} else {
$this->userData->setAttributes($this->session->get('user_saml.samlUserData') ?? []);
$uid = $this->userData->getEffectiveUid();
}
if($uid !== '' && $this->userExists($uid)) {
$uid = $this->userData->testEncodedObjectGUID($uid);
$this->session->set('last-password-confirm', strtotime('+4 year', time()));
return $uid;
}
return '';
}
@ -696,52 +680,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend {
}
}
/**
* returns the plain text UUID if the provided $uid string is a
* base64-encoded binary string representing e.g. the objectGUID. Otherwise
*
*/
public function testEncodedObjectGUID(string $uid): string {
if (preg_match('/[^a-zA-Z0-9=+\/]/', $uid) !== 0) {
// certainly not encoded
return $uid;
}
$candidate = base64_decode($uid, false);
if($candidate === false) {
return $uid;
}
$candidate = $this->convertObjectGUID2Str($candidate);
// the regex only matches the structure of the UUID, not its semantic
// (i.e. version or variant) simply to be future compatible
if(preg_match('/^[a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8}$/i', $candidate) === 1) {
$uid = $candidate;
}
return $uid;
}
/**
* @see \OCA\User_LDAP\Access::convertObjectGUID2Str
*/
protected function convertObjectGUID2Str($oguid) {
$hex_guid = bin2hex($oguid);
$hex_guid_to_guid_str = '';
for($k = 1; $k <= 4; ++$k) {
$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
}
$hex_guid_to_guid_str .= '-';
for($k = 1; $k <= 2; ++$k) {
$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
}
$hex_guid_to_guid_str .= '-';
for($k = 1; $k <= 2; ++$k) {
$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
}
$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
return strtoupper($hex_guid_to_guid_str);
}
public function countUsers() {
$query = $this->db->getQueryBuilder();

150
lib/UserData.php Normal file
View file

@ -0,0 +1,150 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020 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\User_SAML;
use OCA\User_SAML\Exceptions\NoUserFoundException;
use OCP\IConfig;
class UserData {
private $uid;
/** @var array */
private $attributes;
/** @var UserResolver */
private $userResolver;
/** @var SAMLSettings */
private $samlSettings;
/** @var IConfig */
private $config;
public function __construct(UserResolver $userResolver, SAMLSettings $samlSettings, IConfig $config) {
$this->userResolver = $userResolver;
$this->samlSettings = $samlSettings;
$this->config = $config;
}
public function setAttributes(array $attributes): void {
$this->attributes = $attributes;
$this->uid = null; // clear the state in case
}
public function getAttributes(): array {
$this->assertIsInitialized();
return $this->attributes;
}
public function hasUidMappingAttribute(): bool {
$this->assertIsInitialized();
$prefix = $this->samlSettings->getPrefix();
$uidMapping = $this->config->getAppValue('user_saml', $prefix . 'general-uid_mapping');
return isset($this->attributes[$uidMapping]);
}
public function getOriginalUid(): string {
$this->assertIsInitialized();
return $this->extractSamlUserId();
}
public function getEffectiveUid(): string {
if($this->uid !== null) {
return $this->uid;
}
$this->assertIsInitialized();
try {
$uid = $this->extractSamlUserId();
$uid = $this->testEncodedObjectGUID($uid);
$uid = $this->userResolver->findExistingUserId($uid, true);
$this->uid = $uid;
} catch (NoUserFoundException $e) {
return '';
}
return $uid;
}
protected function extractSamlUserId(): string {
$prefix = $this->samlSettings->getPrefix();
$uidMapping = $this->config->getAppValue('user_saml', $prefix . 'general-uid_mapping');
if(isset($this->attributes[$uidMapping])) {
if (is_array($this->attributes[$uidMapping])) {
return trim($this->attributes[$uidMapping][0]);
} else {
return trim($this->attributes[$uidMapping]);
}
}
return '';
}
/**
* returns the plain text UUID if the provided $uid string is a
* base64-encoded binary string representing e.g. the objectGUID. Otherwise
*
*/
public function testEncodedObjectGUID(string $uid): string {
if (preg_match('/[^a-zA-Z0-9=+\/]/', $uid) !== 0) {
// certainly not encoded
return $uid;
}
$candidate = base64_decode($uid, true);
if($candidate === false) {
return $uid;
}
$candidate = $this->convertObjectGUID2Str($candidate);
// the regex only matches the structure of the UUID, not its semantic
// (i.e. version or variant) simply to be future compatible
if(preg_match('/^[a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8}$/i', $candidate) === 1) {
$uid = $candidate;
}
return $uid;
}
/**
* @see \OCA\User_LDAP\Access::convertObjectGUID2Str
*/
protected function convertObjectGUID2Str($oguid): string {
$hex_guid = bin2hex($oguid);
$hex_guid_to_guid_str = '';
for($k = 1; $k <= 4; ++$k) {
$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
}
$hex_guid_to_guid_str .= '-';
for($k = 1; $k <= 2; ++$k) {
$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
}
$hex_guid_to_guid_str .= '-';
for($k = 1; $k <= 2; ++$k) {
$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
}
$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
return strtoupper($hex_guid_to_guid_str);
}
protected function assertIsInitialized() {
if($this->attributes === null) {
throw new \LogicException('UserData have to be initialized with setAttributes first');
}
}
}

111
lib/UserResolver.php Normal file
View file

@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020 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\User_SAML;
use OCA\User_SAML\Exceptions\NoUserFoundException;
use OCP\IUser;
use OCP\IUserManager;
class UserResolver {
/** @var IUserManager */
private $userManager;
public function __construct(IUserManager $userManager) {
$this->userManager = $userManager;
}
/**
* @throws NoUserFoundException
*/
public function findExistingUserId(string $rawUidCandidate, bool $force = false): string {
if($force) {
$this->ensureUser($rawUidCandidate);
}
if($this->userManager->userExists($rawUidCandidate)) {
return $rawUidCandidate;
}
try {
$sanitized = $this->sanitizeUserIdCandidate($rawUidCandidate);
} catch(\InvalidArgumentException $e) {
$sanitized = '';
}
if($this->userManager->userExists($sanitized)) {
return $sanitized;
}
throw new NoUserFoundException('User' . $rawUidCandidate . ' not valid or not found');
}
/**
* @throws NoUserFoundException
*/
public function findExistingUser(string $rawUidCandidate): IUser {
$uid = $this->findExistingUserId($rawUidCandidate);
$user = $this->userManager->get($uid);
if($user === null) {
throw new NoUserFoundException('User' . $rawUidCandidate . ' not valid or not found');
}
return $user;
}
public function userExists(string $uid, bool $force = false): bool {
try {
$this->findExistingUserId($uid, $force);
return true;
} catch(NoUserFoundException $e) {
return false;
}
}
protected function ensureUser($search) {
$this->userManager->search($search);
}
/**
* @throws \InvalidArgumentException
*/
protected function sanitizeUserIdCandidate(string $rawUidCandidate): string {
//FIXME: adjusted copy of LDAP's Access::sanitizeUsername(), should go to API
$sanitized = trim($rawUidCandidate);
// Transliteration to ASCII
$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $sanitized);
if($transliterated !== false) {
// depending on system config iconv can work or not
$sanitized = $transliterated;
}
// Replacements
$sanitized = str_replace(' ', '_', $sanitized);
// Every remaining disallowed characters will be removed
$sanitized = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $sanitized);
if($sanitized === '') {
throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
}
return $sanitized;
}
}

View file

@ -25,6 +25,7 @@ use Test\TestCase;
class Test extends TestCase {
public function testFile() {
$dir =__DIR__;
$routes = require_once __DIR__ . '/../../../appinfo/routes.php';
$expected = [

View file

@ -22,8 +22,11 @@
namespace OCA\User_SAML\Tests\Controller;
use OCA\User_SAML\Controller\SAMLController;
use OCA\User_SAML\Exceptions\NoUserFoundException;
use OCA\User_SAML\SAMLSettings;
use OCA\User_SAML\UserBackend;
use OCA\User_SAML\UserData;
use OCA\User_SAML\UserResolver;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\IConfig;
@ -33,13 +36,16 @@ use OCP\IRequest;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\Security\ICrypto;
use PHPUnit\Framework\MockObject\MockObject;
use OCP\Security\ICrypto;
use Test\TestCase;
class SAMLControllerTest extends TestCase {
/** @var UserResolver|\PHPUnit\Framework\MockObject\MockObject */
protected $userResolver;
/** @var UserData|\PHPUnit\Framework\MockObject\MockObject */
private $userData;
/** @var IRequest|\PHPUnit_Framework_MockObject_MockObject */
private $request;
/** @var ISession|\PHPUnit_Framework_MockObject_MockObject */
@ -54,8 +60,6 @@ class SAMLControllerTest extends TestCase {
private $config;
/** @var IURLGenerator|\PHPUnit_Framework_MockObject_MockObject */
private $urlGenerator;
/** @var IUserManager|\PHPUnit_Framework_MockObject_MockObject */
private $userManager;
/** @var ILogger|\PHPUnit_Framework_MockObject_MockObject */
private $logger;
/** @var IL10N|\PHPUnit_Framework_MockObject_MockObject */
@ -73,14 +77,12 @@ class SAMLControllerTest extends TestCase {
$this->userSession = $this->createMock(IUserSession::class);
$this->samlSettings = $this->createMock(SAMLSettings::class);
$this->userBackend = $this->createMock(UserBackend::class);
$this->userBackend->expects($this->any())
->method('testEncodedObjectGUID')
->willReturnArgument(0);
$this->config = $this->createMock(IConfig::class);
$this->urlGenerator = $this->createMock(IURLGenerator::class);
$this->userManager = $this->createMock(IUserManager::class);
$this->logger = $this->createMock(ILogger::class);
$this->l = $this->createMock(IL10N::class);
$this->userResolver = $this->createMock(UserResolver::class);
$this->userData = $this->createMock(UserData::class);
$this->crypto = $this->createMock(ICrypto::class);
$this->l->expects($this->any())->method('t')->willReturnCallback(
@ -103,9 +105,10 @@ class SAMLControllerTest extends TestCase {
$this->userBackend,
$this->config,
$this->urlGenerator,
$this->userManager,
$this->logger,
$this->l,
$this->userResolver,
$this->userData,
$this->crypto
);
@ -124,334 +127,202 @@ class SAMLControllerTest extends TestCase {
$this->samlController->login(1);
}
public function testLoginWithEnvVariableAndNotExistingUidInSettingsArray() {
$this->config
->expects($this->at(0))
public function samlUserDataProvider() {
$userNotExisting = 0;
$userExisting = 1;
$userLazyExisting = 2;
$apDisabled = 0;
$apEnabled = 1;
$apEnabledUnsuccessful = 2;
return [
[ # 0 - Not existing uid in settings array
[
'foo' => 'bar',
'bar' => 'foo',
],
'https://nextcloud.com/notProvisioned/',
$userNotExisting,
$apDisabled
],
[ # 1 - existing user
[
'foo' => 'bar',
'bar' => 'foo',
'uid' => 'MyUid',
],
'https://nextcloud.com/absolute/',
$userExisting,
$apDisabled
],
[ # 2 - existing user and uid attribute in array
[
'foo' => 'bar',
'bar' => 'foo',
'uid' => ['MyUid'],
],
'https://nextcloud.com/absolute/',
$userExisting,
$apDisabled
],
[ # 3 - Not existing user with provisioning
[
'foo' => 'bar',
'bar' => 'foo',
'uid' => 'MyUid',
],
'https://nextcloud.com/absolute/',
$userNotExisting,
$apEnabled
],
[ # 4 - Not existing user with malfunctioning backend
[
'foo' => 'bar',
'bar' => 'foo',
'uid' => 'MyUid',
],
'https://nextcloud.com/notProvisioned/',
$userNotExisting,
$apEnabledUnsuccessful
],
[ # 5 - Not existing user without provisioning
[
'foo' => 'bar',
'bar' => 'foo',
'uid' => 'MyUid',
],
'https://nextcloud.com/notProvisioned/',
$userNotExisting,
$apDisabled
],
[ # 6 - Not yet mapped user without provisioning
[
'foo' => 'bar',
'bar' => 'foo',
'uid' => 'MyUid',
],
'https://nextcloud.com/absolute/',
$userLazyExisting,
$apDisabled
],
];
}
/**
* @dataProvider samlUserDataProvider
*/
public function testLoginWithEnvVariable(array $samlUserData, string $redirect, int $userState, int $autoProvision) {
$this->config->expects($this->any())
->method('getAppValue')
->with('user_saml', 'type')
->willReturn('environment-variable');
->willReturnCallback(function (string $app, string $key) {
if($app === 'user_saml') {
if($key === 'type') {
return 'environment-variable';
}
if($key === 'general-uid_mapping') {
return 'uid';
}
}
return null;
});
$this->session
->expects($this->once())
->method('get')
->with('user_saml.samlUserData')
->willReturn([
'foo' => 'bar',
'bar' => 'foo',
]);
$this->config
->expects($this->at(1))
->method('getAppValue')
->with('user_saml', 'general-uid_mapping')
->willReturn('uid');
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
->with('user_saml.SAML.notProvisioned')
->willReturn('https://nextcloud.com/notProvisioned/');
->willReturn($samlUserData);
$expected = new RedirectResponse('https://nextcloud.com/notProvisioned/');
$this->userData
->expects($this->once())
->method('setAttributes')
->with($samlUserData);
$this->userData
->expects($this->any())
->method('getAttributes')
->willReturn($samlUserData);
$this->userData
->expects($this->any())
->method('hasUidMappingAttribute')
->willReturn(isset($samlUserData['uid']));
$this->userData
->expects(isset($samlUserData['uid']) ? $this->any() : $this->never())
->method('getOriginalUid')
->willReturn('MyUid');
$this->userData
->expects($this->any())
->method('getEffectiveUid')
->willReturn($userState > 0 ? 'MyUid' : '');
if(strpos($redirect, 'notProvisioned') !== false) {
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
->with('user_saml.SAML.notProvisioned')
->willReturn($redirect);
} else {
$this->urlGenerator
->expects($this->once())
->method('getAbsoluteURL')
->willReturn($redirect);
}
$this->userResolver
->expects($this->any())
->method('userExists')
->with('MyUid')
->willReturn($userState === 1);
if(isset($samlUserData['uid']) && !($userState === 0 && $autoProvision === 0)) {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
$im = $this->userResolver
->expects($this->once())
->method('findExistingUser')
->with('MyUid');
if($autoProvision < 2) {
$im->willReturn($user);
} else {
$im->willThrowException(new NoUserFoundException());
}
$user
->expects($this->exactly((int)($autoProvision < 2)))
->method('updateLastLoginTimestamp');
if($userState === 0) {
$this->userResolver
->expects($this->any())
->method('findExistingUserId')
->with('MyUid', true)
->willThrowException(new NoUserFoundException());
} else if($userState === 2) {
$this->userResolver
->expects($this->any())
->method('findExistingUserId')
->with('MyUid', true)
->willReturn('MyUid');
}
}
$this->userBackend
->expects($this->any())
->method('getCurrentUserId')
->willReturn(isset($samlUserData['uid']) ? 'MyUid' : '');
$this->userBackend
->expects($autoProvision > 0 ? $this->once() : $this->any())
->method('autoprovisionAllowed')
->willReturn($autoProvision > 0);
$this->userBackend
->expects($this->exactly(min(1, $autoProvision)))
->method('createUserIfNotExists')
->with('MyUid');
$expected = new RedirectResponse($redirect);
$result = $this->samlController->login(1);
$this->assertEquals($expected, $result);
}
public function testLoginWithEnvVariableAndExistingUser() {
$this->config
->expects($this->at(0))
->method('getAppValue')
->with('user_saml', 'type')
->willReturn('environment-variable');
$this->session
->expects($this->once())
->method('get')
->with('user_saml.samlUserData')
->willReturn([
'foo' => 'bar',
'uid' => 'MyUid',
'bar' => 'foo',
]);
$this->config
->expects($this->at(1))
->method('getAppValue')
->with('user_saml', 'general-uid_mapping')
->willReturn('uid');
$this->userManager
->expects($this->once())
->method('userExists')
->with('MyUid')
->willReturn(true);
$this->urlGenerator
->expects($this->once())
->method('getAbsoluteURL')
->with('/')
->willReturn('https://nextcloud.com/absolute/');
$this->userBackend
->expects($this->any())
->method('getCurrentUserId')
->willReturn('MyUid');
/** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */
$user = $this->createMock(IUser::class);
$this->userManager
->expects($this->once())
->method('get')
->with('MyUid')
->willReturn($user);
$user
->expects($this->once())
->method('updateLastLoginTimestamp');
$expected = new RedirectResponse('https://nextcloud.com/absolute/');
$this->assertEquals($expected, $this->samlController->login(1));
}
public function testLoginWithEnvVariableAndExistingUserAndArray() {
$this->config
->expects($this->at(0))
->method('getAppValue')
->with('user_saml', 'type')
->willReturn('environment-variable');
$this->session
->expects($this->once())
->method('get')
->with('user_saml.samlUserData')
->willReturn([
'foo' => 'bar',
'uid' => ['MyUid'],
'bar' => 'foo',
]);
$this->config
->expects($this->at(1))
->method('getAppValue')
->with('user_saml', 'general-uid_mapping')
->willReturn('uid');
$this->userManager
->expects($this->once())
->method('userExists')
->with('MyUid')
->willReturn(true);
$this->userBackend
->expects($this->once())
->method('getCurrentUserId')
->willReturn('MyUid');
/** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */
$user = $this->createMock(IUser::class);
$this->userManager
->expects($this->once())
->method('get')
->with('MyUid')
->willReturn($user);
$user
->expects($this->once())
->method('updateLastLoginTimestamp');
$this->urlGenerator
->expects($this->once())
->method('getAbsoluteURL')
->with('/')
->willReturn('https://nextcloud.com/absolute/');
$expected = new RedirectResponse('https://nextcloud.com/absolute/');
$this->assertEquals($expected, $this->samlController->login(1));
}
public function testLoginWithEnvVariableAndNotExistingUserWithProvisioning() {
$this->config
->expects($this->at(0))
->method('getAppValue')
->with('user_saml', 'type')
->willReturn('environment-variable');
$this->session
->expects($this->once())
->method('get')
->with('user_saml.samlUserData')
->willReturn([
'foo' => 'bar',
'uid' => 'MyUid',
'bar' => 'foo',
]);
$this->config
->expects($this->at(1))
->method('getAppValue')
->with('user_saml', 'general-uid_mapping')
->willReturn('uid');
$this->userManager
->expects($this->once())
->method('userExists')
->with('MyUid')
->willReturn(false);
$this->urlGenerator
->expects($this->once())
->method('getAbsoluteURL')
->with('/')
->willReturn('https://nextcloud.com/absolute/');
$this->userBackend
->expects($this->once())
->method('autoprovisionAllowed')
->willReturn(true);
$this->userBackend
->expects($this->once())
->method('createUserIfNotExists')
->with('MyUid');
$this->userBackend
->expects($this->once())
->method('getCurrentUserId')
->willReturn('MyUid');
/** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */
$user = $this->createMock(IUser::class);
$this->userManager
->expects($this->once())
->method('get')
->with('MyUid')
->willReturn($user);
$user
->expects($this->once())
->method('updateLastLoginTimestamp');
$expected = new RedirectResponse('https://nextcloud.com/absolute/');
$this->assertEquals($expected, $this->samlController->login(1));
}
public function testLoginWithEnvVariableAndNotExistingUserWithMalfunctioningBackend() {
$this->config
->expects($this->at(0))
->method('getAppValue')
->with('user_saml', 'type')
->willReturn('environment-variable');
$this->session
->expects($this->once())
->method('get')
->with('user_saml.samlUserData')
->willReturn([
'foo' => 'bar',
'uid' => 'MyUid',
'bar' => 'foo',
]);
$this->config
->expects($this->at(1))
->method('getAppValue')
->with('user_saml', 'general-uid_mapping')
->willReturn('uid');
$this->userManager
->expects($this->once())
->method('userExists')
->with('MyUid')
->willReturn(false);
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
->with('user_saml.SAML.notProvisioned')
->willReturn('https://nextcloud.com/notprovisioned/');
$this->userBackend
->expects($this->once())
->method('autoprovisionAllowed')
->willReturn(true);
$this->userBackend
->expects($this->once())
->method('createUserIfNotExists')
->with('MyUid');
$this->userBackend
->expects($this->exactly(2))
->method('getCurrentUserId')
->willReturn('MyUid');
$this->userManager
->expects($this->once())
->method('get')
->with('MyUid')
->willReturn(null);
$expected = new RedirectResponse('https://nextcloud.com/notprovisioned/');
$this->assertEquals($expected, $this->samlController->login(1));
}
public function testLoginWithEnvVariableAndNotExistingUserWithoutProvisioning() {
$this->config
->expects($this->at(0))
->method('getAppValue')
->with('user_saml', 'type')
->willReturn('environment-variable');
$this->session
->expects($this->once())
->method('get')
->with('user_saml.samlUserData')
->willReturn([
'foo' => 'bar',
'uid' => 'MyUid',
'bar' => 'foo',
]);
$this->config
->expects($this->at(1))
->method('getAppValue')
->with('user_saml', 'general-uid_mapping')
->willReturn('uid');
$this->userManager
->expects($this->any())
->method('userExists')
->with('MyUid')
->willReturn(false);
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
->with('user_saml.SAML.notProvisioned')
->willReturn('https://nextcloud.com/notprovisioned/');
$this->userBackend
->expects($this->once())
->method('autoprovisionAllowed')
->willReturn(false);
$expected = new RedirectResponse('https://nextcloud.com/notprovisioned/');
$this->assertEquals($expected, $this->samlController->login(1));
}
public function testLoginWithEnvVariableAndNotYetMappedUserWithoutProvisioning() {
$this->config
->expects($this->at(0))
->method('getAppValue')
->with('user_saml', 'type')
->willReturn('environment-variable');
$this->session
->expects($this->once())
->method('get')
->with('user_saml.samlUserData')
->willReturn([
'foo' => 'bar',
'uid' => 'MyUid',
'bar' => 'foo',
]);
$this->config
->expects($this->at(1))
->method('getAppValue')
->with('user_saml', 'general-uid_mapping')
->willReturn('uid');
$this->userManager
->expects($this->exactly(2))
->method('userExists')
->with('MyUid')
->willReturnOnConsecutiveCalls(false, true);
$this->userManager
->expects($this->once())
->method('get')
->with('MyUid')
->willReturn($this->createMock(IUser::class));
$this->urlGenerator
->expects($this->once())
->method('getAbsoluteUrl')
->with('/')
->willReturn('https://nextcloud.com/absolute/');
$this->urlGenerator
->expects($this->never())
->method('linkToRouteAbsolute');
$this->userBackend
->expects($this->once())
->method('autoprovisionAllowed')
->willReturn(false);
$this->userBackend
->expects($this->once())
->method('getCurrentUserId')
->willReturn('MyUid');
$expected = new RedirectResponse('https://nextcloud.com/absolute/');
$this->assertEquals($expected, $this->samlController->login(1));
}
public function testNotProvisioned() {
$expected = new TemplateResponse('user_saml', 'notProvisioned', [], 'guest');
$this->assertEquals($expected, $this->samlController->notProvisioned());

View file

@ -23,6 +23,7 @@ namespace OCA\User_SAML\Tests\Settings;
use OCA\User_SAML\SAMLSettings;
use OCA\User_SAML\UserBackend;
use OCA\User_SAML\UserData;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IGroup;
@ -35,6 +36,8 @@ use OCP\IUserManager;
use Test\TestCase;
class UserBackendTest extends TestCase {
/** @var UserData|\PHPUnit\Framework\MockObject\MockObject */
private $userData;
/** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */
private $config;
/** @var IURLGenerator|\PHPUnit_Framework_MockObject_MockObject */
@ -65,6 +68,7 @@ class UserBackendTest extends TestCase {
$this->groupManager = $this->createMock(IGroupManager::class);
$this->SAMLSettings = $this->getMockBuilder(SAMLSettings::class)->disableOriginalConstructor()->getMock();
$this->logger = $this->createMock(ILogger::class);
$this->userData = $this->createMock(UserData::class);
}
public function getMockedBuilder(array $mockedFunctions = []) {
@ -78,7 +82,8 @@ class UserBackendTest extends TestCase {
$this->userManager,
$this->groupManager,
$this->SAMLSettings,
$this->logger
$this->logger,
$this->userData,
])
->setMethods($mockedFunctions)
->getMock();
@ -91,7 +96,8 @@ class UserBackendTest extends TestCase {
$this->userManager,
$this->groupManager,
$this->SAMLSettings,
$this->logger
$this->logger,
$this->userData
);
}
}
@ -281,27 +287,4 @@ class UserBackendTest extends TestCase {
$this->userBackend->updateAttributes('ExistingUser', ['email' => 'new@example.com', 'displayname' => 'New Displayname', 'quota' => '']);
}
public function objectGuidProvider() {
return [
['Joey No Conversion', 'Joey No Conversion'],
['no@convers.ion', 'no@convers.ion'],
['a0aa9ed8-6b48-1034-8ad7-8fb78330d80a', 'a0aa9ed8-6b48-1034-8ad7-8fb78330d80a'],
['EDE70D16-B9D5-4E9A-ABD7-614D17246E3F', 'EDE70D16-B9D5-4E9A-ABD7-614D17246E3F'],
['Tm8gY29udmVyc2lvbgo=', 'Tm8gY29udmVyc2lvbgo='],
['ASfjU2OYEd69ZgAVF4pePA==', '53E32701-9863-DE11-BD66-0015178A5E3C'],
['aaabbbcc@aa.bbbccdd.eee.ff', 'aaabbbcc@aa.bbbccdd.eee.ff'],
['aaabbbcccaa.bbbccdddeee', 'aaabbbcccaa.bbbccdddeee']
];
}
/**
* @dataProvider objectGuidProvider
*/
public function testTestEncodedObjectGUID(string $input, string $expectation) {
$this->getMockedBuilder(['getDisplayName', 'setDisplayName']);
$uid = $this->userBackend->testEncodedObjectGUID($input);
$this->assertSame($expectation, $uid);
}
}

View file

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020 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\User_SAML\Tests;
use OCA\User_SAML\SAMLSettings;
use OCA\User_SAML\UserData;
use OCA\User_SAML\UserResolver;
use OCP\IConfig;
use Test\TestCase;
class UserDataTest extends TestCase {
/** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
protected $config;
/** @var UserResolver|\PHPUnit\Framework\MockObject\MockObject */
protected $resolver;
/** @var SAMLSettings|\PHPUnit\Framework\MockObject\MockObject */
protected $samlSettings;
/** @var UserData */
protected $userData;
public function setUp(): void {
parent::setUp();
$this->resolver = $this->createMock(UserResolver::class);
$this->samlSettings = $this->createMock(SAMLSettings::class);
$this->config = $this->createMock(IConfig::class);
$this->userData = new UserData($this->resolver, $this->samlSettings, $this->config);
}
public function objectGuidProvider() {
return [
['Joey No Conversion', 'Joey No Conversion'],
['no@convers.ion', 'no@convers.ion'],
['a0aa9ed8-6b48-1034-8ad7-8fb78330d80a', 'a0aa9ed8-6b48-1034-8ad7-8fb78330d80a'],
['EDE70D16-B9D5-4E9A-ABD7-614D17246E3F', 'EDE70D16-B9D5-4E9A-ABD7-614D17246E3F'],
['Tm8gY29udmVyc2lvbgo=', 'Tm8gY29udmVyc2lvbgo='],
['ASfjU2OYEd69ZgAVF4pePA==', '53E32701-9863-DE11-BD66-0015178A5E3C'],
['aaabbbcc@aa.bbbccdd.eee.ff', 'aaabbbcc@aa.bbbccdd.eee.ff'],
['aaabbbcccaa.bbbccdddeee', 'aaabbbcccaa.bbbccdddeee']
];
}
/**
* @dataProvider objectGuidProvider
*/
public function testTestEncodedObjectGUID(string $input, string $expectation) {
$uid = $this->invokePrivate($this->userData, 'testEncodedObjectGUID', [$input]);
$this->assertSame($expectation, $uid);
}
}