Refactor authentication system (#2602)

Make auth configuration available via UI, remove FOSUserBundle and SAML-Bundle dependency
This commit is contained in:
Kevin Papst
2021-06-10 15:34:13 +02:00
committed by GitHub
parent 286b63e2c8
commit 7f20cb045c
155 changed files with 5590 additions and 1802 deletions

View File

@@ -11,8 +11,10 @@ namespace App\Tests\Controller\Auth;
use App\Configuration\SystemConfiguration;
use App\Controller\Auth\SamlController;
use App\Saml\SamlAuthFactory;
use App\Tests\Configuration\TestConfigLoader;
use App\Tests\Mocks\Saml\SamlAuthFactory;
use App\Tests\Mocks\Saml\SamlAuthFactoryFactory;
use OneLogin\Saml2\Auth;
use PHPUnit\Framework\TestCase;
use PHPUnit\Util\Xml;
use Symfony\Component\HttpFoundation\Request;
@@ -47,9 +49,9 @@ class SamlControllerTest extends TestCase
];
}
protected function getAuth()
protected function getAuth(): Auth
{
return (new SamlAuthFactory($this))->create();
return (new SamlAuthFactoryFactory($this))->create()->create();
}
protected function getSystemConfiguration(bool $activated = true)
@@ -62,8 +64,9 @@ class SamlControllerTest extends TestCase
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('You must configure the check path in your firewall.');
$oauth = $this->getAuth();
$sut = new SamlController($oauth, $this->getSystemConfiguration());
$factory = $this->getMockBuilder(SamlAuthFactory::class)->disableOriginalConstructor()->getMock();
$sut = new SamlController($factory, $this->getSystemConfiguration());
$sut->assertionConsumerServiceAction();
}
@@ -72,8 +75,9 @@ class SamlControllerTest extends TestCase
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('You must configure the logout path in your firewall.');
$oauth = $this->getAuth();
$sut = new SamlController($oauth, $this->getSystemConfiguration());
$factory = $this->getMockBuilder(SamlAuthFactory::class)->disableOriginalConstructor()->getMock();
$sut = new SamlController($factory, $this->getSystemConfiguration());
$sut->logoutAction();
}
@@ -104,7 +108,11 @@ class SamlControllerTest extends TestCase
EOD;
$oauth = $this->getAuth();
$sut = new SamlController($oauth, $this->getSystemConfiguration());
$factory = $this->getMockBuilder(SamlAuthFactory::class)->disableOriginalConstructor()->getMock();
$factory->expects($this->once())->method('create')->willReturn($oauth);
$sut = new SamlController($factory, $this->getSystemConfiguration());
$result = $sut->metadataAction();
self::assertInstanceOf(Response::class, $result);
@@ -126,8 +134,9 @@ EOD;
$request->setSession($this->createMock(SessionInterface::class));
$request->attributes->set(Security::AUTHENTICATION_ERROR, new \Exception('My test error'));
$oauth = $this->getAuth();
$sut = new SamlController($oauth, $this->getSystemConfiguration());
$factory = $this->getMockBuilder(SamlAuthFactory::class)->disableOriginalConstructor()->getMock();
$sut = new SamlController($factory, $this->getSystemConfiguration());
$sut->loginAction($request);
}
@@ -136,7 +145,9 @@ EOD;
$this->expectException(NotFoundHttpException::class);
$this->expectExceptionMessage('SAML deactivated');
$sut = new SamlController($this->getAuth(), $this->getSystemConfiguration(false));
$factory = $this->getMockBuilder(SamlAuthFactory::class)->disableOriginalConstructor()->getMock();
$sut = new SamlController($factory, $this->getSystemConfiguration(false));
$sut->loginAction(new Request());
}
@@ -145,7 +156,9 @@ EOD;
$this->expectException(NotFoundHttpException::class);
$this->expectExceptionMessage('SAML deactivated');
$sut = new SamlController($this->getAuth(), $this->getSystemConfiguration(false));
$factory = $this->getMockBuilder(SamlAuthFactory::class)->disableOriginalConstructor()->getMock();
$sut = new SamlController($factory, $this->getSystemConfiguration(false));
$sut->metadataAction();
}
@@ -154,7 +167,9 @@ EOD;
$this->expectException(NotFoundHttpException::class);
$this->expectExceptionMessage('SAML deactivated');
$sut = new SamlController($this->getAuth(), $this->getSystemConfiguration(false));
$factory = $this->getMockBuilder(SamlAuthFactory::class)->disableOriginalConstructor()->getMock();
$sut = new SamlController($factory, $this->getSystemConfiguration(false));
$sut->logoutAction();
}
@@ -163,7 +178,9 @@ EOD;
$this->expectException(NotFoundHttpException::class);
$this->expectExceptionMessage('SAML deactivated');
$sut = new SamlController($this->getAuth(), $this->getSystemConfiguration(false));
$factory = $this->getMockBuilder(SamlAuthFactory::class)->disableOriginalConstructor()->getMock();
$sut = new SamlController($factory, $this->getSystemConfiguration(false));
$sut->assertionConsumerServiceAction();
}
}

