]> git.immae.eu Git - github/shaarli/Shaarli.git/blobdiff - tests/security/SessionManagerTest.php
Compatibility with PHPUnit 9
[github/shaarli/Shaarli.git] / tests / security / SessionManagerTest.php
index e4e1cfbc82d291cf927164725d4e370f338bb468..3f9c3ef59fd2138faeb95fe07b715890a0f09ab4 100644 (file)
@@ -1,32 +1,46 @@
 <?php
-require_once 'tests/utils/FakeConfigManager.php';
 
-// Initialize reference data _before_ PHPUnit starts a session
-require_once 'tests/utils/ReferenceSessionIdHashes.php';
-ReferenceSessionIdHashes::genAllHashes();
-
-use \Shaarli\Security\SessionManager;
-use \PHPUnit\Framework\TestCase;
+namespace Shaarli\Security;
 
+use Shaarli\TestCase;
 
 /**
  * Test coverage for SessionManager
  */
 class SessionManagerTest extends TestCase
 {
-    // Session ID hashes
+    /** @var array Session ID hashes */
     protected static $sidHashes = null;
 
-    // Fake ConfigManager
-    protected static $conf = null;
+    /** @var \FakeConfigManager ConfigManager substitute for testing */
+    protected $conf = null;
+
+    /** @var array $_SESSION array for testing */
+    protected $session = [];
+
+    /** @var SessionManager Server-side session management abstraction */
+    protected $sessionManager = null;
 
     /**
      * Assign reference data
      */
-    public static function setUpBeforeClass()
+    public static function setUpBeforeClass(): void
     {
-        self::$sidHashes = ReferenceSessionIdHashes::getHashes();
-        self::$conf = new FakeConfigManager();
+        self::$sidHashes = \ReferenceSessionIdHashes::getHashes();
+    }
+
+    /**
+     * Initialize or reset test resources
+     */
+    protected function setUp(): void
+    {
+        $this->conf = new \FakeConfigManager([
+            'credentials.login' => 'johndoe',
+            'credentials.salt' => 'salt',
+            'security.session_protection_disabled' => false,
+        ]);
+        $this->session = [];
+        $this->sessionManager = new SessionManager($this->session, $this->conf, 'session_path');
     }
 
     /**
@@ -34,12 +48,9 @@ class SessionManagerTest extends TestCase
      */
     public function testGenerateToken()
     {
-        $session = [];
-        $sessionManager = new SessionManager($session, self::$conf);
-
-        $token = $sessionManager->generateToken();
+        $token = $this->sessionManager->generateToken();
 
-        $this->assertEquals(1, $session['tokens'][$token]);
+        $this->assertEquals(1, $this->session['tokens'][$token]);
         $this->assertEquals(40, strlen($token));
     }
 
@@ -54,7 +65,7 @@ class SessionManagerTest extends TestCase
                 $token => 1,
             ],
         ];
-        $sessionManager = new SessionManager($session, self::$conf);
+        $sessionManager = new SessionManager($session, $this->conf, 'session_path');
 
         // check and destroy the token
         $this->assertTrue($sessionManager->checkToken($token));
