Debian Codegraph @

tests/phpunit/includes/session/SessionManagerTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Session;
4
5 use DummySessionProvider;
6 use InvalidArgumentException;
7 use MediaWiki\Config\HashConfig;
8 use MediaWiki\Context\RequestContext;
9 use MediaWiki\MainConfigNames;
10 use MediaWiki\Request\FauxRequest;
11 use MediaWiki\Request\ProxyLookup;
12 use MediaWiki\Session\CookieSessionProvider;
13 use MediaWiki\Session\MetadataMergeException;
14 use MediaWiki\Session\PHPSessionHandler;
15 use MediaWiki\Session\Session;
16 use MediaWiki\Session\SessionInfo;
17 use MediaWiki\Session\SessionManager;
18 use MediaWiki\Session\SessionOverflowException;
19 use MediaWiki\Session\SessionProvider;
20 use MediaWiki\Session\UserInfo;
21 use MediaWiki\Utils\MWTimestamp;
22 use MediaWikiIntegrationTestCase;
23 use Psr\Log\LoggerInterface;
24 use Psr\Log\LogLevel;
25 use Psr\Log\NullLogger;
26 use ReflectionClass;
27 use stdClass;
28 use TestLogger;
29 use UnexpectedValueException;
30 use Wikimedia\ScopedCallback;
31 use Wikimedia\TestingAccessWrapper;
32
33 /**
34 * @group Session
35 * @group Database
36 * @covers \MediaWiki\Session\SessionManager
37 */
38 class SessionManagerTest extends MediaWikiIntegrationTestCase {
39 use SessionProviderTestTrait;
40
41 /** @var HashConfig */
42 private $config;
43
44 /** @var TestLogger */
45 private $logger;
46
47 /** @var TestBagOStuff */
48 private $store;
49
50 protected function getManager() {
51 $this->store = new TestBagOStuff();
52 $cacheType = $this->setMainCache( $this->store );
53
54 $this->config = new HashConfig( [
55 MainConfigNames::LanguageCode => 'en',
56 MainConfigNames::SessionCacheType => $cacheType,
57 MainConfigNames::ObjectCacheSessionExpiry => 100,
58 MainConfigNames::SessionProviders => [
59 [ 'class' => DummySessionProvider::class ],
60 ]
61 ] );
62 $this->logger = new TestLogger( false, static function ( $m ) {
63 return ( str_starts_with( $m, 'SessionBackend ' )
64 || str_starts_with( $m, 'SessionManager using store ' )
65 // These were added for T264793 and behave somewhat erratically, not worth testing
66 || str_starts_with( $m, 'Failed to load session, unpersisting' )
67 || preg_match( '/^(Persisting|Unpersisting) session (for|due to)/', $m )
68 ) ? null : $m;
69 } );
70
71 return new SessionManager( [
72 'config' => $this->config,
73 'logger' => $this->logger,
74 'store' => $this->store,
75 ] );
76 }
77
78 protected function objectCacheDef( $object ) {
79 return [ 'factory' => static function () use ( $object ) {
80 return $object;
81 } ];
82 }
83
84 public function testSingleton() {
85 $reset = TestUtils::setSessionManagerSingleton( null );
86
87 $singleton = SessionManager::singleton();
88 $this->assertInstanceOf( SessionManager::class, $singleton );
89 $this->assertSame( $singleton, SessionManager::singleton() );
90 }
91
92 public function testGetGlobalSession() {
93 $context = RequestContext::getMain();
94
95 if ( !PHPSessionHandler::isInstalled() ) {
96 PHPSessionHandler::install( SessionManager::singleton() );
97 }
98 $staticAccess = TestingAccessWrapper::newFromClass( PHPSessionHandler::class );
99 $handler = TestingAccessWrapper::newFromObject( $staticAccess->instance );
100 $oldEnable = $handler->enable;
101 $reset[] = new ScopedCallback( static function () use ( $handler, $oldEnable ) {
102 if ( $handler->enable ) {
103 session_write_close();
104 }
105 $handler->enable = $oldEnable;
106 } );
107 $reset[] = TestUtils::setSessionManagerSingleton( $this->getManager() );
108
109 $handler->enable = true;
110 $request = new FauxRequest();
111 $context->setRequest( $request );
112 $id = $request->getSession()->getId();
113
114 session_write_close();
115 session_id( '' );
116 $session = SessionManager::getGlobalSession();
117 $this->assertSame( $id, $session->getId() );
118
119 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
120 $session = SessionManager::getGlobalSession();
121 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $session->getId() );
122 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $request->getSession()->getId() );
123
124 session_write_close();
125 $handler->enable = false;
126 $request = new FauxRequest();
127 $context->setRequest( $request );
128 $id = $request->getSession()->getId();
129
130 session_id( '' );
131 $session = SessionManager::getGlobalSession();
132 $this->assertSame( $id, $session->getId() );
133
134 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
135 $session = SessionManager::getGlobalSession();
136 $this->assertSame( $id, $session->getId() );
137 $this->assertSame( $id, $request->getSession()->getId() );
138 }
139
140 public function testConstructor() {
141 $manager = TestingAccessWrapper::newFromObject( $this->getManager() );
142 $this->assertSame( $this->config, $manager->config );
143 $this->assertSame( $this->logger, $manager->logger );
144 $this->assertSame( $this->store, $manager->store );
145
146 $manager = TestingAccessWrapper::newFromObject( new SessionManager() );
147 $this->assertSame( $this->getServiceContainer()->getMainConfig(), $manager->config );
148
149 $manager = TestingAccessWrapper::newFromObject( new SessionManager( [
150 'config' => $this->config,
151 'store' => $this->store,
152 ] ) );
153 $this->assertSame( $this->store, $manager->store );
154
155 foreach ( [
156 'config' => '$options[\'config\'] must be an instance of Config',
157 'logger' => '$options[\'logger\'] must be an instance of LoggerInterface',
158 'store' => '$options[\'store\'] must be an instance of BagOStuff',
159 ] as $key => $error ) {
160 try {
161 new SessionManager( [ $key => new stdClass ] );
162 $this->fail( 'Expected exception not thrown' );
163 } catch ( InvalidArgumentException $ex ) {
164 $this->assertSame( $error, $ex->getMessage() );
165 }
166 }
167 }
168
169 public function testGetSessionForRequest() {
170 $manager = $this->getManager();
171 $request = new FauxRequest();
172 $requestUnpersist1 = false;
173 $requestUnpersist2 = false;
174 $requestInfo1 = null;
175 $requestInfo2 = null;
176
177 $id1 = '';
178 $id2 = '';
179 $idEmpty = 'empty-session-------------------';
180
181 $providerBuilder = $this->getMockBuilder( DummySessionProvider::class )
182 ->onlyMethods(
183 [ 'provideSessionInfo', 'newSessionInfo', '__toString', 'describe', 'unpersistSession' ]
184 );
185
186 $provider1 = $providerBuilder->getMock();
187 $provider1->method( 'provideSessionInfo' )
188 ->with( $this->identicalTo( $request ) )
189 ->willReturnCallback( static function ( $request ) use ( &$requestInfo1 ) {
190 return $requestInfo1;
191 } );
192 $provider1->method( 'newSessionInfo' )
193 ->willReturnCallback( static function () use ( $idEmpty, $provider1 ) {
194 return new SessionInfo( SessionInfo::MIN_PRIORITY, [
195 'provider' => $provider1,
196 'id' => $idEmpty,
197 'persisted' => true,
198 'idIsSafe' => true,
199 ] );
200 } );
201 $provider1->method( '__toString' )
202 ->willReturn( 'Provider1' );
203 $provider1->method( 'describe' )
204 ->willReturn( '#1 sessions' );
205 $provider1->method( 'unpersistSession' )
206 ->willReturnCallback( static function ( $request ) use ( &$requestUnpersist1 ) {
207 $requestUnpersist1 = true;
208 } );
209
210 $provider2 = $providerBuilder->getMock();
211 $provider2->method( 'provideSessionInfo' )
212 ->with( $this->identicalTo( $request ) )
213 ->willReturnCallback( static function ( $request ) use ( &$requestInfo2 ) {
214 return $requestInfo2;
215 } );
216 $provider2->method( '__toString' )
217 ->willReturn( 'Provider2' );
218 $provider2->method( 'describe' )
219 ->willReturn( '#2 sessions' );
220 $provider2->method( 'unpersistSession' )
221 ->willReturnCallback( static function ( $request ) use ( &$requestUnpersist2 ) {
222 $requestUnpersist2 = true;
223 } );
224
225 $this->config->set( MainConfigNames::SessionProviders, [
226 $this->objectCacheDef( $provider1 ),
227 $this->objectCacheDef( $provider2 ),
228 ] );
229
230 // No provider returns info
231 $session = $manager->getSessionForRequest( $request );
232 $this->assertInstanceOf( Session::class, $session );
233 $this->assertSame( $idEmpty, $session->getId() );
234 $this->assertFalse( $requestUnpersist1 );
235 $this->assertFalse( $requestUnpersist2 );
236
237 // Both providers return info, picks best one
238 $requestInfo1 = new SessionInfo( SessionInfo::MIN_PRIORITY + 1, [
239 'provider' => $provider1,
240 'id' => ( $id1 = $manager->generateSessionId() ),
241 'persisted' => true,
242 'idIsSafe' => true,
243 ] );
244 $requestInfo2 = new SessionInfo( SessionInfo::MIN_PRIORITY + 2, [
245 'provider' => $provider2,
246 'id' => ( $id2 = $manager->generateSessionId() ),
247 'persisted' => true,
248 'idIsSafe' => true,
249 ] );
250 $session = $manager->getSessionForRequest( $request );
251 $this->assertInstanceOf( Session::class, $session );
252 $this->assertSame( $id2, $session->getId() );
253 $this->assertFalse( $requestUnpersist1 );
254 $this->assertFalse( $requestUnpersist2 );
255
256 $requestInfo1 = new SessionInfo( SessionInfo::MIN_PRIORITY + 2, [
257 'provider' => $provider1,
258 'id' => ( $id1 = $manager->generateSessionId() ),
259 'persisted' => true,
260 'idIsSafe' => true,
261 ] );
262 $requestInfo2 = new SessionInfo( SessionInfo::MIN_PRIORITY + 1, [
263 'provider' => $provider2,
264 'id' => ( $id2 = $manager->generateSessionId() ),
265 'persisted' => true,
266 'idIsSafe' => true,
267 ] );
268 $session = $manager->getSessionForRequest( $request );
269 $this->assertInstanceOf( Session::class, $session );
270 $this->assertSame( $id1, $session->getId() );
271 $this->assertFalse( $requestUnpersist1 );
272 $this->assertFalse( $requestUnpersist2 );
273
274 // Tied priorities
275 $requestInfo1 = new SessionInfo( SessionInfo::MAX_PRIORITY, [
276 'provider' => $provider1,
277 'id' => ( $id1 = $manager->generateSessionId() ),
278 'persisted' => true,
279 'userInfo' => UserInfo::newAnonymous(),
280 'idIsSafe' => true,
281 ] );
282 $requestInfo2 = new SessionInfo( SessionInfo::MAX_PRIORITY, [
283 'provider' => $provider2,
284 'id' => ( $id2 = $manager->generateSessionId() ),
285 'persisted' => true,
286 'userInfo' => UserInfo::newAnonymous(),
287 'idIsSafe' => true,
288 ] );
289 try {
290 $manager->getSessionForRequest( $request );
291 $this->fail( 'Expcected exception not thrown' );
292 } catch ( SessionOverflowException $ex ) {
293 $this->assertStringStartsWith(
294 'Multiple sessions for this request tied for top priority: ',
295 $ex->getMessage()
296 );
297 $this->assertCount( 2, $ex->getSessionInfos() );
298 $this->assertContains( $requestInfo1, $ex->getSessionInfos() );
299 $this->assertContains( $requestInfo2, $ex->getSessionInfos() );
300 }
301 $this->assertFalse( $requestUnpersist1 );
302 $this->assertFalse( $requestUnpersist2 );
303
304 // Bad provider
305 $requestInfo1 = new SessionInfo( SessionInfo::MAX_PRIORITY, [
306 'provider' => $provider2,
307 'id' => ( $id1 = $manager->generateSessionId() ),
308 'persisted' => true,
309 'idIsSafe' => true,
310 ] );
311 $requestInfo2 = null;
312 try {
313 $manager->getSessionForRequest( $request );
314 $this->fail( 'Expcected exception not thrown' );
315 } catch ( UnexpectedValueException $ex ) {
316 $this->assertSame(
317 'Provider1 returned session info for a different provider: ' . $requestInfo1,
318 $ex->getMessage()
319 );
320 }
321 $this->assertFalse( $requestUnpersist1 );
322 $this->assertFalse( $requestUnpersist2 );
323
324 // Unusable session info
325 $this->logger->setCollect( true );
326 $requestInfo1 = new SessionInfo( SessionInfo::MAX_PRIORITY, [
327 'provider' => $provider1,
328 'id' => ( $id1 = $manager->generateSessionId() ),
329 'persisted' => true,
330 'userInfo' => UserInfo::newFromName( 'TestGetSessionForRequest', false ),
331 'idIsSafe' => true,
332 ] );
333 $requestInfo2 = new SessionInfo( SessionInfo::MIN_PRIORITY, [
334 'provider' => $provider2,
335 'id' => ( $id2 = $manager->generateSessionId() ),
336 'persisted' => true,
337 'idIsSafe' => true,
338 ] );
339 $session = $manager->getSessionForRequest( $request );
340 $this->assertInstanceOf( Session::class, $session );
341 $this->assertSame( $id2, $session->getId() );
342 $this->logger->setCollect( false );
343 $this->assertTrue( $requestUnpersist1 );
344 $this->assertFalse( $requestUnpersist2 );
345 $requestUnpersist1 = false;
346
347 $this->logger->setCollect( true );
348 $requestInfo1 = new SessionInfo( SessionInfo::MAX_PRIORITY, [
349 'provider' => $provider1,
350 'id' => ( $id1 = $manager->generateSessionId() ),
351 'persisted' => true,
352 'idIsSafe' => true,
353 ] );
354 $requestInfo2 = new SessionInfo( SessionInfo::MAX_PRIORITY, [
355 'provider' => $provider2,
356 'id' => ( $id2 = $manager->generateSessionId() ),
357 'persisted' => true,
358 'userInfo' => UserInfo::newFromName( 'TestGetSessionForRequest', false ),
359 'idIsSafe' => true,
360 ] );
361 $session = $manager->getSessionForRequest( $request );
362 $this->assertInstanceOf( Session::class, $session );
363 $this->assertSame( $id1, $session->getId() );
364 $this->logger->setCollect( false );
365 $this->assertFalse( $requestUnpersist1 );
366 $this->assertTrue( $requestUnpersist2 );
367 $requestUnpersist2 = false;
368
369 // Unpersisted session ID
370 $requestInfo1 = new SessionInfo( SessionInfo::MAX_PRIORITY, [
371 'provider' => $provider1,
372 'id' => ( $id1 = $manager->generateSessionId() ),
373 'persisted' => false,
374 'userInfo' => UserInfo::newFromName( 'TestGetSessionForRequest', true ),
375 'idIsSafe' => true,
376 ] );
377 $requestInfo2 = null;
378 $session = $manager->getSessionForRequest( $request );
379 $this->assertInstanceOf( Session::class, $session );
380 $this->assertSame( $id1, $session->getId() );
381 $this->assertTrue( $requestUnpersist1 ); // The saving of the session does it
382 $this->assertFalse( $requestUnpersist2 );
383 $session->persist();
384 $this->assertTrue( $session->isPersistent() );
385 }
386
387 public function testGetSessionById() {
388 $manager = $this->getManager();
389 try {
390 $manager->getSessionById( 'bad' );
391 $this->fail( 'Expected exception not thrown' );
392 } catch ( InvalidArgumentException $ex ) {
393 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
394 }
395
396 // Unknown session ID
397 $id = $manager->generateSessionId();
398 $session = $manager->getSessionById( $id, true );
399 $this->assertInstanceOf( Session::class, $session );
400 $this->assertSame( $id, $session->getId() );
401
402 $id = $manager->generateSessionId();
403 $this->assertNull( $manager->getSessionById( $id, false ) );
404
405 $userIdentity = $this->getTestSysop()->getUserIdentity();
406 // Known but unloadable session ID
407 $this->logger->setCollect( true );
408 $id = $manager->generateSessionId();
409 $this->store->setSession( $id, [ 'metadata' => [
410 'userId' => $userIdentity->getId(),
411 'userToken' => 'bad',
412 ] ] );
413
414 $this->assertNull( $manager->getSessionById( $id, true ) );
415 $this->assertNull( $manager->getSessionById( $id, false ) );
416 $this->logger->setCollect( false );
417
418 // Known session ID
419 $this->store->setSession( $id, [] );
420 $session = $manager->getSessionById( $id, false );
421 $this->assertInstanceOf( Session::class, $session );
422 $this->assertSame( $id, $session->getId() );
423
424 // Store isn't checked if the session is already loaded
425 $this->store->setSession( $id, [ 'metadata' => [
426 'userId' => $userIdentity->getId(),
427 'userToken' => 'bad',
428 ] ] );
429 $session2 = $manager->getSessionById( $id, false );
430 $this->assertInstanceOf( Session::class, $session2 );
431 $this->assertSame( $id, $session2->getId() );
432 unset( $session, $session2 );
433 $this->logger->setCollect( true );
434 $this->assertNull( $manager->getSessionById( $id, true ) );
435 $this->logger->setCollect( false );
436
437 // Failure to create an empty session
438 $manager = $this->getManager();
439 $provider = $this->getMockBuilder( DummySessionProvider::class )
440 ->onlyMethods( [ 'provideSessionInfo', 'newSessionInfo', '__toString' ] )
441 ->getMock();
442 $provider->method( 'provideSessionInfo' )
443 ->willReturn( null );
444 $provider->method( 'newSessionInfo' )
445 ->willReturn( null );
446 $provider->method( '__toString' )
447 ->willReturn( 'MockProvider' );
448 $this->config->set( MainConfigNames::SessionProviders, [
449 $this->objectCacheDef( $provider ),
450 ] );
451 $this->logger->setCollect( true );
452 $this->assertNull( $manager->getSessionById( $id, true ) );
453 $this->logger->setCollect( false );
454 $this->assertSame( [
455 [ LogLevel::ERROR, 'Failed to create empty session: {exception}' ]
456 ], $this->logger->getBuffer() );
457 }
458
459 public function testGetEmptySession() {
460 $manager = $this->getManager();
461 $pmanager = TestingAccessWrapper::newFromObject( $manager );
462
463 $providerBuilder = $this->getMockBuilder( DummySessionProvider::class )
464 ->onlyMethods( [ 'provideSessionInfo', 'newSessionInfo', '__toString' ] );
465
466 $expectId = null;
467 $info1 = null;
468 $info2 = null;
469
470 $provider1 = $providerBuilder->getMock();
471 $provider1->method( 'provideSessionInfo' )
472 ->willReturn( null );
473 $provider1->method( 'newSessionInfo' )
474 ->with( $this->callback( static function ( $id ) use ( &$expectId ) {
475 return $id === $expectId;
476 } ) )
477 ->willReturnCallback( static function () use ( &$info1 ) {
478 return $info1;
479 } );
480 $provider1->method( '__toString' )
481 ->willReturn( 'MockProvider1' );
482
483 $provider2 = $providerBuilder->getMock();
484 $provider2->method( 'provideSessionInfo' )
485 ->willReturn( null );
486 $provider2->method( 'newSessionInfo' )
487 ->with( $this->callback( static function ( $id ) use ( &$expectId ) {
488 return $id === $expectId;
489 } ) )
490 ->willReturnCallback( static function () use ( &$info2 ) {
491 return $info2;
492 } );
493 $provider1->method( '__toString' )
494 ->willReturn( 'MockProvider2' );
495
496 $this->config->set( MainConfigNames::SessionProviders, [
497 $this->objectCacheDef( $provider1 ),
498 $this->objectCacheDef( $provider2 ),
499 ] );
500
501 // No info
502 $expectId = null;
503 $info1 = null;
504 $info2 = null;
505 try {
506 $manager->getEmptySession();
507 $this->fail( 'Expected exception not thrown' );
508 } catch ( UnexpectedValueException $ex ) {
509 $this->assertSame(
510 'No provider could provide an empty session!',
511 $ex->getMessage()
512 );
513 }
514
515 // Info
516 $expectId = null;
517 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, [
518 'provider' => $provider1,
519 'id' => 'empty---------------------------',
520 'persisted' => true,
521 'idIsSafe' => true,
522 ] );
523 $info2 = null;
524 $session = $manager->getEmptySession();
525 $this->assertInstanceOf( Session::class, $session );
526 $this->assertSame( 'empty---------------------------', $session->getId() );
527
528 // Info, explicitly
529 $expectId = 'expected------------------------';
530 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, [
531 'provider' => $provider1,
532 'id' => $expectId,
533 'persisted' => true,
534 'idIsSafe' => true,
535 ] );
536 $info2 = null;
537 $session = $pmanager->getEmptySessionInternal( null, $expectId );
538 $this->assertInstanceOf( Session::class, $session );
539 $this->assertSame( $expectId, $session->getId() );
540
541 // Wrong ID
542 $expectId = 'expected-----------------------2';
543 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, [
544 'provider' => $provider1,
545 'id' => "un$expectId",
546 'persisted' => true,
547 'idIsSafe' => true,
548 ] );
549 $info2 = null;
550 try {
551 $pmanager->getEmptySessionInternal( null, $expectId );
552 $this->fail( 'Expected exception not thrown' );
553 } catch ( UnexpectedValueException $ex ) {
554 $this->assertSame(
555 'MockProvider1 returned empty session info with a wrong id: ' .
556 "un$expectId != $expectId",
557 $ex->getMessage()
558 );
559 }
560
561 // Unsafe ID
562 $expectId = 'expected-----------------------2';
563 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, [
564 'provider' => $provider1,
565 'id' => $expectId,
566 'persisted' => true,
567 ] );
568 $info2 = null;
569 try {
570 $pmanager->getEmptySessionInternal( null, $expectId );
571 $this->fail( 'Expected exception not thrown' );
572 } catch ( UnexpectedValueException $ex ) {
573 $this->assertSame(
574 'MockProvider1 returned empty session info with id flagged unsafe',
575 $ex->getMessage()
576 );
577 }
578
579 // Wrong provider
580 $expectId = null;
581 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, [
582 'provider' => $provider2,
583 'id' => 'empty---------------------------',
584 'persisted' => true,
585 'idIsSafe' => true,
586 ] );
587 $info2 = null;
588 try {
589 $manager->getEmptySession();
590 $this->fail( 'Expected exception not thrown' );
591 } catch ( UnexpectedValueException $ex ) {
592 $this->assertSame(
593 'MockProvider1 returned an empty session info for a different provider: ' . $info1,
594 $ex->getMessage()
595 );
596 }
597
598 // Highest priority wins
599 $expectId = null;
600 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY + 1, [
601 'provider' => $provider1,
602 'id' => 'empty1--------------------------',
603 'persisted' => true,
604 'idIsSafe' => true,
605 ] );
606 $info2 = new SessionInfo( SessionInfo::MIN_PRIORITY, [
607 'provider' => $provider2,
608 'id' => 'empty2--------------------------',
609 'persisted' => true,
610 'idIsSafe' => true,
611 ] );
612 $session = $manager->getEmptySession();
613 $this->assertInstanceOf( Session::class, $session );
614 $this->assertSame( 'empty1--------------------------', $session->getId() );
615
616 $expectId = null;
617 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY + 1, [
618 'provider' => $provider1,
619 'id' => 'empty1--------------------------',
620 'persisted' => true,
621 'idIsSafe' => true,
622 ] );
623 $info2 = new SessionInfo( SessionInfo::MIN_PRIORITY + 2, [
624 'provider' => $provider2,
625 'id' => 'empty2--------------------------',
626 'persisted' => true,
627 'idIsSafe' => true,
628 ] );
629 $session = $manager->getEmptySession();
630 $this->assertInstanceOf( Session::class, $session );
631 $this->assertSame( 'empty2--------------------------', $session->getId() );
632
633 // Tied priorities throw an exception
634 $expectId = null;
635 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, [
636 'provider' => $provider1,
637 'id' => 'empty1--------------------------',
638 'persisted' => true,
639 'userInfo' => UserInfo::newAnonymous(),
640 'idIsSafe' => true,
641 ] );
642 $info2 = new SessionInfo( SessionInfo::MIN_PRIORITY, [
643 'provider' => $provider2,
644 'id' => 'empty2--------------------------',
645 'persisted' => true,
646 'userInfo' => UserInfo::newAnonymous(),
647 'idIsSafe' => true,
648 ] );
649 try {
650 $manager->getEmptySession();
651 $this->fail( 'Expected exception not thrown' );
652 } catch ( UnexpectedValueException $ex ) {
653 $this->assertStringStartsWith(
654 'Multiple empty sessions tied for top priority: ',
655 $ex->getMessage()
656 );
657 }
658
659 // Bad id
660 try {
661 $pmanager->getEmptySessionInternal( null, 'bad' );
662 $this->fail( 'Expected exception not thrown' );
663 } catch ( InvalidArgumentException $ex ) {
664 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
665 }
666
667 // Session already exists
668 $expectId = 'expected-----------------------3';
669 $this->store->setSessionMeta( $expectId, [
670 'provider' => 'MockProvider2',
671 'userId' => 0,
672 'userName' => null,
673 'userToken' => null,
674 ] );
675 try {
676 $pmanager->getEmptySessionInternal( null, $expectId );
677 $this->fail( 'Expected exception not thrown' );
678 } catch ( InvalidArgumentException $ex ) {
679 $this->assertSame( 'Session ID already exists', $ex->getMessage() );
680 }
681 }
682
683 public function testInvalidateSessionsForUser() {
684 $user = $this->getTestSysop()->getUser();
685 $manager = $this->getManager();
686
687 $providerBuilder = $this->getMockBuilder( DummySessionProvider::class )
688 ->onlyMethods( [ 'invalidateSessionsForUser', '__toString' ] );
689
690 $provider1 = $providerBuilder->getMock();
691 $provider1->expects( $this->once() )->method( 'invalidateSessionsForUser' )
692 ->with( $this->identicalTo( $user ) );
693 $provider1->method( '__toString' )
694 ->willReturn( 'MockProvider1' );
695
696 $provider2 = $providerBuilder->getMock();
697 $provider2->expects( $this->once() )->method( 'invalidateSessionsForUser' )
698 ->with( $this->identicalTo( $user ) );
699 $provider2->method( '__toString' )
700 ->willReturn( 'MockProvider2' );
701
702 $this->config->set( MainConfigNames::SessionProviders, [
703 $this->objectCacheDef( $provider1 ),
704 $this->objectCacheDef( $provider2 ),
705 ] );
706
707 $oldToken = $user->getToken( true );
708 $manager->invalidateSessionsForUser( $user );
709 $this->assertNotEquals( $oldToken, $user->getToken() );
710 }
711
712 public function testGetVaryHeaders() {
713 $manager = $this->getManager();
714
715 $providerBuilder = $this->getMockBuilder( DummySessionProvider::class )
716 ->onlyMethods( [ 'getVaryHeaders', '__toString' ] );
717
718 $provider1 = $providerBuilder->getMock();
719 $provider1->expects( $this->once() )->method( 'getVaryHeaders' )
720 ->willReturn( [
721 'Foo' => null,
722 'Bar' => [ 'X', 'Bar1' ],
723 'Quux' => null,
724 ] );
725 $provider1->method( '__toString' )
726 ->willReturn( 'MockProvider1' );
727
728 $provider2 = $providerBuilder->getMock();
729 $provider2->expects( $this->once() )->method( 'getVaryHeaders' )
730 ->willReturn( [
731 'Baz' => null,
732 'Bar' => [ 'X', 'Bar2' ],
733 'Quux' => [ 'Quux' ],
734 ] );
735 $provider2->method( '__toString' )
736 ->willReturn( 'MockProvider2' );
737
738 $this->config->set( MainConfigNames::SessionProviders, [
739 $this->objectCacheDef( $provider1 ),
740 $this->objectCacheDef( $provider2 ),
741 ] );
742
743 $expect = [
744 'Foo' => null,
745 'Bar' => null,
746 'Quux' => null,
747 'Baz' => null,
748 ];
749
750 $this->assertEquals( $expect, $manager->getVaryHeaders() );
751
752 // Again, to ensure it's cached
753 $this->assertEquals( $expect, $manager->getVaryHeaders() );
754 }
755
756 public function testGetVaryCookies() {
757 $manager = $this->getManager();
758
759 $providerBuilder = $this->getMockBuilder( DummySessionProvider::class )
760 ->onlyMethods( [ 'getVaryCookies', '__toString' ] );
761
762 $provider1 = $providerBuilder->getMock();
763 $provider1->expects( $this->once() )->method( 'getVaryCookies' )
764 ->willReturn( [ 'Foo', 'Bar' ] );
765 $provider1->method( '__toString' )
766 ->willReturn( 'MockProvider1' );
767
768 $provider2 = $providerBuilder->getMock();
769 $provider2->expects( $this->once() )->method( 'getVaryCookies' )
770 ->willReturn( [ 'Foo', 'Baz' ] );
771 $provider2->method( '__toString' )
772 ->willReturn( 'MockProvider2' );
773
774 $this->config->set( MainConfigNames::SessionProviders, [
775 $this->objectCacheDef( $provider1 ),
776 $this->objectCacheDef( $provider2 ),
777 ] );
778
779 $expect = [ 'Foo', 'Bar', 'Baz' ];
780
781 $this->assertEquals( $expect, $manager->getVaryCookies() );
782
783 // Again, to ensure it's cached
784 $this->assertEquals( $expect, $manager->getVaryCookies() );
785 }
786
787 public function testGetProviders() {
788 $realManager = $this->getManager();
789 $manager = TestingAccessWrapper::newFromObject( $realManager );
790
791 $this->config->set( MainConfigNames::SessionProviders, [
792 [ 'class' => DummySessionProvider::class ],
793 ] );
794 $providers = $manager->getProviders();
795 $this->assertArrayHasKey( 'DummySessionProvider', $providers );
796 $provider = TestingAccessWrapper::newFromObject( $providers['DummySessionProvider'] );
797 $this->assertSame( $manager->logger, $provider->logger );
798 $this->assertSame( $manager->config, $provider->getConfig() );
799 $this->assertSame( $realManager, $provider->getManager() );
800
801 $this->config->set( MainConfigNames::SessionProviders, [
802 [ 'class' => DummySessionProvider::class ],
803 [ 'class' => DummySessionProvider::class ],
804 ] );
805 $manager->sessionProviders = null;
806 try {
807 $manager->getProviders();
808 $this->fail( 'Expected exception not thrown' );
809 } catch ( UnexpectedValueException $ex ) {
810 $this->assertSame(
811 'Duplicate provider name "DummySessionProvider"',
812 $ex->getMessage()
813 );
814 }
815 }
816
817 public function testShutdown() {
818 $manager = TestingAccessWrapper::newFromObject( $this->getManager() );
819 $manager->setLogger( new NullLogger() );
820
821 $mock = $this->getMockBuilder( stdClass::class )
822 ->addMethods( [ 'shutdown' ] )->getMock();
823 $mock->expects( $this->once() )->method( 'shutdown' );
824
825 $manager->allSessionBackends = [ $mock ];
826 $manager->shutdown();
827 }
828
829 public function testGetSessionFromInfo() {
830 $manager = TestingAccessWrapper::newFromObject( $this->getManager() );
831 $request = new FauxRequest();
832
833 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
834
835 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
836 'provider' => $manager->getProvider( 'DummySessionProvider' ),
837 'id' => $id,
838 'persisted' => true,
839 'userInfo' => UserInfo::newFromName( 'TestGetSessionFromInfo', true ),
840 'idIsSafe' => true,
841 ] );
842 TestingAccessWrapper::newFromObject( $info )->idIsSafe = true;
843 $session1 = TestingAccessWrapper::newFromObject(
844 $manager->getSessionFromInfo( $info, $request )
845 );
846 $session2 = TestingAccessWrapper::newFromObject(
847 $manager->getSessionFromInfo( $info, $request )
848 );
849
850 $this->assertSame( $session1->backend, $session2->backend );
851 $this->assertNotEquals( $session1->index, $session2->index );
852 $this->assertSame( $session1->getSessionId(), $session2->getSessionId() );
853 $this->assertSame( $id, $session1->getId() );
854
855 TestingAccessWrapper::newFromObject( $info )->idIsSafe = false;
856 $session3 = $manager->getSessionFromInfo( $info, $request );
857 $this->assertNotSame( $id, $session3->getId() );
858 }
859
860 public function testBackendRegistration() {
861 $manager = $this->getManager();
862
863 $session = $manager->getSessionForRequest( new FauxRequest );
864 $backend = TestingAccessWrapper::newFromObject( $session )->backend;
865 $sessionId = $session->getSessionId();
866 $id = (string)$sessionId;
867
868 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
869
870 $manager->changeBackendId( $backend );
871 $this->assertSame( $sessionId, $session->getSessionId() );
872 $this->assertNotEquals( $id, (string)$sessionId );
873 $id = (string)$sessionId;
874
875 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
876
877 // Destruction of the session here causes the backend to be deregistered
878 $session = null;
879
880 try {
881 $manager->changeBackendId( $backend );
882 $this->fail( 'Expected exception not thrown' );
883 } catch ( InvalidArgumentException $ex ) {
884 $this->assertSame(
885 'Backend was not registered with this SessionManager', $ex->getMessage()
886 );
887 }
888
889 try {
890 $manager->deregisterSessionBackend( $backend );
891 $this->fail( 'Expected exception not thrown' );
892 } catch ( InvalidArgumentException $ex ) {
893 $this->assertSame(
894 'Backend was not registered with this SessionManager', $ex->getMessage()
895 );
896 }
897
898 $session = $manager->getSessionById( $id, true );
899 $this->assertSame( $sessionId, $session->getSessionId() );
900 }
901
902 public function testGenerateSessionId() {
903 $manager = $this->getManager();
904
905 $id = $manager->generateSessionId();
906 $this->assertTrue( SessionManager::validateSessionId( $id ), "Generated ID: $id" );
907 }
908
909 public function testPreventSessionsForUser() {
910 $manager = $this->getManager();
911
912 $providerBuilder = $this->getMockBuilder( DummySessionProvider::class )
913 ->onlyMethods( [ 'preventSessionsForUser', '__toString' ] );
914
915 $username = 'TestPreventSessionsForUser';
916 $provider1 = $providerBuilder->getMock();
917 $provider1->expects( $this->once() )->method( 'preventSessionsForUser' )
918 ->with( $username );
919 $provider1->method( '__toString' )
920 ->willReturn( 'MockProvider1' );
921
922 $this->config->set( MainConfigNames::SessionProviders, [
923 $this->objectCacheDef( $provider1 ),
924 ] );
925
926 $this->assertFalse( $manager->isUserSessionPrevented( $username ) );
927 $manager->preventSessionsForUser( $username );
928 $this->assertTrue( $manager->isUserSessionPrevented( $username ) );
929 }
930
931 public function testLoadSessionInfoFromStore() {
932 $manager = $this->getManager();
933 $logger = new TestLogger( true );
934 $manager->setLogger( $logger );
935 $request = new FauxRequest();
936
937 // TestingAccessWrapper can't handle methods with reference arguments, sigh.
938 $rClass = new ReflectionClass( $manager );
939 $rMethod = $rClass->getMethod( 'loadSessionInfoFromStore' );
940 $loadSessionInfoFromStore = static function ( &$info ) use ( $rMethod, $manager, $request ) {
941 return $rMethod->invokeArgs( $manager, [ &$info, $request ] );
942 };
943
944 $username = $this->getTestSysop()->getUserIdentity()->getName();
945 $userInfo = UserInfo::newFromName( $username, true );
946 $unverifiedUserInfo = UserInfo::newFromName( $username, false );
947
948 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
949 $metadata = [
950 'userId' => $userInfo->getId(),
951 'userName' => $userInfo->getName(),
952 'userToken' => $userInfo->getToken( true ),
953 'provider' => 'Mock',
954 ];
955
956 $builder = $this->getMockBuilder( SessionProvider::class )
957 ->onlyMethods( [ '__toString', 'mergeMetadata', 'refreshSessionInfo' ] );
958
959 $provider = $builder->getMockForAbstractClass();
960 $this->initProvider( $provider, null, null, $manager );
961 $provider->method( 'persistsSessionId' )
962 ->willReturn( true );
963 $provider->method( 'canChangeUser' )
964 ->willReturn( true );
965 $provider->method( 'refreshSessionInfo' )
966 ->willReturn( true );
967 $provider->method( '__toString' )
968 ->willReturn( 'Mock' );
969 $provider->method( 'mergeMetadata' )
970 ->willReturnCallback( static function ( $a, $b ) {
971 if ( $b === [ 'Throw' ] ) {
972 throw new MetadataMergeException( 'no merge!' );
973 }
974 return [ 'Merged' ];
975 } );
976
977 $provider2 = $builder->getMockForAbstractClass();
978 $this->initProvider( $provider2, null, null, $manager );
979 $provider2->method( 'persistsSessionId' )
980 ->willReturn( false );
981 $provider2->method( 'canChangeUser' )
982 ->willReturn( false );
983 $provider2->method( '__toString' )
984 ->willReturn( 'Mock2' );
985 $provider2->method( 'refreshSessionInfo' )
986 ->willReturnCallback( static function ( $info, $request, &$metadata ) {
987 $metadata['changed'] = true;
988 return true;
989 } );
990
991 $provider3 = $builder->getMockForAbstractClass();
992 $this->initProvider( $provider3, null, null, $manager );
993 $provider3->method( 'persistsSessionId' )
994 ->willReturn( true );
995 $provider3->method( 'canChangeUser' )
996 ->willReturn( true );
997 $provider3->expects( $this->once() )->method( 'refreshSessionInfo' )
998 ->willReturn( false );
999 $provider3->method( '__toString' )
1000 ->willReturn( 'Mock3' );
1001
1002 TestingAccessWrapper::newFromObject( $manager )->sessionProviders = [
1003 (string)$provider => $provider,
1004 (string)$provider2 => $provider2,
1005 (string)$provider3 => $provider3,
1006 ];
1007
1008 // No metadata, basic usage
1009 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1010 'provider' => $provider,
1011 'id' => $id,
1012 'userInfo' => $userInfo
1013 ] );
1014 $this->assertFalse( $info->isIdSafe() );
1015 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1016 $this->assertFalse( $info->isIdSafe() );
1017 $this->assertSame( [], $logger->getBuffer() );
1018
1019 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1020 'provider' => $provider,
1021 'userInfo' => $userInfo
1022 ] );
1023 $this->assertTrue( $info->isIdSafe() );
1024 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1025 $this->assertTrue( $info->isIdSafe() );
1026 $this->assertSame( [], $logger->getBuffer() );
1027
1028 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1029 'provider' => $provider2,
1030 'id' => $id,
1031 'userInfo' => $userInfo
1032 ] );
1033 $this->assertFalse( $info->isIdSafe() );
1034 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1035 $this->assertTrue( $info->isIdSafe() );
1036 $this->assertSame( [], $logger->getBuffer() );
1037
1038 // Unverified user, no metadata
1039 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1040 'provider' => $provider,
1041 'id' => $id,
1042 'userInfo' => $unverifiedUserInfo
1043 ] );
1044 $this->assertSame( $unverifiedUserInfo, $info->getUserInfo() );
1045 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1046 $this->assertSame( [
1047 [
1048 LogLevel::INFO,
1049 'Session "{session}": Unverified user provided and no metadata to auth it',
1050 ]
1051 ], $logger->getBuffer() );
1052 $logger->clearBuffer();
1053
1054 // No metadata, missing data
1055 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1056 'id' => $id,
1057 'userInfo' => $userInfo
1058 ] );
1059 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1060 $this->assertSame( [
1061 [ LogLevel::WARNING, 'Session "{session}": Null provider and no metadata' ],
1062 ], $logger->getBuffer() );
1063 $logger->clearBuffer();
1064
1065 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1066 'provider' => $provider,
1067 'id' => $id,
1068 ] );
1069 $this->assertFalse( $info->isIdSafe() );
1070 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1071 $this->assertInstanceOf( UserInfo::class, $info->getUserInfo() );
1072 $this->assertTrue( $info->getUserInfo()->isVerified() );
1073 $this->assertTrue( $info->getUserInfo()->isAnon() );
1074 $this->assertFalse( $info->isIdSafe() );
1075 $this->assertSame( [], $logger->getBuffer() );
1076
1077 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1078 'provider' => $provider2,
1079 'id' => $id,
1080 ] );
1081 $this->assertFalse( $info->isIdSafe() );
1082 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1083 $this->assertSame( [
1084 [ LogLevel::INFO, 'Session "{session}": No user provided and provider cannot set user' ]
1085 ], $logger->getBuffer() );
1086 $logger->clearBuffer();
1087
1088 // Incomplete/bad metadata
1089 $this->store->setRawSession( $id, true );
1090 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1091 $this->assertSame( [
1092 [ LogLevel::WARNING, 'Session "{session}": Bad data' ],
1093 ], $logger->getBuffer() );
1094 $logger->clearBuffer();
1095
1096 $this->store->setRawSession( $id, [ 'data' => [] ] );
1097 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1098 $this->assertSame( [
1099 [ LogLevel::WARNING, 'Session "{session}": Bad data structure' ],
1100 ], $logger->getBuffer() );
1101 $logger->clearBuffer();
1102
1103 $this->store->deleteSession( $id );
1104 $this->store->setRawSession( $id, [ 'metadata' => $metadata ] );
1105 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1106 $this->assertSame( [
1107 [ LogLevel::WARNING, 'Session "{session}": Bad data structure' ],
1108 ], $logger->getBuffer() );
1109 $logger->clearBuffer();
1110
1111 $this->store->setRawSession( $id, [ 'metadata' => $metadata, 'data' => true ] );
1112 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1113 $this->assertSame( [
1114 [ LogLevel::WARNING, 'Session "{session}": Bad data structure' ],
1115 ], $logger->getBuffer() );
1116 $logger->clearBuffer();
1117
1118 $this->store->setRawSession( $id, [ 'metadata' => true, 'data' => [] ] );
1119 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1120 $this->assertSame( [
1121 [ LogLevel::WARNING, 'Session "{session}": Bad data structure' ],
1122 ], $logger->getBuffer() );
1123 $logger->clearBuffer();
1124
1125 foreach ( $metadata as $key => $dummy ) {
1126 $tmp = $metadata;
1127 unset( $tmp[$key] );
1128 $this->store->setRawSession( $id, [ 'metadata' => $tmp, 'data' => [] ] );
1129 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1130 $this->assertSame( [
1131 [ LogLevel::WARNING, 'Session "{session}": Bad metadata' ],
1132 ], $logger->getBuffer() );
1133 $logger->clearBuffer();
1134 }
1135
1136 // Basic usage with metadata
1137 $this->store->setRawSession( $id, [ 'metadata' => $metadata, 'data' => [] ] );
1138 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1139 'provider' => $provider,
1140 'id' => $id,
1141 'userInfo' => $userInfo
1142 ] );
1143 $this->assertFalse( $info->isIdSafe() );
1144 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1145 $this->assertTrue( $info->isIdSafe() );
1146 $this->assertSame( [], $logger->getBuffer() );
1147
1148 // Mismatched provider
1149 $this->store->setSessionMeta( $id, [ 'provider' => 'Bad' ] + $metadata );
1150 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1151 'provider' => $provider,
1152 'id' => $id,
1153 'userInfo' => $userInfo
1154 ] );
1155 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1156 $this->assertSame( [
1157 [ LogLevel::WARNING, 'Session "{session}": Wrong provider Bad !== Mock' ],
1158 ], $logger->getBuffer() );
1159 $logger->clearBuffer();
1160
1161 // Unknown provider
1162 $this->store->setSessionMeta( $id, [ 'provider' => 'Bad' ] + $metadata );
1163 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1164 'id' => $id,
1165 'userInfo' => $userInfo
1166 ] );
1167 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1168 $this->assertSame( [
1169 [ LogLevel::WARNING, 'Session "{session}": Unknown provider Bad' ],
1170 ], $logger->getBuffer() );
1171 $logger->clearBuffer();
1172
1173 // Fill in provider
1174 $this->store->setSessionMeta( $id, $metadata );
1175 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1176 'id' => $id,
1177 'userInfo' => $userInfo
1178 ] );
1179 $this->assertFalse( $info->isIdSafe() );
1180 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1181 $this->assertTrue( $info->isIdSafe() );
1182 $this->assertSame( [], $logger->getBuffer() );
1183
1184 // Bad user metadata
1185 $this->store->setSessionMeta( $id, [ 'userId' => -1, 'userToken' => null ] + $metadata );
1186 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1187 'provider' => $provider,
1188 'id' => $id,
1189 ] );
1190 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1191 $this->assertSame( [
1192 [ LogLevel::ERROR, 'Session "{session}": {exception}' ],
1193 ], $logger->getBuffer() );
1194 $logger->clearBuffer();
1195
1196 $this->store->setSessionMeta(
1197 $id, [ 'userId' => 0, 'userName' => '<X>', 'userToken' => null ] + $metadata
1198 );
1199 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1200 'provider' => $provider,
1201 'id' => $id,
1202 ] );
1203 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1204 $this->assertSame( [
1205 [ LogLevel::ERROR, 'Session "{session}": {exception}', ],
1206 ], $logger->getBuffer() );
1207 $logger->clearBuffer();
1208
1209 // Mismatched user by ID
1210 $this->store->setSessionMeta(
1211 $id, [ 'userId' => $userInfo->getId() + 1, 'userToken' => null ] + $metadata
1212 );
1213 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1214 'provider' => $provider,
1215 'id' => $id,
1216 'userInfo' => $userInfo
1217 ] );
1218 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1219 $this->assertSame( [
1220 [ LogLevel::WARNING, 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}' ],
1221 ], $logger->getBuffer() );
1222 $logger->clearBuffer();
1223
1224 // Mismatched user by name
1225 $this->store->setSessionMeta(
1226 $id, [ 'userId' => 0, 'userName' => 'X', 'userToken' => null ] + $metadata
1227 );
1228 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1229 'provider' => $provider,
1230 'id' => $id,
1231 'userInfo' => $userInfo
1232 ] );
1233 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1234 $this->assertSame( [
1235 [ LogLevel::WARNING, 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}' ],
1236 ], $logger->getBuffer() );
1237 $logger->clearBuffer();
1238
1239 // ID matches, name doesn't
1240 $this->store->setSessionMeta(
1241 $id, [ 'userId' => $userInfo->getId(), 'userName' => 'X', 'userToken' => null ] + $metadata
1242 );
1243 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1244 'provider' => $provider,
1245 'id' => $id,
1246 'userInfo' => $userInfo
1247 ] );
1248 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1249 $this->assertSame( [
1250 [
1251 LogLevel::WARNING,
1252 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}'
1253 ],
1254 ], $logger->getBuffer() );
1255 $logger->clearBuffer();
1256
1257 // Mismatched anon user
1258 $this->store->setSessionMeta(
1259 $id, [ 'userId' => 0, 'userName' => null, 'userToken' => null ] + $metadata
1260 );
1261 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1262 'provider' => $provider,
1263 'id' => $id,
1264 'userInfo' => $userInfo
1265 ] );
1266 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1267 $this->assertSame( [
1268 [
1269 LogLevel::WARNING,
1270 'Session "{session}": the session store entry is for an anonymous user, ' .
1271 'but the session metadata indicates a non-anonynmous user',
1272 ],
1273 ], $logger->getBuffer() );
1274 $logger->clearBuffer();
1275
1276 // Lookup user by ID
1277 $this->store->setSessionMeta( $id, [ 'userToken' => null ] + $metadata );
1278 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1279 'provider' => $provider,
1280 'id' => $id,
1281 ] );
1282 $this->assertFalse( $info->isIdSafe() );
1283 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1284 $this->assertSame( $userInfo->getId(), $info->getUserInfo()->getId() );
1285 $this->assertTrue( $info->isIdSafe() );
1286 $this->assertSame( [], $logger->getBuffer() );
1287
1288 // Lookup user by name
1289 $this->store->setSessionMeta(
1290 $id, [ 'userId' => 0, 'userName' => $username, 'userToken' => null ] + $metadata
1291 );
1292 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1293 'provider' => $provider,
1294 'id' => $id,
1295 ] );
1296 $this->assertFalse( $info->isIdSafe() );
1297 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1298 $this->assertSame( $userInfo->getId(), $info->getUserInfo()->getId() );
1299 $this->assertTrue( $info->isIdSafe() );
1300 $this->assertSame( [], $logger->getBuffer() );
1301
1302 // Lookup anonymous user
1303 $this->store->setSessionMeta(
1304 $id, [ 'userId' => 0, 'userName' => null, 'userToken' => null ] + $metadata
1305 );
1306 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1307 'provider' => $provider,
1308 'id' => $id,
1309 ] );
1310 $this->assertFalse( $info->isIdSafe() );
1311 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1312 $this->assertTrue( $info->getUserInfo()->isAnon() );
1313 $this->assertTrue( $info->isIdSafe() );
1314 $this->assertSame( [], $logger->getBuffer() );
1315
1316 // Unverified user with metadata
1317 $this->store->setSessionMeta( $id, $metadata );
1318 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1319 'provider' => $provider,
1320 'id' => $id,
1321 'userInfo' => $unverifiedUserInfo
1322 ] );
1323 $this->assertFalse( $info->isIdSafe() );
1324 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1325 $this->assertTrue( $info->getUserInfo()->isVerified() );
1326 $this->assertSame( $unverifiedUserInfo->getId(), $info->getUserInfo()->getId() );
1327 $this->assertSame( $unverifiedUserInfo->getName(), $info->getUserInfo()->getName() );
1328 $this->assertTrue( $info->isIdSafe() );
1329 $this->assertSame( [], $logger->getBuffer() );
1330
1331 // Unverified user with metadata
1332 $this->store->setSessionMeta( $id, $metadata );
1333 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1334 'provider' => $provider,
1335 'id' => $id,
1336 'userInfo' => $unverifiedUserInfo
1337 ] );
1338 $this->assertFalse( $info->isIdSafe() );
1339 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1340 $this->assertTrue( $info->getUserInfo()->isVerified() );
1341 $this->assertSame( $unverifiedUserInfo->getId(), $info->getUserInfo()->getId() );
1342 $this->assertSame( $unverifiedUserInfo->getName(), $info->getUserInfo()->getName() );
1343 $this->assertTrue( $info->isIdSafe() );
1344 $this->assertSame( [], $logger->getBuffer() );
1345
1346 // Wrong token
1347 $this->store->setSessionMeta( $id, [ 'userToken' => 'Bad' ] + $metadata );
1348 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1349 'provider' => $provider,
1350 'id' => $id,
1351 'userInfo' => $userInfo
1352 ] );
1353 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1354 $this->assertSame( [
1355 [ LogLevel::WARNING, 'Session "{session}": User token mismatch' ],
1356 ], $logger->getBuffer() );
1357 $logger->clearBuffer();
1358
1359 // Provider metadata
1360 $this->store->setSessionMeta( $id, [ 'provider' => 'Mock2' ] + $metadata );
1361 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1362 'provider' => $provider2,
1363 'id' => $id,
1364 'userInfo' => $userInfo,
1365 'metadata' => [ 'Info' ],
1366 ] );
1367 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1368 $this->assertSame( [ 'Info', 'changed' => true ], $info->getProviderMetadata() );
1369 $this->assertSame( [], $logger->getBuffer() );
1370
1371 $this->store->setSessionMeta( $id, [ 'providerMetadata' => [ 'Saved' ] ] + $metadata );
1372 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1373 'provider' => $provider,
1374 'id' => $id,
1375 'userInfo' => $userInfo,
1376 ] );
1377 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1378 $this->assertSame( [ 'Saved' ], $info->getProviderMetadata() );
1379 $this->assertSame( [], $logger->getBuffer() );
1380
1381 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1382 'provider' => $provider,
1383 'id' => $id,
1384 'userInfo' => $userInfo,
1385 'metadata' => [ 'Info' ],
1386 ] );
1387 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1388 $this->assertSame( [ 'Merged' ], $info->getProviderMetadata() );
1389 $this->assertSame( [], $logger->getBuffer() );
1390
1391 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1392 'provider' => $provider,
1393 'id' => $id,
1394 'userInfo' => $userInfo,
1395 'metadata' => [ 'Throw' ],
1396 ] );
1397 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1398 $this->assertSame( [
1399 [
1400 LogLevel::WARNING,
1401 'Session "{session}": Metadata merge failed: {exception}',
1402 ],
1403 ], $logger->getBuffer() );
1404 $logger->clearBuffer();
1405
1406 // Remember from session
1407 $this->store->setSessionMeta( $id, $metadata );
1408 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1409 'provider' => $provider,
1410 'id' => $id,
1411 ] );
1412 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1413 $this->assertFalse( $info->wasRemembered() );
1414 $this->assertSame( [], $logger->getBuffer() );
1415
1416 $this->store->setSessionMeta( $id, [ 'remember' => true ] + $metadata );
1417 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1418 'provider' => $provider,
1419 'id' => $id,
1420 ] );
1421 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1422 $this->assertTrue( $info->wasRemembered() );
1423 $this->assertSame( [], $logger->getBuffer() );
1424
1425 $this->store->setSessionMeta( $id, [ 'remember' => false ] + $metadata );
1426 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1427 'provider' => $provider,
1428 'id' => $id,
1429 'userInfo' => $userInfo
1430 ] );
1431 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1432 $this->assertTrue( $info->wasRemembered() );
1433 $this->assertSame( [], $logger->getBuffer() );
1434
1435 // forceHTTPS from session
1436 $this->store->setSessionMeta( $id, $metadata );
1437 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1438 'provider' => $provider,
1439 'id' => $id,
1440 'userInfo' => $userInfo
1441 ] );
1442 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1443 $this->assertFalse( $info->forceHTTPS() );
1444 $this->assertSame( [], $logger->getBuffer() );
1445
1446 $this->store->setSessionMeta( $id, [ 'forceHTTPS' => true ] + $metadata );
1447 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1448 'provider' => $provider,
1449 'id' => $id,
1450 'userInfo' => $userInfo
1451 ] );
1452 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1453 $this->assertTrue( $info->forceHTTPS() );
1454 $this->assertSame( [], $logger->getBuffer() );
1455
1456 $this->store->setSessionMeta( $id, [ 'forceHTTPS' => false ] + $metadata );
1457 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1458 'provider' => $provider,
1459 'id' => $id,
1460 'userInfo' => $userInfo,
1461 'forceHTTPS' => true
1462 ] );
1463 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1464 $this->assertTrue( $info->forceHTTPS() );
1465 $this->assertSame( [], $logger->getBuffer() );
1466
1467 // "Persist" flag from session
1468 $this->store->setSessionMeta( $id, $metadata );
1469 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1470 'provider' => $provider,
1471 'id' => $id,
1472 'userInfo' => $userInfo
1473 ] );
1474 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1475 $this->assertFalse( $info->wasPersisted() );
1476 $this->assertSame( [], $logger->getBuffer() );
1477
1478 $this->store->setSessionMeta( $id, [ 'persisted' => true ] + $metadata );
1479 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1480 'provider' => $provider,
1481 'id' => $id,
1482 'userInfo' => $userInfo
1483 ] );
1484 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1485 $this->assertTrue( $info->wasPersisted() );
1486 $this->assertSame( [], $logger->getBuffer() );
1487
1488 $this->store->setSessionMeta( $id, [ 'persisted' => false ] + $metadata );
1489 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1490 'provider' => $provider,
1491 'id' => $id,
1492 'userInfo' => $userInfo,
1493 'persisted' => true
1494 ] );
1495 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1496 $this->assertTrue( $info->wasPersisted() );
1497 $this->assertSame( [], $logger->getBuffer() );
1498
1499 // Provider refreshSessionInfo() returning false
1500 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1501 'provider' => $provider3,
1502 ] );
1503 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1504 $this->assertSame( [], $logger->getBuffer() );
1505
1506 // Hook
1507 $called = false;
1508 $data = [ 'foo' => 1 ];
1509 $this->store->setSession( $id, [ 'metadata' => $metadata, 'data' => $data ] );
1510 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1511 'provider' => $provider,
1512 'id' => $id,
1513 'userInfo' => $userInfo
1514 ] );
1515 $manager->setHookContainer( $this->createHookContainer( [
1516 'SessionCheckInfo' => function ( &$reason, $i, $r, $m, $d ) use (
1517 $info, $metadata, $data, $request, &$called
1518 ) {
1519 $this->assertSame( $info->getId(), $i->getId() );
1520 $this->assertSame( $info->getProvider(), $i->getProvider() );
1521 $this->assertSame( $info->getUserInfo(), $i->getUserInfo() );
1522 $this->assertSame( $request, $r );
1523 $this->assertEquals( $metadata, $m );
1524 $this->assertEquals( $data, $d );
1525 $called = true;
1526 return false;
1527 }
1528 ] ) );
1529 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1530 $this->assertTrue( $called );
1531 $this->assertSame( [
1532 [ LogLevel::WARNING, 'Session "{session}": Hook aborted' ],
1533 ], $logger->getBuffer() );
1534 $logger->clearBuffer();
1535 $manager->setHookContainer( $this->createHookContainer() );
1536
1537 // forceUse deletes bad backend data
1538 $this->store->setSessionMeta( $id, [ 'userToken' => 'Bad' ] + $metadata );
1539 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
1540 'provider' => $provider,
1541 'id' => $id,
1542 'userInfo' => $userInfo,
1543 'forceUse' => true,
1544 ] );
1545 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1546 $this->assertFalse( $this->store->getSession( $id ) );
1547 $this->assertSame( [
1548 [ LogLevel::WARNING, 'Session "{session}": User token mismatch' ],
1549 ], $logger->getBuffer() );
1550 $logger->clearBuffer();
1551 }
1552
1553 /**
1554 * @dataProvider provideLogPotentialSessionLeakage
1555 */
1556 public function testLogPotentialSessionLeakage(
1557 $ip, $mwuser, $sessionData, $expectedSessionData, $expectedLogLevel
1558 ) {
1559 MWTimestamp::setFakeTime( 1234567 );
1560 $this->overrideConfigValue( MainConfigNames::SuspiciousIpExpiry, 600 );
1561 $manager = new SessionManager();
1562 $logger = $this->createMock( LoggerInterface::class );
1563 $this->setLogger( 'session-ip', $logger );
1564 $request = new FauxRequest();
1565 $request->setIP( $ip );
1566 $request->setCookie( 'mwuser-sessionId', $mwuser );
1567
1568 $proxyLookup = $this->createMock( ProxyLookup::class );
1569 $proxyLookup->method( 'isConfiguredProxy' )->willReturnCallback( static function ( $ip ) {
1570 return $ip === '11.22.33.44';
1571 } );
1572 $this->setService( 'ProxyLookup', $proxyLookup );
1573
1574 $session = $this->createMock( Session::class );
1575 $session->method( 'isPersistent' )->willReturn( true );
1576 $session->method( 'getUser' )->willReturn( $this->getTestSysop()->getUser() );
1577 $session->method( 'getRequest' )->willReturn( $request );
1578 $session->method( 'getProvider' )->willReturn(
1579 $this->createMock( CookieSessionProvider::class ) );
1580 $session->method( 'get' )
1581 ->with( 'SessionManager-logPotentialSessionLeakage' )
1582 ->willReturn( $sessionData );
1583 $session->expects( $this->exactly( isset( $expectedSessionData ) ) )->method( 'set' )
1584 ->with( 'SessionManager-logPotentialSessionLeakage', $expectedSessionData );
1585
1586 $logger->expects( $this->exactly( isset( $expectedLogLevel ) ) )->method( 'log' )
1587 ->with( $expectedLogLevel );
1588
1589 $manager->logPotentialSessionLeakage( $session );
1590 }
1591
1592 public static function provideLogPotentialSessionLeakage() {
1593 $now = 1234567;
1594 $valid = $now - 100;
1595 $expired = $now - 1000;
1596 return [
1597 'no log for new IP' => [
1598 'ip' => '1.2.3.4',
1599 'mwuser' => null,
1600 'sessionData' => [],
1601 'expectedSessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => null, 'timestamp' => $now ],
1602 'expectedLogLevel' => null,
1603 ],
1604 'no log for same IP' => [
1605 'ip' => '1.2.3.4',
1606 'mwuser' => null,
1607 'sessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => null, 'timestamp' => $valid ],
1608 'expectedSessionData' => null,
1609 'expectedLogLevel' => null,
1610 ],
1611 'no log for expired IP' => [
1612 'ip' => '1.2.3.4',
1613 'mwuser' => null,
1614 'sessionData' => [ 'ip' => '10.20.30.40', 'mwuser' => null, 'timestamp' => $expired ],
1615 'expectedSessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => null, 'timestamp' => $now ],
1616 'expectedLogLevel' => null,
1617 ],
1618 'INFO log for changed IP' => [
1619 'ip' => '1.2.3.4',
1620 'mwuser' => null,
1621 'sessionData' => [ 'ip' => '10.20.30.40', 'mwuser' => null, 'timestamp' => $valid ],
1622 'expectedSessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => null, 'timestamp' => $now ],
1623 'expectedLogLevel' => LogLevel::INFO,
1624 ],
1625
1626 'no log for new mwuser' => [
1627 'ip' => '1.2.3.4',
1628 'mwuser' => 'new',
1629 'sessionData' => [],
1630 'expectedSessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => 'new', 'timestamp' => $now ],
1631 'expectedLogLevel' => null,
1632 ],
1633 'no log for same mwuser' => [
1634 'ip' => '1.2.3.4',
1635 'mwuser' => 'old',
1636 'sessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => 'old', 'timestamp' => $valid ],
1637 'expectedSessionData' => null,
1638 'expectedLogLevel' => null,
1639 ],
1640 'NOTICE log for changed mwuser' => [
1641 'ip' => '1.2.3.4',
1642 'mwuser' => 'new',
1643 'sessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => 'old', 'timestamp' => $valid ],
1644 'expectedSessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => 'new', 'timestamp' => $now ],
1645 'expectedLogLevel' => LogLevel::NOTICE,
1646 ],
1647 'no expiration for mwuser' => [
1648 'ip' => '1.2.3.4',
1649 'mwuser' => 'new',
1650 'sessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => 'old', 'timestamp' => $expired ],
1651 'expectedSessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => 'new', 'timestamp' => $now ],
1652 'expectedLogLevel' => LogLevel::NOTICE,
1653 ],
1654 'WARNING log for changed IP + mwuser' => [
1655 'ip' => '1.2.3.4',
1656 'mwuser' => 'new',
1657 'sessionData' => [ 'ip' => '10.20.30.40', 'mwuser' => 'old', 'timestamp' => $valid ],
1658 'expectedSessionData' => [ 'ip' => '1.2.3.4', 'mwuser' => 'new', 'timestamp' => $now ],
1659 'expectedLogLevel' => LogLevel::WARNING,
1660 ],
1661
1662 'special IPs are ignored (1)' => [
1663 'ip' => '127.0.0.1',
1664 'mwuser' => 'new',
1665 'sessionData' => [ 'ip' => '10.20.30.40', 'mwuser' => 'old', 'timestamp' => $valid ],
1666 'expectedSessionData' => null,
1667 'expectedLogLevel' => null,
1668 ],
1669 'special IPs are ignored (2)' => [
1670 'ip' => '11.22.33.44',
1671 'mwuser' => 'new',
1672 'sessionData' => [ 'ip' => '10.20.30.40', 'mwuser' => 'old', 'timestamp' => $valid ],
1673 'expectedSessionData' => null,
1674 'expectedLogLevel' => null,
1675 ],
1676 ];
1677 }
1678 }