Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace core\session;
18
 
19
use core\tests\session\mock_handler;
20
use Redis;
21
use RedisException;
22
 
23
/**
24
 * Unit tests for classes/session/redis.php.
25
 *
26
 * NOTE: in order to execute this test you need to set up
27
 *       Redis server and add configuration a constant
28
 *       to config.php or phpunit.xml configuration file:
29
 *
30
 * define('TEST_SESSION_REDIS_HOST', '127.0.0.1');
31
 *
32
 * @package   core
33
 * @covers    \core\session\redis
34
 * @author    Russell Smith <mr-russ@smith2001.net>
35
 * @copyright 2016 Russell Smith
36
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37
 * @runClassInSeparateProcess
38
 * @covers \core\session\redis
39
 */
40
final class redis_test extends \advanced_testcase {
41
    /** @var string $keyprefix This key prefix used when testing Redis */
42
    protected string $keyprefix = '';
43
    /** @var ?Redis $redis The current testing redis connection */
44
    protected ?Redis $redis = null;
45
    /** @var bool $encrypted Is the current testing redis connection encrypted*/
46
    protected bool $encrypted = false;
47
    /** @var int $acquiretimeout how long we wait for session lock in seconds when testing Redis */
48
    protected int $acquiretimeout = 1;
49
    /** @var int $lockexpire how long to wait in seconds before expiring the lock when testing Redis */
50
    protected int $lockexpire = 70;
51
 
52
    #[\Override]
53
    public function setUp(): void {
54
        global $CFG;
55
        parent::setUp();
56
 
57
        if (!extension_loaded('redis')) {
58
            $this->markTestSkipped('Redis extension not loaded.');
59
        }
60
        if (!defined('TEST_SESSION_REDIS_HOST')) {
61
            $this->markTestSkipped('Session test server not set. define: TEST_SESSION_REDIS_HOST');
62
        }
63
        $version = phpversion('Redis');
64
        if (!$version) {
65
            $this->markTestSkipped('Redis extension version missing');
66
        } else if (version_compare($version, \core\session\redis::REDIS_MIN_EXTENSION_VERSION) <= 0) {
67
            $this->markTestSkipped('Redis extension version must be at least ' . \core\session\redis::REDIS_MIN_EXTENSION_VERSION .
68
                ': now running "' . $version . '"');
69
        }
70
 
71
        $this->resetAfterTest();
72
 
73
        $this->keyprefix = 'phpunit'.rand(1, 100000);
74
 
75
        if (strpos(TEST_SESSION_REDIS_HOST, ':')) {
76
            list($server, $port) = explode(':', TEST_SESSION_REDIS_HOST);
77
        } else {
78
            $server = TEST_SESSION_REDIS_HOST;
79
            $port = 6379;
80
        }
81
        $CFG->session_redis_host = $server;
82
        $CFG->session_redis_port = $port;
83
 
84
        $opts = [];
85
        if (defined('TEST_SESSION_REDIS_ENCRYPT') && TEST_SESSION_REDIS_ENCRYPT) {
86
            $this->encrypted = true;
87
            $sslopts = $CFG->session_redis_encrypt = ['verify_peer' => false, 'verify_peer_name' => false];
88
            $opts['stream'] = $sslopts;
89
        }
90
        $CFG->session_redis_prefix = $this->keyprefix;
91
 
92
        // Set a very short lock timeout to ensure tests run quickly.  We are running single threaded,
93
        // so unless we lock and expect it to be there, we will always see a lock.
94
        $CFG->session_redis_acquire_lock_timeout = $this->acquiretimeout;
95
        $CFG->session_redis_lock_expire = $this->lockexpire;
96
 
97
        $this->redis = new Redis();
98
        $this->redis->connect($server, $port, 1, null, 1, 0, $opts);
99
        if (!$this->redis->ping()) {
100
            $this->markTestSkipped("Redis ping failed");
101
        }
102
    }
103
 
104
    public function tearDown(): void {
105
        if (!extension_loaded('redis') || !defined('TEST_SESSION_REDIS_HOST')) {
106
            return;
107
        }
108
 
109
        $list = $this->redis->keys($this->keyprefix.'*');
110
        foreach ($list as $keyname) {
111
            $this->redis->del($keyname);
112
        }
113
        $this->redis->close();
114
        parent::tearDown();
115
    }
116
 
117
    public function test_normal_session_read_only(): void {
118
        $sess = new \core\session\redis();
119
        $sess->set_requires_write_lock(false);
120
        $sess->init();
121
        $this->assertSame('', $sess->read('sess1'));
122
        $this->assertTrue($sess->close());
123
    }
124
 
125
    public function test_normal_session_start_stop_works(): void {
126
        $sess = new \core\session\redis();
127
        $sess->init();
128
        $sess->set_requires_write_lock(true);
129
        $this->assertTrue($sess->open('Not used', 'Not used'));
130
        $this->assertSame('', $sess->read('sess1'));
131
        $this->assertTrue($sess->write('sess1', 'DATA'));
132
        $this->assertTrue($sess->close());
133
 
134
        // Read the session again to ensure locking did what it should.
135
        $this->assertTrue($sess->open('Not used', 'Not used'));
136
        $this->assertSame('DATA', $sess->read('sess1'));
137
        $this->assertTrue($sess->write('sess1', 'DATA-new'));
138
        $this->assertTrue($sess->close());
139
        $this->assert_session_no_locks();
140
    }
141
 
142
    public function test_compression_read_and_write_works(): void {
143
        global $CFG;
144
 
145
        $CFG->session_redis_compressor = \core\session\redis::COMPRESSION_GZIP;
146
 
147
        $sess = new \core\session\redis();
148
        $sess->init();
149
        $this->assertTrue($sess->write('sess1', 'DATA'));
150
        $this->assertSame('DATA', $sess->read('sess1'));
151
        $this->assertTrue($sess->close());
152
 
153
        if (extension_loaded('zstd')) {
154
            $CFG->session_redis_compressor = \core\session\redis::COMPRESSION_ZSTD;
155
 
156
            $sess = new \core\session\redis();
157
            $sess->init();
158
            $this->assertTrue($sess->write('sess2', 'DATA'));
159
            $this->assertSame('DATA', $sess->read('sess2'));
160
            $this->assertTrue($sess->close());
161
        }
162
 
163
        $CFG->session_redis_compressor = \core\session\redis::COMPRESSION_NONE;
164
    }
165
 
166
    public function test_session_blocks_with_existing_session(): void {
167
        $sess = new \core\session\redis();
168
        $sess->init();
169
        $sess->set_requires_write_lock(true);
170
        $this->assertTrue($sess->open('Not used', 'Not used'));
171
        $this->assertSame('', $sess->read('sess1'));
172
        $this->assertTrue($sess->write('sess1', 'DATA'));
173
        $this->assertTrue($sess->close());
174
 
175
        // Sessions are not locked until they have been saved once.
176
        $this->assertTrue($sess->open('Not used', 'Not used'));
177
        $this->assertSame('DATA', $sess->read('sess1'));
178
 
179
        $sessblocked = new \core\session\redis();
180
        $sessblocked->init();
181
        $sessblocked->set_requires_write_lock(true);
182
        $this->assertTrue($sessblocked->open('Not used', 'Not used'));
183
 
184
        // Trap the error log and send it to stdOut so we can expect output at the right times.
185
        $errorlog = tempnam(sys_get_temp_dir(), "rediserrorlog");
186
        $this->iniSet('error_log', $errorlog);
187
        try {
188
            $sessblocked->read('sess1');
189
            $this->fail('Session lock must fail to be obtained.');
190
        } catch (\core\session\exception $e) {
191
            $this->assertStringContainsString("Unable to obtain lock for session id session_se", $e->getMessage());
192
            $this->assertStringContainsString('within 1 sec.', $e->getMessage());
193
            $this->assertStringContainsString('session lock timeout (1 min 10 secs) ', $e->getMessage());
194
            $this->assertStringContainsString('Cannot obtain session lock for sid: session_sess1', file_get_contents($errorlog));
195
        }
196
 
197
        $this->assertTrue($sessblocked->close());
198
        $this->assertTrue($sess->write('sess1', 'DATA-new'));
199
        $this->assertTrue($sess->close());
200
        $this->assert_session_no_locks();
201
    }
202
 
203
    public function test_session_is_destroyed_when_it_does_not_exist(): void {
204
        $sess = new \core\session\redis();
205
        $sess->init();
206
        $sess->set_requires_write_lock(true);
207
        $this->assertTrue($sess->open('Not used', 'Not used'));
208
        $this->assertTrue($sess->destroy('sess-destroy'));
209
        $this->assert_session_no_locks();
210
    }
211
 
212
    public function test_session_is_destroyed_when_we_have_it_open(): void {
213
        $sess = new \core\session\redis();
214
        $sess->init();
215
        $sess->set_requires_write_lock(true);
216
        $this->assertTrue($sess->open('Not used', 'Not used'));
217
        $this->assertSame('', $sess->read('sess-destroy'));
218
        $this->assertTrue($sess->destroy('sess-destroy'));
219
        $this->assertTrue($sess->close());
220
        $this->assert_session_no_locks();
221
    }
222
 
223
    public function test_multiple_sessions_do_not_interfere_with_each_other(): void {
224
        $sess1 = new \core\session\redis();
225
        $sess1->set_requires_write_lock(true);
226
        $sess1->init();
227
        $sess2 = new \core\session\redis();
228
        $sess2->set_requires_write_lock(true);
229
        $sess2->init();
230
 
231
        // Initialize session 1.
232
        $this->assertTrue($sess1->open('Not used', 'Not used'));
233
        $this->assertSame('', $sess1->read('sess1'));
234
        $this->assertTrue($sess1->write('sess1', 'DATA'));
235
        $this->assertTrue($sess1->close());
236
 
237
        // Initialize session 2.
238
        $this->assertTrue($sess2->open('Not used', 'Not used'));
239
        $this->assertSame('', $sess2->read('sess2'));
240
        $this->assertTrue($sess2->write('sess2', 'DATA2'));
241
        $this->assertTrue($sess2->close());
242
 
243
        // Open and read session 1 and 2.
244
        $this->assertTrue($sess1->open('Not used', 'Not used'));
245
        $this->assertSame('DATA', $sess1->read('sess1'));
246
        $this->assertTrue($sess2->open('Not used', 'Not used'));
247
        $this->assertSame('DATA2', $sess2->read('sess2'));
248
 
249
        // Write both sessions.
250
        $this->assertTrue($sess1->write('sess1', 'DATAX'));
251
        $this->assertTrue($sess2->write('sess2', 'DATA2X'));
252
 
253
        // Read both sessions.
254
        $this->assertTrue($sess1->open('Not used', 'Not used'));
255
        $this->assertTrue($sess2->open('Not used', 'Not used'));
256
        $this->assertEquals('DATAX', $sess1->read('sess1'));
257
        $this->assertEquals('DATA2X', $sess2->read('sess2'));
258
 
259
        // Close both sessions
260
        $this->assertTrue($sess1->close());
261
        $this->assertTrue($sess2->close());
262
 
263
        // Read the session again to ensure locking did what it should.
264
        $this->assert_session_no_locks();
265
    }
266
 
267
    public function test_multiple_sessions_work_with_a_single_instance(): void {
268
        $sess = new \core\session\redis();
269
        $sess->init();
270
        $sess->set_requires_write_lock(true);
271
 
272
        // Initialize session 1.
273
        $this->assertTrue($sess->open('Not used', 'Not used'));
274
        $this->assertSame('', $sess->read('sess1'));
275
        $this->assertTrue($sess->write('sess1', 'DATA'));
276
        $this->assertSame('', $sess->read('sess2'));
277
        $this->assertTrue($sess->write('sess2', 'DATA2'));
278
        $this->assertSame('DATA', $sess->read('sess1'));
279
        $this->assertSame('DATA2', $sess->read('sess2'));
280
        $this->assertTrue($sess->destroy('sess2'));
281
 
282
        $this->assertTrue($sess->close());
283
        $this->assert_session_no_locks();
284
 
285
        $this->assertTrue($sess->close());
286
    }
287
 
288
    public function test_session_exists_returns_valid_values(): void {
289
        $sess = new \core\session\redis();
290
        $sess->init();
291
        $sess->set_requires_write_lock(true);
292
 
293
        $this->assertTrue($sess->open('Not used', 'Not used'));
294
        $this->assertSame('', $sess->read('sess1'));
295
 
296
        $this->assertFalse($sess->session_exists('sess1'), 'Session must not exist yet, it has not been saved');
297
        $this->assertTrue($sess->write('sess1', 'DATA'));
298
        $this->assertTrue($sess->session_exists('sess1'), 'Session must exist now.');
299
        $this->assertTrue($sess->destroy('sess1'));
300
        $this->assertFalse($sess->session_exists('sess1'), 'Session should be destroyed.');
301
    }
302
 
303
    public function test_destroy_removes_the_session_from_redis(): void {
304
        global $DB;
305
 
306
        $sess = new \core\session\redis();
307
        $sess->init();
308
 
309
        $mockhandler = new mock_handler();
310
 
311
        $this->assertTrue($sess->open('Not used', 'Not used'));
312
        $this->assertTrue($sess->write('sess1', 'DATA'));
313
        $this->assertTrue($sess->write('sess2', 'DATA'));
314
        $this->assertTrue($sess->write('sess3', 'DATA'));
315
 
316
        $sessiondata = new \stdClass();
317
        $sessiondata->userid = 2;
318
        $sessiondata->timecreated = time();
319
        $sessiondata->timemodified = time();
320
 
321
        $sessiondata->sid = 'sess1';
322
        $mockhandler->add_test_session($sessiondata);
323
        $sessiondata->sid = 'sess2';
324
        $mockhandler->add_test_session($sessiondata);
325
        $sessiondata->sid = 'sess3';
326
        $mockhandler->add_test_session($sessiondata);
327
 
328
        $this->assertNotEquals('', $sess->read('sess1'));
329
        $sess->destroy('sess1');
330
        $this->assertEquals('', $sess->read('sess1'));
331
 
332
        $this->assertEmpty($this->redis->keys($this->keyprefix.'sess1.lock'));
333
 
334
        $sess->destroy_all();
335
 
336
        $mockhandler = new mock_handler();
337
        $this->assertEquals(
338
            3,
339
            $mockhandler->count_sessions(),
340
            'Moodle handles session database, plugin must not change it.',
341
        );
342
        $this->assert_session_no_locks();
343
        $this->assertEmpty($this->redis->keys($this->keyprefix.'*'), 'There should be no session data left.');
344
    }
345
 
346
    public function test_exception_when_connection_attempts_exceeded(): void {
347
        global $CFG;
348
 
349
        $CFG->session_redis_port = 111111;
350
        $actual = '';
351
 
352
        $sess = new \core\session\redis();
353
        try {
354
            $sess->init();
355
        } catch (RedisException $e) {
356
            $actual = $e->getMessage();
357
        }
358
 
359
        // The Redis session test config allows the user to put the port number inside the host. e.g. 127.0.0.1:6380.
360
        // Therefore, to get the host, we need to explode it.
361
        list($host, ) = explode(':', TEST_SESSION_REDIS_HOST);
362
 
363
        $expected = "Failed to connect (try 3 out of 3) to Redis at $host:111111";
364
        $this->assertDebuggingCalledCount(3);
365
        $this->assertStringContainsString($expected, $actual);
366
    }
367
 
368
    /**
369
     * Assert that we don't have any session locks in Redis.
370
     */
371
    protected function assert_session_no_locks(): void {
372
        $this->assertEmpty($this->redis->keys($this->keyprefix.'*.lock'));
373
    }
374
 
375
    public function test_session_redis_encrypt(): void {
376
        global $CFG;
377
 
378
        $CFG->session_redis_encrypt = ['verify_peer' => false, 'verify_peer_name' => false];
379
 
380
        $sess = new \core\session\redis();
381
 
382
        $prop = new \ReflectionProperty(\core\session\redis::class, 'sslopts');
383
 
384
        $this->assertEquals($CFG->session_redis_encrypt, $prop->getValue($sess));
385
    }
386
 
387
    /**
388
     * Test the get maxlifetime method.
389
     */
390
    public function test_get_maxlifetime(): void {
391
        global $CFG;
392
 
393
        // Set the timeout to something known for the test.
394
        set_config('sessiontimeout', 100);
395
 
396
        // Generate a test user.
397
        $user = $this->getDataGenerator()->create_user();
398
 
399
        // Create a new redis session object.
400
        $session = new \core\session\redis();
401
        $session->init();
402
 
403
        // The get_maxlifetime is private, so we need to use reflection to access it.
404
        $method = new \ReflectionMethod(\core\session\redis::class, 'get_maxlifetime');
405
 
406
        // Test guest timeout, which should be longer.
407
        $result = $method->invoke($session, $CFG->siteguest);
408
        $this->assertEquals(500, $result);
409
 
410
        // Test first access timeout.
411
        $result = $method->invoke($session, 0, true);
412
        $this->assertEquals(180, $result);
413
 
414
        // Test with a real user.
415
        $result = $method->invoke($session, $user->id);
416
        $this->assertEquals(180, $result);
417
 
418
    }
419
 
420
    /**
421
     * Test the add session method.
422
     */
423
    public function test_add_session(): void {
424
 
425
        // Set the timeout to something known for the test.
426
        set_config('sessiontimeout', 100);
427
 
428
        // Generate a test user.
429
        $user = $this->getDataGenerator()->create_user();
430
 
431
        // Create a new redis session object.
432
        $session = new \core\session\redis();
433
        $session->init();
434
 
435
        // Create two sessions for the user.
436
        session_id('id1');
437
        $session1data = $session->add_session($user->id);
438
        session_id('id2');
439
        $session2data = $session->add_session($user->id);
440
 
441
        $session1 = $session->get_session_by_sid('id1');
442
        $session2 = $session->get_session_by_sid('id2');
443
 
444
        // Assert that the sessions were created and have expected data.
445
        $this->assertEqualsCanonicalizing((array)$session1data, (array)$session1);
446
        $this->assertEqualsCanonicalizing((array)$session2data, (array)$session2);
447
 
448
        // Check that the session hash has a ttl set.
449
        $this->assertGreaterThan(-1, $this->redis->ttl($this->keyprefix . 'session_id1'));
450
 
451
        // Check that the session ttl is less or equal to what we set it.
452
        $this->assertLessThanOrEqual(180, $this->redis->ttl($this->keyprefix . 'session_id1'));
453
 
454
    }
455
 
456
    /**
457
     * Test writing session data.
458
     */
459
    public function test_write(): void {
460
        // Set the timeout to something known for the test.
461
        set_config('sessiontimeout', 100);
462
 
463
        // Generate a test user.
464
        $user = $this->getDataGenerator()->create_user();
465
 
466
        // Create a new redis session object.
467
        $session = new \core\session\redis();
468
        $session->init();
469
 
470
        // Create two sessions for the user.
471
        session_id('id1');
472
        $session->add_session($user->id);
473
        session_id('id2');
474
        $session->add_session($user->id);
475
 
476
        $testdata = 'some test data';
477
 
478
        // Write some data to the store.
479
        $result = $session->write('id2', $testdata);
480
 
481
        // Check that the write was successful.
482
        $this->assertTrue($result);
483
 
484
        // Check that the data was written to the store.
485
        $getdata = $this->redis->hget($this->keyprefix . 'session_id2', 'sessdata');
486
        $this->assertStringContainsString($testdata, $getdata);
487
    }
488
 
489
    /**
490
     * Test reading session data.
491
     */
492
    public function test_read(): void {
493
        // Set the timeout to something known for the test.
494
        set_config('sessiontimeout', 100);
495
 
496
        // Generate a test user.
497
        $user = $this->getDataGenerator()->create_user();
498
 
499
        // Create a new redis session object.
500
        $session = new \core\session\redis();
501
        $session->init();
502
 
503
        // Create two sessions for the user.
504
        session_id('id1');
505
        $session->add_session($user->id);
506
        session_id('id2');
507
        $session->add_session($user->id);
508
 
509
        $testdata = 'some test data';
510
 
511
        // Write some session data to the store.
512
        $session->write('id2', $testdata);
513
 
514
        // Read the session data.
515
        $result = $session->read('id2');
516
 
517
        // Check that the read was successful.
518
        $this->assertEquals($result, $testdata);
519
 
520
    }
521
 
522
    /**
523
     * Test updating a session.
524
     */
525
    public function test_update_session(): void {
526
        // Set the timeout to something known for the test.
527
        set_config('sessiontimeout', 100);
528
 
529
        // Generate a test user.
530
        $user = $this->getDataGenerator()->create_user();
531
 
532
        // Create a new redis session object.
533
        $session = new \core\session\redis();
534
        $session->init();
535
 
536
        // Create two sessions for the user.
537
        session_id('id1');
538
        $session->add_session($user->id);
539
        session_id('id2');
540
        $sessiondata = $session->add_session($user->id);
541
 
542
        // Update the session data.
543
        $sessiondata->lastip = '8.8.8.8';
544
        $session->update_session($sessiondata);
545
 
546
        // Check the value was updated.
547
        $updatedsession = $session->get_session_by_sid('id2');
548
        $this->assertEquals('8.8.8.8', $updatedsession->lastip);
549
 
550
        // Test session update when userid is not set, should not error.
551
        unset($sessiondata->userid);
552
        $session->update_session($sessiondata);
553
        $this->assertDebuggingNotCalled();
554
    }
555
 
556
    /**
557
     * Test destroying a session by auth plugin.
558
     */
559
    public function test_destroy_by_auth_plugin(): void {
560
        // Create test users.
561
        $user1 = $this->getDataGenerator()->create_user();
562
        $user2 = $this->getDataGenerator()->create_user(['auth' => 'db']);
563
 
564
        // Create a new redis session object.
565
        $session = new \core\session\redis();
566
        $session->init();
567
 
568
        // Create  sessions for the users.
569
        session_id('id1');
570
        $session1data = $session->add_session($user1->id);
571
        session_id('id2');
572
        $session2data = $session->add_session($user2->id);
573
 
574
        $session1 = $session->get_session_by_sid('id1');
575
        $session2 = $session->get_session_by_sid('id2');
576
 
577
        // Assert that the sessions were created and have expected data.
578
        $this->assertEqualsCanonicalizing((array) $session1data, (array) $session1);
579
        $this->assertEqualsCanonicalizing((array) $session2data, (array) $session2);
580
 
581
        // Destroy the session by auth plugin.
582
        $session->destroy_by_auth_plugin('manual');
583
 
584
        // Check that the session was destroyed.
585
        $this->assertFalse($session->session_exists('id1'));
586
 
587
        // Check the session with db auth plugin was not destroyed.
588
        $this->assertTrue($session->session_exists('id2'));
589
    }
590
}