aboutsummaryrefslogtreecommitdiffhomepage
path: root/tests/security/SessionManagerTest.php
blob: 7961e7710dc3581a2d7f63659fc6f2aa500c25b2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
<?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;

/**
 * Test coverage for SessionManager
 */
class SessionManagerTest extends TestCase
{
    /** @var array Session ID hashes */
    protected static $sidHashes = 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()
    {
        self::$sidHashes = ReferenceSessionIdHashes::getHashes();
    }

    /**
     * Initialize or reset test resources
     */
    public function setUp()
    {
        $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);
    }

    /**
     * Generate a session token
     */
    public function testGenerateToken()
    {
        $token = $this->sessionManager->generateToken();

        $this->assertEquals(1, $this->session['tokens'][$token]);
        $this->assertEquals(40, strlen($token));
    }

    /**
     * Check a session token
     */
    public function testCheckToken()
    {
        $token = '4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b';
        $session = [
            'tokens' => [
                $token => 1,
            ],
        ];
        $sessionManager = new SessionManager($session, $this->conf);

        // check and destroy the token
        $this->assertTrue($sessionManager->checkToken($token));
        $this->assertFalse(isset($session['tokens'][$token]));

        // ensure the token has been destroyed
        $this->assertFalse($sessionManager->checkToken($token));
    }

    /**
     * Generate and check a session token
     */
    public function testGenerateAndCheckToken()
    {
        $token = $this->sessionManager->generateToken();

        // ensure a token has been generated
        $this->assertEquals(1, $this->session['tokens'][$token]);
        $this->assertEquals(40, strlen($token));

        // check and destroy the token
        $this->assertTrue($this->sessionManager->checkToken($token));
        $this->assertFalse(isset($this->session['tokens'][$token]));

        // ensure the token has been destroyed
        $this->assertFalse($this->sessionManager->checkToken($token));
    }

    /**
     * Check an invalid session token
     */
    public function testCheckInvalidToken()
    {
        $this->assertFalse($this->sessionManager->checkToken('4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b'));
    }

    /**
     * Test SessionManager::checkId with a valid ID - TEST ALL THE HASHES!
     *
     * This tests extensively covers all hash algorithms / bit representations
     */
    public function testIsAnyHashSessionIdValid()
    {
        foreach (self::$sidHashes as $algo => $bpcs) {
            foreach ($bpcs as $bpc => $hash) {
                $this->assertTrue(SessionManager::checkId($hash));
            }
        }
    }

    /**
     * Test checkId with a valid ID - SHA-1 hashes
     */
    public function testIsSha1SessionIdValid()
    {
        $this->assertTrue(SessionManager::checkId(sha1('shaarli')));
    }

    /**
     * Test checkId with a valid ID - SHA-256 hashes
     */
    public function testIsSha256SessionIdValid()
    {
        $this->assertTrue(SessionManager::checkId(hash('sha256', 'shaarli')));
    }

    /**
     * Test checkId with a valid ID - SHA-512 hashes
     */
    public function testIsSha512SessionIdValid()
    {
        $this->assertTrue(SessionManager::checkId(hash('sha512', 'shaarli')));
    }

    /**
     * Test checkId with invalid IDs.
     */
    public function testIsSessionIdInvalid()
    {
        $this->assertFalse(SessionManager::checkId(''));
        $this->assertFalse(SessionManager::checkId([]));
        $this->assertFalse(
            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' => false,
        ];
        $this->sessionManager->logout();

        $this->assertFalse(isset($this->session['ip']));
        $this->assertFalse(isset($this->session['expires_on']));
        $this->assertFalse(isset($this->session['username']));
        $this->assertFalse(isset($this->session['visibility']));
        $this->assertFalse(isset($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'));
    }
}