aboutsummaryrefslogtreecommitdiffhomepage
path: root/tests/security/LoginManagerTest.php
blob: d302983de2b013e8ec91e79e9c04eb62f59b75fb (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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<?php

namespace Shaarli\Security;

use Shaarli\TestCase;

/**
 * Test coverage for LoginManager
 */
class LoginManagerTest extends TestCase
{
    /** @var \FakeConfigManager Configuration Manager instance */
    protected $configManager = null;

    /** @var LoginManager Login Manager instance */
    protected $loginManager = null;

    /** @var SessionManager Session Manager instance */
    protected $sessionManager = null;

    /** @var string Banned IP filename */
    protected $banFile = 'sandbox/ipbans.php';

    /** @var string Log filename */
    protected $logFile = 'sandbox/shaarli.log';

    /** @var array Simulates the $_COOKIE array */
    protected $cookie = [];

    /** @var array Simulates the $GLOBALS array */
    protected $globals = [];

    /** @var array Simulates the $_SERVER array */
    protected $server = [];

    /** @var array Simulates the $_SESSION array */
    protected $session = [];

    /** @var string Advertised client IP address */
    protected $clientIpAddress = '10.1.47.179';

    /** @var string Local client IP address */
    protected $ipAddr = '127.0.0.1';

    /** @var string Trusted proxy IP address */
    protected $trustedProxy = '10.1.1.100';

    /** @var string User login */
    protected $login = 'johndoe';

    /** @var string User password */
    protected $password = 'IC4nHazL0g1n?';

    /** @var string Hash of the salted user password */
    protected $passwordHash = '';

    /** @var string Salt used by hash functions */
    protected $salt = '669e24fa9c5a59a613f98e8e38327384504a4af2';

    /** @var CookieManager */
    protected $cookieManager;

    /**
     * Prepare or reset test resources
     */
    protected function setUp(): void
    {
        if (file_exists($this->banFile)) {
            unlink($this->banFile);
        }

        $this->passwordHash = sha1($this->password . $this->login . $this->salt);

        $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' => 2,
            'security.ban_duration' => 3600,
            'security.trusted_proxies' => [$this->trustedProxy],
            'ldap.host' => '',
        ]);

        $this->cookie = [];
        $this->session = [];

        $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->loginManager = new LoginManager($this->configManager, $this->sessionManager, $this->cookieManager);
        $this->server['REMOTE_ADDR'] = $this->ipAddr;
    }

    /**
     * Record a failed login attempt
     */
    public function testHandleFailedLogin()
    {
        $this->loginManager->handleFailedLogin($this->server);
        $this->loginManager->handleFailedLogin($this->server);
        $this->assertFalse($this->loginManager->canLogin($this->server));
    }

    /**
     * Record a failed login attempt - IP behind a trusted proxy
     */
    public function testHandleFailedLoginBehindTrustedProxy()
    {
        $server = [
            'REMOTE_ADDR' => $this->trustedProxy,
            'HTTP_X_FORWARDED_FOR' => $this->ipAddr,
        ];
        $this->loginManager->handleFailedLogin($server);
        $this->loginManager->handleFailedLogin($server);
        $this->assertFalse($this->loginManager->canLogin($server));
    }

    /**
     * Record a failed login attempt - IP behind a trusted proxy but not forwarded
     */
    public function testHandleFailedLoginBehindTrustedProxyNoIp()
    {
        $server = [
            'REMOTE_ADDR' => $this->trustedProxy,
        ];
        $this->loginManager->handleFailedLogin($server);
        $this->loginManager->handleFailedLogin($server);
        $this->assertTrue($this->loginManager->canLogin($server));
    }

    /**
     * Nothing to do
     */
    public function testHandleSuccessfulLogin()
    {
        $this->assertTrue($this->loginManager->canLogin($this->server));

        $this->loginManager->handleSuccessfulLogin($this->server);
        $this->assertTrue($this->loginManager->canLogin($this->server));
    }

    /**
     * Erase failure records after successfully logging in from this IP
     */
    public function testHandleSuccessfulLoginAfterFailure()
    {
        $this->loginManager->handleFailedLogin($this->server);
        $this->assertTrue($this->loginManager->canLogin($this->server));

        $this->loginManager->handleSuccessfulLogin($this->server);
        $this->loginManager->handleFailedLogin($this->server);
        $this->assertTrue($this->loginManager->canLogin($this->server));
    }

    /**
     * The IP is not banned
     */
    public function testCanLoginIpNotBanned()
    {
        $this->assertTrue($this->loginManager->canLogin($this->server));
    }

    /**
     * Generate a token depending on the user credentials and client IP
     */
    public function testGenerateStaySignedInToken()
    {
        $this->loginManager->generateStaySignedInToken($this->clientIpAddress);

        $this->assertEquals(
            sha1($this->passwordHash . $this->clientIpAddress . $this->salt),
            $this->loginManager->getStaySignedInToken()
        );
    }

    /**
     * Generate a token depending on the user credentials with session protected disabled
     */
    public function testGenerateStaySignedInTokenSessionProtectionDisabled()
    {
        $this->configManager->set('security.session_protection_disabled', true);
        $this->loginManager->generateStaySignedInToken($this->clientIpAddress);

        $this->assertEquals(
            sha1($this->passwordHash . $this->salt),
            $this->loginManager->getStaySignedInToken()
        );
    }

    /**
     * Check user login - Shaarli has not yet been configured
     */
    public function testCheckLoginStateNotConfigured()
    {
        $configManager = new \FakeConfigManager([
            'resource.ban_file' => $this->banFile,
        ]);
        $loginManager = new LoginManager($configManager, null, $this->cookieManager);
        $loginManager->checkLoginState('');

        $this->assertFalse($loginManager->isLoggedIn());
    }

    /**
     * Check user login - the client cookie does not match the server token
     */
    public function testCheckLoginStateStaySignedInWithInvalidToken()
    {
        // simulate a previous login
        $this->session = [
            'ip' => $this->clientIpAddress,
            'expires_on' => time() + 100,
        ];
        $this->loginManager->generateStaySignedInToken($this->clientIpAddress);
        $this->cookie[CookieManager::STAY_SIGNED_IN] = 'nope';

        $this->loginManager->checkLoginState($this->clientIpAddress);

        $this->assertTrue($this->loginManager->isLoggedIn());
        $this->assertTrue(empty($this->session['username']));
    }

    /**
     * Check user login - the client cookie matches the server token
     */
    public function testCheckLoginStateStaySignedInWithValidToken()
    {
        $this->loginManager->generateStaySignedInToken($this->clientIpAddress);
        $this->cookie[CookieManager::STAY_SIGNED_IN] = $this->loginManager->getStaySignedInToken();

        $this->loginManager->checkLoginState($this->clientIpAddress);

        $this->assertTrue($this->loginManager->isLoggedIn());
        $this->assertEquals($this->login, $this->session['username']);
        $this->assertEquals($this->clientIpAddress, $this->session['ip']);
    }

    /**
     * Check user login - the session has expired
     */
    public function testCheckLoginStateSessionExpired()
    {
        $this->loginManager->generateStaySignedInToken($this->clientIpAddress);
        $this->session['expires_on'] = time() - 100;

        $this->loginManager->checkLoginState($this->clientIpAddress);

        $this->assertFalse($this->loginManager->isLoggedIn());
    }

    /**
     * Check user login - the remote client IP has changed
     */
    public function testCheckLoginStateClientIpChanged()
    {
        $this->loginManager->generateStaySignedInToken($this->clientIpAddress);

        $this->loginManager->checkLoginState('10.7.157.98');

        $this->assertFalse($this->loginManager->isLoggedIn());
    }

    /**
     * Check user credentials - wrong login supplied
     */
    public function testCheckCredentialsWrongLogin()
    {
        $this->assertFalse(
            $this->loginManager->checkCredentials('', '', 'b4dl0g1n', $this->password)
        );
    }

    /**
     * Check user credentials - wrong password supplied
     */
    public function testCheckCredentialsWrongPassword()
    {
        $this->assertFalse(
            $this->loginManager->checkCredentials('', '', $this->login, 'b4dp455wd')
        );
    }

    /**
     * Check user credentials - wrong login and password supplied
     */
    public function testCheckCredentialsWrongLoginAndPassword()
    {
        $this->assertFalse(
            $this->loginManager->checkCredentials('', '', 'b4dl0g1n', 'b4dp455wd')
        );
    }

    /**
     * Check user credentials - correct login and password supplied
     */
    public function testCheckCredentialsGoodLoginAndPassword()
    {
        $this->assertTrue(
            $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; })
        );
    }
}