View File

@@ -10,8 +10,10 @@
namespace App\Tests\Controller;
use App\DataFixtures\UserFixtures;
use App\Entity\Configuration;
use App\Entity\User;
use App\Repository\ConfigurationRepository;
use App\Repository\UserRepository;
use App\Tests\KernelTestTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
@@ -33,6 +35,43 @@ abstract class ControllerBaseTest extends WebTestCase
parent::tearDown();
}
/**
* Using a special container, to access private services as well.
*
* @param string $service
* @return object|null
* @see https://symfony.com/blog/new-in-symfony-4-1-simpler-service-testing
*/
protected function getPrivateService(string $service)
{
return self::$container->get($service);
}
protected function loadUserFromDatabase(string $username)
{
$container = self::$kernel->getContainer();
/** @var UserRepository $userRepository */
$userRepository = $container->get('doctrine')->getRepository(User::class);
$user = $userRepository->loadUserByUsername($username);
self::assertInstanceOf(User::class, $user);
return $user;
}
protected function setSystemConfiguration(string $name, $value): void
{
$repository = static::$kernel->getContainer()->get(ConfigurationRepository::class);
$entity = $repository->findOneBy(['name' => $name]);
if ($entity === null) {
$entity = new Configuration();
$entity->setName($name);
}
$entity->setValue($value);
$repository->saveConfiguration($entity);
$this->clearConfigCache();
}
protected function clearConfigCache()
{
/** @var ConfigurationRepository $repository */

View File

@@ -0,0 +1,80 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\Controller\Security;
use App\Tests\Controller\ControllerBaseTest;
/**
* @group integration
*/
class PasswordResetControllerTest extends ControllerBaseTest
{
private function testResetActionWithDeactivatedFeature(string $route, string $method = 'GET')
{
$client = self::createClient();
$this->setSystemConfiguration('user.password_reset', false);
$this->request($client, $route, $method);
$this->assertRouteNotFound($client);
}
public function testResetRequestWithDeactivatedFeature()
{
$this->testResetActionWithDeactivatedFeature('/resetting/request');
}
public function testSendEmailRequestWithDeactivatedFeature()
{
$this->testResetActionWithDeactivatedFeature('/resetting/send-email', 'POST');
}
public function testCheckEmailWithDeactivatedFeature()
{
$this->testResetActionWithDeactivatedFeature('/resetting/check-email');
}
public function testResetWithDeactivatedFeature()
{
$this->testResetActionWithDeactivatedFeature('/resetting/reset/1234567890');
}
public function testResetRequestPageIsRendered()
{
$client = self::createClient();
$this->setSystemConfiguration('user.password_reset', true);
$this->request($client, '/resetting/request');
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());
$content = $response->getContent();
$this->assertStringContainsString('<title>Kimai Time Tracking</title>', $content);
$this->assertStringContainsString('Reset your password', $content);
$this->assertStringContainsString('<form action="/en/resetting/send-email" method="POST" class="fos_user_resetting_request">', $content);
$this->assertStringContainsString('<input type="text"', $content);
$this->assertStringContainsString('id="username" name="username" required="required"', $content);
$this->assertStringContainsString('>Reset your password</button>', $content);
$form = $client->getCrawler()->filter('form.fos_user_resetting_request')->form();
$client->submit($form, [
'username' => 'john_user',
]);
$this->assertIsRedirect($client, $this->createUrl('/resetting/check-email?username=john_user'));
$client->followRedirect();
$this->assertTrue($client->getResponse()->isSuccessful());
$user = $this->loadUserFromDatabase('john_user');
$token = $user->getConfirmationToken();
$this->request($client, '/resetting/reset/' . $token);
$this->assertTrue($client->getResponse()->isSuccessful());
}
}