@@ -69,21 +80,18 @@ class SessionManagerTest extends TestCase
      */
     public function testGenerateAndCheckToken()
     {
-        $session = [];
-        $sessionManager = new SessionManager($session, self::$conf);
-
-        $token = $sessionManager->generateToken();
+        $token = $this->sessionManager->generateToken();
 
         // ensure a token has been generated
-        $this->assertEquals(1, $session['tokens'][$token]);
+        $this->assertEquals(1, $this->session['tokens'][$token]);
         $this->assertEquals(40, strlen($token));
 
         // check and destroy the token
-        $this->assertTrue($sessionManager->checkToken($token));
-        $this->assertFalse(isset($session['tokens'][$token]));
+        $this->assertTrue($this->sessionManager->checkToken($token));
+        $this->assertFalse(isset($this->session['tokens'][$token]));
 
         // ensure the token has been destroyed
-        $this->assertFalse($sessionManager->checkToken($token));
+        $this->assertFalse($this->sessionManager->checkToken($token));
     }
 
     /**
@@ -91,10 +99,7 @@ class SessionManagerTest extends TestCase
      */
     public function testCheckInvalidToken()
     {
-        $session = [];
-        $sessionManager = new SessionManager($session, self::$conf);
-
-        $this->assertFalse($sessionManager->checkToken('4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b'));
+        $this->assertFalse($this->sessionManager->checkToken('4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b'));
     }
 
     /**
@@ -146,4 +151,176 @@ class SessionManagerTest extends TestCase
             SessionManager::checkId('c0ZqcWF3VFE2NmJBdm1HMVQ0ZHJ3UmZPbTFsNGhkNHI=')
         );
     }
+
+    /**
+     * Store login information after a successful login
+     */
+    public function testStoreLoginInfo()
+    {
+        $this->sessionManager->storeLoginInfo('ip_id');
+
+        $this->assertGreaterThan(time(), $this->session['expires_on']);
+        $this->assertEquals('ip_id', $this->session['ip']);
+        $this->assertEquals('johndoe', $this->session['username']);
+    }
+
+    /**
+     * Extend a server-side session by SessionManager::$SHORT_TIMEOUT
+     */
+    public function testExtendSession()
+    {
+        $this->sessionManager->extendSession();
+
+        $this->assertGreaterThan(time(), $this->session['expires_on']);
+        $this->assertLessThanOrEqual(
+            time() + SessionManager::$SHORT_TIMEOUT,
+            $this->session['expires_on']
+        );
+    }
+
+    /**
+     * Extend a server-side session by SessionManager::$LONG_TIMEOUT
+     */
+    public function testExtendSessionStaySignedIn()
+    {
+        $this->sessionManager->setStaySignedIn(true);
+        $this->sessionManager->extendSession();
+
+        $this->assertGreaterThan(time(), $this->session['expires_on']);
+        $this->assertGreaterThan(
+            time() + SessionManager::$LONG_TIMEOUT - 10,
+            $this->session['expires_on']
+        );
+        $this->assertLessThanOrEqual(
+            time() + SessionManager::$LONG_TIMEOUT,
+            $this->session['expires_on']
+        );
+    }
+
+    /**
+     * Unset session variables after logging out
+     */
+    public function testLogout()
+    {
+        $this->session = [
+            'ip' => 'ip_id',
+            'expires_on' => time() + 1000,
+            'username' => 'johndoe',
+            'visibility' => 'public',
+            'untaggedonly' => true,
+        ];
+        $this->sessionManager->logout();
+
+        $this->assertArrayNotHasKey('ip', $this->session);
+        $this->assertArrayNotHasKey('expires_on', $this->session);
+        $this->assertArrayNotHasKey('username', $this->session);
+        $this->assertArrayNotHasKey('visibility', $this->session);
+        $this->assertArrayHasKey('untaggedonly', $this->session);
+        $this->assertTrue($this->session['untaggedonly']);
+    }
+
+    /**
+     * The session is active and expiration time has been reached
+     */
+    public function testHasExpiredTimeElapsed()
+    {
+        $this->session['expires_on'] = time() - 10;
+
+        $this->assertTrue($this->sessionManager->hasSessionExpired());
+    }
+
+    /**
+     * The session is active and expiration time has not been reached
+     */
+    public function testHasNotExpired()
+    {
+        $this->session['expires_on'] = time() + 1000;
+
+        $this->assertFalse($this->sessionManager->hasSessionExpired());
+    }
+
+    /**
+     * Session hijacking protection is disabled, we assume the IP has not changed
+     */
+    public function testHasClientIpChangedNoSessionProtection()
+    {
+        $this->conf->set('security.session_protection_disabled', true);
+
+        $this->assertFalse($this->sessionManager->hasClientIpChanged(''));
+    }
+
+    /**
+     * The client IP identifier has not changed
+     */
+    public function testHasClientIpChangedNope()
+    {
+        $this->session['ip'] = 'ip_id';
+        $this->assertFalse($this->sessionManager->hasClientIpChanged('ip_id'));
+    }
+
+    /**
+     * The client IP identifier has changed
+     */
+    public function testHasClientIpChanged()
+    {
+        $this->session['ip'] = 'ip_id_one';
+        $this->assertTrue($this->sessionManager->hasClientIpChanged('ip_id_two'));
+    }
+
+    /**
+     * Test creating an entry in the session array
+     */
+    public function testSetSessionParameterCreate(): void
+    {
+        $this->sessionManager->setSessionParameter('abc', 'def');
+
+        static::assertSame('def', $this->session['abc']);
+    }
+
+    /**
+     * Test updating an entry in the session array
+     */
+    public function testSetSessionParameterUpdate(): void
+    {
+        $this->session['abc'] = 'ghi';
+
+        $this->sessionManager->setSessionParameter('abc', 'def');
+
+        static::assertSame('def', $this->session['abc']);
+    }
+
+    /**
+     * Test updating an entry in the session array with null value
+     */
+    public function testSetSessionParameterUpdateNull(): void
+    {
+        $this->session['abc'] = 'ghi';
+
+        $this->sessionManager->setSessionParameter('abc', null);
+
+        static::assertArrayHasKey('abc', $this->session);
+        static::assertNull($this->session['abc']);
+    }
+
+    /**
+     * Test deleting an existing entry in the session array
+     */
+    public function testDeleteSessionParameter(): void
+    {
+        $this->session['abc'] = 'def';
+
+        $this->sessionManager->deleteSessionParameter('abc');
+
+        static::assertArrayNotHasKey('abc', $this->session);
+    }
+
+    /**
+     * Test deleting a non existent entry in the session array
+     */
+    public function testDeleteSessionParameterNotExisting(): void
+    {
+        $this->sessionManager->deleteSessionParameter('abc');
+
+        static::assertArrayNotHasKey('abc', $this->session);
+    }
 }