]> git.immae.eu Git - github/shaarli/Shaarli.git/blobdiff - tests/security/LoginManagerTest.php
Use PSR-3 logger for login attempts
[github/shaarli/Shaarli.git] / tests / security / LoginManagerTest.php
index de8055edaede452cdeeb1c21ed42ae3b13447a8e..f7609fc676e8601a03dc688cdf2cee6407e1fe97 100644 (file)
@@ -1,16 +1,17 @@
 <?php
-namespace Shaarli\Security;
 
-require_once 'tests/utils/FakeConfigManager.php';
+namespace Shaarli\Security;
 
-use PHPUnit\Framework\TestCase;
+use Psr\Log\LoggerInterface;
+use Shaarli\FakeConfigManager;
+use Shaarli\TestCase;
 
 /**
  * Test coverage for LoginManager
  */
 class LoginManagerTest extends TestCase
 {
-    /** @var \FakeConfigManager Configuration Manager instance */
+    /** @var FakeConfigManager Configuration Manager instance */
     protected $configManager = null;
 
     /** @var LoginManager Login Manager instance */
@@ -58,10 +59,16 @@ class LoginManagerTest extends TestCase
     /** @var string Salt used by hash functions */
     protected $salt = '669e24fa9c5a59a613f98e8e38327384504a4af2';
 
+    /** @var CookieManager */
+    protected $cookieManager;
+
+    /** @var BanManager */
+    protected $banManager;
+
     /**
      * Prepare or reset test resources
      */
-    public function setUp()
+    protected function setUp(): void
     {
         if (file_exists($this->banFile)) {
             unlink($this->banFile);
@@ -69,60 +76,49 @@ class LoginManagerTest extends TestCase
 
         $this->passwordHash = sha1($this->password . $this->login . $this->salt);
 
-        $this->configManager = new \FakeConfigManager([
+        $this->configManager = new FakeConfigManager([
             'credentials.login' => $this->login,
             'credentials.hash' => $this->passwordHash,
             'credentials.salt' => $this->salt,
             'resource.ban_file' => $this->banFile,
             'resource.log' => $this->logFile,
-            'security.ban_after' => 4,
+            'security.ban_after' => 2,
             'security.ban_duration' => 3600,
             'security.trusted_proxies' => [$this->trustedProxy],
+            'ldap.host' => '',
         ]);
 
         $this->cookie = [];
-
-        $this->globals = &$GLOBALS;
-        unset($this->globals['IPBANS']);
-
         $this->session = [];
 
-        $this->sessionManager = new SessionManager($this->session, $this->configManager);
-        $this->loginManager = new LoginManager($this->globals, $this->configManager, $this->sessionManager);
-        $this->server['REMOTE_ADDR'] = $this->ipAddr;
-    }
-
-    /**
-     * Wipe test resources
-     */
-    public function tearDown()
-    {
-        unset($this->globals['IPBANS']);
-    }
-
-    /**
-     * Instantiate a LoginManager and load ban records
-     */
-    public function testReadBanFile()
-    {
-        file_put_contents(
-            $this->banFile,
-            "<?php\n\$GLOBALS['IPBANS']=array('FAILURES' => array('127.0.0.1' => 99));\n?>"
+        $this->cookieManager = $this->createMock(CookieManager::class);
+        $this->cookieManager->method('getCookieParameter')->willReturnCallback(function (string $key) {
+            return $this->cookie[$key] ?? null;
+        });
+        $this->sessionManager = new SessionManager($this->session, $this->configManager, 'session_path');
+        $this->banManager = $this->createMock(BanManager::class);
+        $this->loginManager = new LoginManager(
+            $this->configManager,
+            $this->sessionManager,
+            $this->cookieManager,
+            $this->banManager,
+            $this->createMock(LoggerInterface::class)
         );
-        new LoginManager($this->globals, $this->configManager, null);
-        $this->assertEquals(99, $this->globals['IPBANS']['FAILURES']['127.0.0.1']);
+        $this->server['REMOTE_ADDR'] = $this->ipAddr;
     }
 
     /**
      * Record a failed login attempt
      */
-    public function testHandleFailedLogin()
+    public function testHandleFailedLogin(): void
     {
-        $this->loginManager->handleFailedLogin($this->server);
-        $this->assertEquals(1, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
+        $this->banManager->expects(static::exactly(2))->method('handleFailedAttempt');
+        $this->banManager->method('isBanned')->willReturn(true);
 
         $this->loginManager->handleFailedLogin($this->server);
-        $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
+        $this->loginManager->handleFailedLogin($this->server);
+
+        static::assertFalse($this->loginManager->canLogin($this->server));
     }
 
     /**
@@ -134,11 +130,14 @@ class LoginManagerTest extends TestCase
             'REMOTE_ADDR' => $this->trustedProxy,
             'HTTP_X_FORWARDED_FOR' => $this->ipAddr,
         ];
-        $this->loginManager->handleFailedLogin($server);
-        $this->assertEquals(1, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
 
+        $this->banManager->expects(static::exactly(2))->method('handleFailedAttempt');
+        $this->banManager->method('isBanned')->willReturn(true);
+
+        $this->loginManager->handleFailedLogin($server);
         $this->loginManager->handleFailedLogin($server);
-        $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
+
+        $this->assertFalse($this->loginManager->canLogin($server));
     }
 
     /**
@@ -150,39 +149,8 @@ class LoginManagerTest extends TestCase
             'REMOTE_ADDR' => $this->trustedProxy,
         ];
         $this->loginManager->handleFailedLogin($server);
-        $this->assertFalse(isset($this->globals['IPBANS']['FAILURES'][$this->ipAddr]));
-
         $this->loginManager->handleFailedLogin($server);
-        $this->assertFalse(isset($this->globals['IPBANS']['FAILURES'][$this->ipAddr]));
-    }
-
-    /**
-     * Record a failed login attempt and ban the IP after too many failures
-     */
-    public function testHandleFailedLoginBanIp()
-    {
-        $this->loginManager->handleFailedLogin($this->server);
-        $this->assertEquals(1, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
-        $this->assertTrue($this->loginManager->canLogin($this->server));
-
-        $this->loginManager->handleFailedLogin($this->server);
-        $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
-        $this->assertTrue($this->loginManager->canLogin($this->server));
-
-        $this->loginManager->handleFailedLogin($this->server);
-        $this->assertEquals(3, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
-        $this->assertTrue($this->loginManager->canLogin($this->server));
-
-        $this->loginManager->handleFailedLogin($this->server);
-        $this->assertEquals(4, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
-        $this->assertFalse($this->loginManager->canLogin($this->server));
-
-        // handleFailedLogin is not supposed to be called at this point:
-        // - no login form should be displayed once an IP has been banned
-        // - yet this could happen when using custom templates / scripts
-        $this->loginManager->handleFailedLogin($this->server);
-        $this->assertEquals(5, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
-        $this->assertFalse($this->loginManager->canLogin($this->server));
+        $this->assertTrue($this->loginManager->canLogin($server));
     }
 
     /**
@@ -202,14 +170,11 @@ class LoginManagerTest extends TestCase
     public function testHandleSuccessfulLoginAfterFailure()
     {
         $this->loginManager->handleFailedLogin($this->server);
-        $this->loginManager->handleFailedLogin($this->server);
-        $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]);
         $this->assertTrue($this->loginManager->canLogin($this->server));
 
         $this->loginManager->handleSuccessfulLogin($this->server);
+        $this->loginManager->handleFailedLogin($this->server);
         $this->assertTrue($this->loginManager->canLogin($this->server));
-        $this->assertFalse(isset($this->globals['IPBANS']['FAILURES'][$this->ipAddr]));
-        $this->assertFalse(isset($this->globals['IPBANS']['BANS'][$this->ipAddr]));
     }
 
     /**
@@ -221,41 +186,28 @@ class LoginManagerTest extends TestCase
     }
 
     /**
-     * The IP is banned
-     */
-    public function testCanLoginIpBanned()
-    {
-        // ban the IP for an hour
-        $this->globals['IPBANS']['FAILURES'][$this->ipAddr] = 10;
-        $this->globals['IPBANS']['BANS'][$this->ipAddr] = time() + 3600;
-
-        $this->assertFalse($this->loginManager->canLogin($this->server));
-    }
-
-    /**
-     * The IP is banned, and the ban duration is over
+     * Generate a token depending on the user credentials and client IP
      */
-    public function testCanLoginIpBanExpired()
+    public function testGenerateStaySignedInToken()
     {
-        // ban the IP for an hour
-        $this->globals['IPBANS']['FAILURES'][$this->ipAddr] = 10;
-        $this->globals['IPBANS']['BANS'][$this->ipAddr] = time() + 3600;
-        $this->assertFalse($this->loginManager->canLogin($this->server));
+        $this->loginManager->generateStaySignedInToken($this->clientIpAddress);
 
-        // lift the ban
-        $this->globals['IPBANS']['BANS'][$this->ipAddr] = time() - 3600;
-        $this->assertTrue($this->loginManager->canLogin($this->server));
+        $this->assertEquals(
+            sha1($this->passwordHash . $this->clientIpAddress . $this->salt),
+            $this->loginManager->getStaySignedInToken()
+        );
     }
 
     /**
-     * Generate a token depending on the user credentials and client IP
+     * Generate a token depending on the user credentials with session protected disabled
      */
-    public function testGenerateStaySignedInToken()
+    public function testGenerateStaySignedInTokenSessionProtectionDisabled()
     {
+        $this->configManager->set('security.session_protection_disabled', true);
         $this->loginManager->generateStaySignedInToken($this->clientIpAddress);
 
         $this->assertEquals(
-            sha1($this->passwordHash . $this->clientIpAddress . $this->salt),
+            sha1($this->passwordHash . $this->salt),
             $this->loginManager->getStaySignedInToken()
         );
     }
@@ -265,11 +217,17 @@ class LoginManagerTest extends TestCase
      */
     public function testCheckLoginStateNotConfigured()
     {
-        $configManager = new \FakeConfigManager([
+        $configManager = new FakeConfigManager([
             'resource.ban_file' => $this->banFile,
         ]);
-        $loginManager = new LoginManager($this->globals, $configManager, null);
-        $loginManager->checkLoginState([], '');
+        $loginManager = new LoginManager(
+            $configManager,
+            $this->sessionManager,
+            $this->cookieManager,
+            $this->banManager,
+            $this->createMock(LoggerInterface::class)
+        );
+        $loginManager->checkLoginState('');
 
         $this->assertFalse($loginManager->isLoggedIn());
     }
@@ -285,9 +243,9 @@ class LoginManagerTest extends TestCase
             'expires_on' => time() + 100,
         ];
         $this->loginManager->generateStaySignedInToken($this->clientIpAddress);
-        $this->cookie[LoginManager::$STAY_SIGNED_IN_COOKIE] = 'nope';
+        $this->cookie[CookieManager::STAY_SIGNED_IN] = 'nope';
 
-        $this->loginManager->checkLoginState($this->cookie, $this->clientIpAddress);
+        $this->loginManager->checkLoginState($this->clientIpAddress);
 
         $this->assertTrue($this->loginManager->isLoggedIn());
         $this->assertTrue(empty($this->session['username']));
@@ -299,9 +257,9 @@ class LoginManagerTest extends TestCase
     public function testCheckLoginStateStaySignedInWithValidToken()
     {
         $this->loginManager->generateStaySignedInToken($this->clientIpAddress);
-        $this->cookie[LoginManager::$STAY_SIGNED_IN_COOKIE] = $this->loginManager->getStaySignedInToken();
+        $this->cookie[CookieManager::STAY_SIGNED_IN] = $this->loginManager->getStaySignedInToken();
 
-        $this->loginManager->checkLoginState($this->cookie, $this->clientIpAddress);
+        $this->loginManager->checkLoginState($this->clientIpAddress);
 
         $this->assertTrue($this->loginManager->isLoggedIn());
         $this->assertEquals($this->login, $this->session['username']);
@@ -316,7 +274,7 @@ class LoginManagerTest extends TestCase
         $this->loginManager->generateStaySignedInToken($this->clientIpAddress);
         $this->session['expires_on'] = time() - 100;
 
-        $this->loginManager->checkLoginState($this->cookie, $this->clientIpAddress);
+        $this->loginManager->checkLoginState($this->clientIpAddress);
 
         $this->assertFalse($this->loginManager->isLoggedIn());
     }
@@ -328,7 +286,7 @@ class LoginManagerTest extends TestCase
     {
         $this->loginManager->generateStaySignedInToken($this->clientIpAddress);
 
-        $this->loginManager->checkLoginState($this->cookie, '10.7.157.98');
+        $this->loginManager->checkLoginState('10.7.157.98');
 
         $this->assertFalse($this->loginManager->isLoggedIn());
     }
@@ -339,7 +297,7 @@ class LoginManagerTest extends TestCase
     public function testCheckCredentialsWrongLogin()
     {
         $this->assertFalse(
-            $this->loginManager->checkCredentials('', '', 'b4dl0g1n', $this->password)
+            $this->loginManager->checkCredentials('', 'b4dl0g1n', $this->password)
         );
     }
 
@@ -349,7 +307,7 @@ class LoginManagerTest extends TestCase
     public function testCheckCredentialsWrongPassword()
     {
         $this->assertFalse(
-            $this->loginManager->checkCredentials('', '', $this->login, 'b4dp455wd')
+            $this->loginManager->checkCredentials('', $this->login, 'b4dp455wd')
         );
     }
 
@@ -359,7 +317,7 @@ class LoginManagerTest extends TestCase
     public function testCheckCredentialsWrongLoginAndPassword()
     {
         $this->assertFalse(
-            $this->loginManager->checkCredentials('', '', 'b4dl0g1n', 'b4dp455wd')
+            $this->loginManager->checkCredentials('', 'b4dl0g1n', 'b4dp455wd')
         );
     }
 
@@ -369,7 +327,40 @@ class LoginManagerTest extends TestCase
     public function testCheckCredentialsGoodLoginAndPassword()
     {
         $this->assertTrue(
-            $this->loginManager->checkCredentials('', '', $this->login, $this->password)
+            $this->loginManager->checkCredentials('', $this->login, $this->password)
+        );
+    }
+
+    /**
+     * Check user credentials through LDAP - server unreachable
+     */
+    public function testCheckCredentialsFromUnreachableLdap()
+    {
+        $this->configManager->set('ldap.host', 'dummy');
+        $this->assertFalse(
+            $this->loginManager->checkCredentials('', $this->login, $this->password)
+        );
+    }
+
+    /**
+     * Check user credentials through LDAP - wrong login and password supplied
+     */
+    public function testCheckCredentialsFromLdapWrongLoginAndPassword()
+    {
+        $this->configManager->set('ldap.host', 'dummy');
+        $this->assertFalse(
+            $this->loginManager->checkCredentialsFromLdap($this->login, $this->password, function() { return null; }, function() { return false; })
+        );
+    }
+
+    /**
+     * Check user credentials through LDAP - correct login and password supplied
+     */
+    public function testCheckCredentialsFromLdapGoodLoginAndPassword()
+    {
+        $this->configManager->set('ldap.host', 'dummy');
+        $this->assertTrue(
+            $this->loginManager->checkCredentialsFromLdap($this->login, $this->password, function() { return null; }, function() { return true; })
         );
     }
 }