View File

@@ -0,0 +1,120 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\Controller\Security;
use App\Controller\Security\SecurityController;
use App\Tests\Controller\ControllerBaseTest;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
/**
* This test makes sure the login and registration work as expected.
* The logic is located in the FOSUserBundle and already tested, but we use a different layout.
*
* @group integration
*/
class SecurityControllerTest extends ControllerBaseTest
{
public function testRootUrlIsRedirectedToLogin()
{
$client = self::createClient();
$client->request('GET', '/');
$this->assertIsRedirect($client, $this->createUrl('/homepage'));
$client->followRedirect();
$this->assertIsRedirect($client, $this->createUrl('/login'));
}
public function testLoginPageIsRendered()
{
$client = self::createClient();
$this->request($client, '/login');
$response = $client->getResponse();
$this->assertTrue($client->getResponse()->isSuccessful());
$content = $response->getContent();
$this->assertStringContainsString('<title>Kimai Time Tracking</title>', $content);
$this->assertStringContainsString('<form action="/en/login_check" method="post">', $content);
$this->assertStringContainsString('<input type="text" name="_username"', $content);
$this->assertStringContainsString('<input name="_password" type="password"', $content);
$this->assertStringContainsString('<input id="remember_me" name="_remember_me" type="checkbox"', $content);
$this->assertStringContainsString('">Login</button>', $content);
$this->assertStringContainsString('<input type="hidden" name="_csrf_token" value="', $content);
$this->assertStringNotContainsString('<a href="/en/register/"', $content);
$this->assertStringNotContainsString('Register a new account', $content);
}
public function testLoginPositive()
{
$client = self::createClient();
$this->request($client, '/login');
$this->assertTrue($client->getResponse()->isSuccessful());
$form = $client->getCrawler()->filter('body form')->form();
$client->submit($form, [
'_username' => 'susan_super',
'_password' => 'kitten'
]);
$this->assertIsRedirect($client); // redirect to root URL
$client->followRedirect();
$this->assertIsRedirect($client, '/homepage'); // redirect to homepage
$client->followRedirect();
$this->assertIsRedirect($client, '/timesheet/'); // redirect to configured start page
$client->followRedirect();
$this->assertTrue($client->getResponse()->isSuccessful());
}
public function testLoginNegative()
{
$client = self::createClient();
$this->request($client, '/login');
$this->assertTrue($client->getResponse()->isSuccessful());
$form = $client->getCrawler()->filter('body form')->form();
$client->submit($form, [
'_username' => 'susan_super',
'_password' => '1234567890'
]);
$this->assertIsRedirect($client); // redirect to root URL
$client->followRedirect();
$this->assertTrue($client->getResponse()->isSuccessful());
self::assertStringContainsString('<div class="alert alert-danger">Invalid credentials.</div>', $client->getResponse()->getContent());
}
public function testCheckAction()
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('You must configure the check path to be handled by the firewall using form_login in your security firewall configuration.');
$client = self::createClient(); // just to bootstrap the container
$csrf = $this->createMock(CsrfTokenManagerInterface::class);
$sut = new SecurityController($csrf);
$sut->checkAction();
}
public function testLogoutAction()
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('You must activate the logout in your security firewall configuration.');
$client = self::createClient(); // just to bootstrap the container
$csrf = $this->createMock(CsrfTokenManagerInterface::class);
$sut = new SecurityController($csrf);
$sut->logoutAction();
}
}

View File

@@ -7,49 +7,49 @@
* file that was distributed with this source code.
*/
namespace App\Tests\Controller;
namespace App\Tests\Controller\Security;
use App\Entity\User;
use App\Tests\Controller\ControllerBaseTest;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
/**
* This test makes sure the login and registration work as expected.
* The logic is located in the FOSUserBundle and already tested, but we use a different layout.
*
* @group integration
*/
class SecurityControllerTest extends ControllerBaseTest
class SelfRegistrationControllerTest extends ControllerBaseTest
{
public function testRootUrlIsRedirectedToLogin()
private function testRegisterActionWithDeactivatedFeature(string $route)
{
$client = self::createClient();
$client->request('GET', '/');
$this->assertIsRedirect($client, $this->createUrl('/homepage'));
$client->followRedirect();
$this->assertIsRedirect($client, $this->createUrl('/login'));
$this->setSystemConfiguration('user.registration', false);
$this->request($client, $route);
$this->assertRouteNotFound($client);
}
public function testLoginPageIsRendered()
public function testRegisterWithDeactivatedFeature()
{
$client = self::createClient();
$this->request($client, '/login');
$this->testRegisterActionWithDeactivatedFeature('/register/');
}
$response = $client->getResponse();
$this->assertTrue($client->getResponse()->isSuccessful());
public function testCheckEmailWithDeactivatedFeature()
{
$this->testRegisterActionWithDeactivatedFeature('/register/check-email');
}
$content = $response->getContent();
$this->assertStringContainsString('<title>Kimai Time Tracking</title>', $content);
$this->assertStringContainsString('<form action="/en/login_check" method="post">', $content);
$this->assertStringContainsString('<input type="text" name="_username"', $content);
$this->assertStringContainsString('<input name="_password" type="password"', $content);
$this->assertStringContainsString('<input id="remember_me" name="_remember_me" type="checkbox"', $content);
$this->assertStringContainsString('">Login</button>', $content);
$this->assertStringContainsString('<input type="hidden" name="_csrf_token" value="', $content);
$this->assertStringContainsString('<a href="/en/register/"', $content);
$this->assertStringContainsString('Register a new account', $content);
public function testConfirmWithDeactivatedFeature()
{
$this->testRegisterActionWithDeactivatedFeature('/register/confirm/123123');
}
public function testConfirmedWithDeactivatedFeature()
{
$this->testRegisterActionWithDeactivatedFeature('/register/confirmed');
}
public function testRegisterAccountPageIsRendered()
{
$client = self::createClient();
$this->setSystemConfiguration('user.registration', true);
$this->request($client, '/register/');
$response = $client->getResponse();
@@ -71,9 +71,9 @@ class SecurityControllerTest extends ControllerBaseTest
$this->assertStringContainsString('>Register</button>', $content);
}
public function testRegisterAccount()
private function createUser(KernelBrowser $client, string $username, string $email, string $password): User
{
$client = self::createClient();
$this->setSystemConfiguration('user.registration', true);
$this->request($client, '/register/');
$response = $client->getResponse();
@@ -82,23 +82,85 @@ class SecurityControllerTest extends ControllerBaseTest
$form = $client->getCrawler()->filter('form[name=fos_user_registration_form]')->form();
$client->submit($form, [
'fos_user_registration_form' => [
'email' => 'test@example.com',
'username' => 'example',
'email' => $email,
'username' => $username,
'plainPassword' => [
'first' => 'test1234',
'second' => 'test1234',
'first' => $password,
'second' => $password,
],
]
]);
$this->assertIsRedirect($client, $this->createUrl('/register/confirmed'));
$this->assertIsRedirect($client, $this->createUrl('/register/check-email'));
$client->followRedirect();
$this->assertTrue($client->getResponse()->isSuccessful());
return $this->loadUserFromDatabase($username);
}
public function testCheckEmailWithoutEmail()
{
$client = self::createClient();
$this->setSystemConfiguration('user.registration', true);
$this->request($client, '/register/check-email');
$this->assertIsRedirect($client, $this->createUrl('/register/'));
$client->followRedirect();
$this->assertTrue($client->getResponse()->isSuccessful());
}
public function testRegisterAccount()
{
$client = self::createClient();
$this->createUser($client, 'example', 'register@example.com', 'test1234');
$content = $client->getResponse()->getContent();
$this->assertStringContainsString('<title>Kimai Time Tracking</title>', $content);
$this->assertStringContainsString('<p>Congrats example, your account is now activated.</p>', $content);
$this->assertStringContainsString('<a href="/en/homepage">', $content);
$this->assertStringContainsString('An email has been sent to register@example.com. It contains an activation link you must click to activate your account.', $content);
$this->assertStringContainsString('<a href="/en/login">', $content);
}
public function testConfirmWithInvalidToken()
{
$client = self::createClient();
$this->setSystemConfiguration('user.registration', true);
$this->request($client, '/register/confirm/1234567890');
$this->assertIsRedirect($client, $this->createUrl('/login'));
$client->followRedirect();
$this->assertTrue($client->getResponse()->isSuccessful());
}
public function testConfirmAccount()
{
$client = self::createClient();
$user = $this->createUser($client, 'example', 'register@example.com', 'test1234');
$token = $user->getConfirmationToken();
self::assertNotEmpty($token);
self::assertFalse($user->isEnabled());
$this->request($client, '/register/confirm/' . $token);
$this->assertIsRedirect($client, $this->createUrl('/register/confirmed'));
$client->followRedirect();
$this->assertTrue($client->getResponse()->isSuccessful());
$content = $client->getResponse()->getContent();
$this->assertStringContainsString('Congratulations example, your account is now activated.', $content);
$user = $this->loadUserFromDatabase('example');
self::assertTrue($user->isEnabled());
}
public function testConfirmedAnonymousRedirectsToLogin()
{
$client = self::createClient();
$this->setSystemConfiguration('user.registration', true);
$this->request($client, '/register/confirmed');
// AccessDeniedException redirects to login
$this->assertIsRedirect($client, $this->createUrl('/login'));
$client->followRedirect();
$this->assertTrue($client->getResponse()->isSuccessful());
}
/**
@@ -107,6 +169,7 @@ class SecurityControllerTest extends ControllerBaseTest
public function testRegisterActionWithValidationProblems(array $formData, array $validationFields)
{
$client = self::createClient();
$this->setSystemConfiguration('user.registration', true);
$this->assertHasValidationError($client, '/register/', 'form[name=fos_user_registration_form]', $formData, $validationFields);
}
@@ -124,11 +187,9 @@ class SecurityControllerTest extends ControllerBaseTest
]
],
[
'#fos_user_registration_form_username',
'#fos_user_registration_form_username',
'#fos_user_registration_form_plainPassword_first',
'#fos_user_registration_form_email',
'#fos_user_registration_form_email',
]
],
// invalid fields: username, password, email
@@ -141,11 +202,9 @@ class SecurityControllerTest extends ControllerBaseTest
]
],
[
'#fos_user_registration_form_username',
'#fos_user_registration_form_username',
'#fos_user_registration_form_plainPassword_first',
'#fos_user_registration_form_email',
'#fos_user_registration_form_email',
]
],
// invalid fields: password (too short)

View File

@@ -74,6 +74,7 @@ class SystemConfigurationControllerTest extends ControllerBaseTest
['form[name=system_configuration_form_timesheet]', $this->createUrl('/admin/system-config/update/timesheet')],
['form[name=system_configuration_form_lockdown_period]', $this->createUrl('/admin/system-config/update/lockdown_period')],
['form[name=system_configuration_form_invoice]', $this->createUrl('/admin/system-config/update/invoice')],
['form[name=system_configuration_form_authentication]', $this->createUrl('/admin/system-config/update/authentication')],
['form[name=system_configuration_form_rounding]', $this->createUrl('/admin/system-config/update/rounding')],
['form[name=system_configuration_form_form_customer]', $this->createUrl('/admin/system-config/update/form_customer')],
['form[name=system_configuration_form_form_user]', $this->createUrl('/admin/system-config/update/form_user')],

View File

@@ -273,11 +273,9 @@ class UserControllerTest extends ControllerBaseTest
]
],
[
'#user_create_username',
'#user_create_username',
'#user_create_plainPassword_first',
'#user_create_email',
'#user_create_email',
]
],
// invalid fields: username, password, email, enabled
@@ -293,11 +291,9 @@ class UserControllerTest extends ControllerBaseTest
]
],
[
'#user_create_username',
'#user_create_username',
'#user_create_plainPassword_first',
'#user_create_email',
'#user_create_email',
]
],
// invalid fields: password (too short)