3 namespace MediaWiki\Session
;
13 * @covers MediaWiki\Session\SessionManager
15 class SessionManagerTest
extends MediaWikiTestCase
{
17 protected $config, $logger, $store;
19 protected function getManager() {
20 \ObjectCache
::$instances['testSessionStore'] = new TestBagOStuff();
21 $this->config
= new \
HashConfig( [
22 'LanguageCode' => 'en',
23 'SessionCacheType' => 'testSessionStore',
24 'ObjectCacheSessionExpiry' => 100,
25 'SessionProviders' => [
26 [ 'class' => 'DummySessionProvider' ],
29 $this->logger
= new \
TestLogger( false, function ( $m ) {
30 return substr( $m, 0, 15 ) === 'SessionBackend ' ?
null : $m;
32 $this->store
= new TestBagOStuff();
34 return new SessionManager( [
35 'config' => $this->config
,
36 'logger' => $this->logger
,
37 'store' => $this->store
,
41 protected function objectCacheDef( $object ) {
42 return [ 'factory' => function () use ( $object ) {
47 public function testSingleton() {
48 $reset = TestUtils
::setSessionManagerSingleton( null );
50 $singleton = SessionManager
::singleton();
51 $this->assertInstanceOf( 'MediaWiki\\Session\\SessionManager', $singleton );
52 $this->assertSame( $singleton, SessionManager
::singleton() );
55 public function testGetGlobalSession() {
56 $context = \RequestContext
::getMain();
58 if ( !PHPSessionHandler
::isInstalled() ) {
59 PHPSessionHandler
::install( SessionManager
::singleton() );
61 $rProp = new \
ReflectionProperty( 'MediaWiki\\Session\\PHPSessionHandler', 'instance' );
62 $rProp->setAccessible( true );
63 $handler = \TestingAccessWrapper
::newFromObject( $rProp->getValue() );
64 $oldEnable = $handler->enable
;
65 $reset[] = new \
ScopedCallback( function () use ( $handler, $oldEnable ) {
66 if ( $handler->enable
) {
67 session_write_close();
69 $handler->enable
= $oldEnable;
71 $reset[] = TestUtils
::setSessionManagerSingleton( $this->getManager() );
73 $handler->enable
= true;
74 $request = new \
FauxRequest();
75 $context->setRequest( $request );
76 $id = $request->getSession()->getId();
79 $session = SessionManager
::getGlobalSession();
80 $this->assertSame( $id, $session->getId() );
82 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
83 $session = SessionManager
::getGlobalSession();
84 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $session->getId() );
85 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $request->getSession()->getId() );
87 session_write_close();
88 $handler->enable
= false;
89 $request = new \
FauxRequest();
90 $context->setRequest( $request );
91 $id = $request->getSession()->getId();
94 $session = SessionManager
::getGlobalSession();
95 $this->assertSame( $id, $session->getId() );
97 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
98 $session = SessionManager
::getGlobalSession();
99 $this->assertSame( $id, $session->getId() );
100 $this->assertSame( $id, $request->getSession()->getId() );
103 public function testConstructor() {
104 $manager = \TestingAccessWrapper
::newFromObject( $this->getManager() );
105 $this->assertSame( $this->config
, $manager->config
);
106 $this->assertSame( $this->logger
, $manager->logger
);
107 $this->assertSame( $this->store
, $manager->store
);
109 $manager = \TestingAccessWrapper
::newFromObject( new SessionManager() );
110 $this->assertSame( \RequestContext
::getMain()->getConfig(), $manager->config
);
112 $manager = \TestingAccessWrapper
::newFromObject( new SessionManager( [
113 'config' => $this->config
,
115 $this->assertSame( \ObjectCache
::$instances['testSessionStore'], $manager->store
);
118 'config' => '$options[\'config\'] must be an instance of Config',
119 'logger' => '$options[\'logger\'] must be an instance of LoggerInterface',
120 'store' => '$options[\'store\'] must be an instance of BagOStuff',
121 ] as $key => $error ) {
123 new SessionManager( [ $key => new \stdClass
] );
124 $this->fail( 'Expected exception not thrown' );
125 } catch ( \InvalidArgumentException
$ex ) {
126 $this->assertSame( $error, $ex->getMessage() );
131 public function testGetSessionForRequest() {
132 $manager = $this->getManager();
133 $request = new \
FauxRequest();
134 $request->unpersist1
= false;
135 $request->unpersist2
= false;
139 $idEmpty = 'empty-session-------------------';
141 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
143 [ 'provideSessionInfo', 'newSessionInfo', '__toString', 'describe', 'unpersistSession' ]
146 $provider1 = $providerBuilder->getMock();
147 $provider1->expects( $this->any() )->method( 'provideSessionInfo' )
148 ->with( $this->identicalTo( $request ) )
149 ->will( $this->returnCallback( function ( $request ) {
150 return $request->info1
;
152 $provider1->expects( $this->any() )->method( 'newSessionInfo' )
153 ->will( $this->returnCallback( function () use ( $idEmpty, $provider1 ) {
154 return new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
155 'provider' => $provider1,
161 $provider1->expects( $this->any() )->method( '__toString' )
162 ->will( $this->returnValue( 'Provider1' ) );
163 $provider1->expects( $this->any() )->method( 'describe' )
164 ->will( $this->returnValue( '#1 sessions' ) );
165 $provider1->expects( $this->any() )->method( 'unpersistSession' )
166 ->will( $this->returnCallback( function ( $request ) {
167 $request->unpersist1
= true;
170 $provider2 = $providerBuilder->getMock();
171 $provider2->expects( $this->any() )->method( 'provideSessionInfo' )
172 ->with( $this->identicalTo( $request ) )
173 ->will( $this->returnCallback( function ( $request ) {
174 return $request->info2
;
176 $provider2->expects( $this->any() )->method( '__toString' )
177 ->will( $this->returnValue( 'Provider2' ) );
178 $provider2->expects( $this->any() )->method( 'describe' )
179 ->will( $this->returnValue( '#2 sessions' ) );
180 $provider2->expects( $this->any() )->method( 'unpersistSession' )
181 ->will( $this->returnCallback( function ( $request ) {
182 $request->unpersist2
= true;
185 $this->config
->set( 'SessionProviders', [
186 $this->objectCacheDef( $provider1 ),
187 $this->objectCacheDef( $provider2 ),
190 // No provider returns info
191 $request->info1
= null;
192 $request->info2
= null;
193 $session = $manager->getSessionForRequest( $request );
194 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
195 $this->assertSame( $idEmpty, $session->getId() );
196 $this->assertFalse( $request->unpersist1
);
197 $this->assertFalse( $request->unpersist2
);
199 // Both providers return info, picks best one
200 $request->info1
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, [
201 'provider' => $provider1,
202 'id' => ( $id1 = $manager->generateSessionId() ),
206 $request->info2
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
2, [
207 'provider' => $provider2,
208 'id' => ( $id2 = $manager->generateSessionId() ),
212 $session = $manager->getSessionForRequest( $request );
213 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
214 $this->assertSame( $id2, $session->getId() );
215 $this->assertFalse( $request->unpersist1
);
216 $this->assertFalse( $request->unpersist2
);
218 $request->info1
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
2, [
219 'provider' => $provider1,
220 'id' => ( $id1 = $manager->generateSessionId() ),
224 $request->info2
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, [
225 'provider' => $provider2,
226 'id' => ( $id2 = $manager->generateSessionId() ),
230 $session = $manager->getSessionForRequest( $request );
231 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
232 $this->assertSame( $id1, $session->getId() );
233 $this->assertFalse( $request->unpersist1
);
234 $this->assertFalse( $request->unpersist2
);
237 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
238 'provider' => $provider1,
239 'id' => ( $id1 = $manager->generateSessionId() ),
241 'userInfo' => UserInfo
::newAnonymous(),
244 $request->info2
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
245 'provider' => $provider2,
246 'id' => ( $id2 = $manager->generateSessionId() ),
248 'userInfo' => UserInfo
::newAnonymous(),
252 $manager->getSessionForRequest( $request );
253 $this->fail( 'Expcected exception not thrown' );
254 } catch ( \OverFlowException
$ex ) {
255 $this->assertStringStartsWith(
256 'Multiple sessions for this request tied for top priority: ',
259 $this->assertCount( 2, $ex->sessionInfos
);
260 $this->assertContains( $request->info1
, $ex->sessionInfos
);
261 $this->assertContains( $request->info2
, $ex->sessionInfos
);
263 $this->assertFalse( $request->unpersist1
);
264 $this->assertFalse( $request->unpersist2
);
267 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
268 'provider' => $provider2,
269 'id' => ( $id1 = $manager->generateSessionId() ),
273 $request->info2
= null;
275 $manager->getSessionForRequest( $request );
276 $this->fail( 'Expcected exception not thrown' );
277 } catch ( \UnexpectedValueException
$ex ) {
279 'Provider1 returned session info for a different provider: ' . $request->info1
,
283 $this->assertFalse( $request->unpersist1
);
284 $this->assertFalse( $request->unpersist2
);
286 // Unusable session info
287 $this->logger
->setCollect( true );
288 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
289 'provider' => $provider1,
290 'id' => ( $id1 = $manager->generateSessionId() ),
292 'userInfo' => UserInfo
::newFromName( 'UTSysop', false ),
295 $request->info2
= new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
296 'provider' => $provider2,
297 'id' => ( $id2 = $manager->generateSessionId() ),
301 $session = $manager->getSessionForRequest( $request );
302 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
303 $this->assertSame( $id2, $session->getId() );
304 $this->logger
->setCollect( false );
305 $this->assertTrue( $request->unpersist1
);
306 $this->assertFalse( $request->unpersist2
);
307 $request->unpersist1
= false;
309 $this->logger
->setCollect( true );
310 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
311 'provider' => $provider1,
312 'id' => ( $id1 = $manager->generateSessionId() ),
316 $request->info2
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
317 'provider' => $provider2,
318 'id' => ( $id2 = $manager->generateSessionId() ),
320 'userInfo' => UserInfo
::newFromName( 'UTSysop', false ),
323 $session = $manager->getSessionForRequest( $request );
324 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
325 $this->assertSame( $id1, $session->getId() );
326 $this->logger
->setCollect( false );
327 $this->assertFalse( $request->unpersist1
);
328 $this->assertTrue( $request->unpersist2
);
329 $request->unpersist2
= false;
331 // Unpersisted session ID
332 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
333 'provider' => $provider1,
334 'id' => ( $id1 = $manager->generateSessionId() ),
335 'persisted' => false,
336 'userInfo' => UserInfo
::newFromName( 'UTSysop', true ),
339 $request->info2
= null;
340 $session = $manager->getSessionForRequest( $request );
341 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
342 $this->assertSame( $id1, $session->getId() );
343 $this->assertTrue( $request->unpersist1
); // The saving of the session does it
344 $this->assertFalse( $request->unpersist2
);
346 $this->assertTrue( $session->isPersistent(), 'sanity check' );
349 public function testGetSessionById() {
350 $manager = $this->getManager();
352 $manager->getSessionById( 'bad' );
353 $this->fail( 'Expected exception not thrown' );
354 } catch ( \InvalidArgumentException
$ex ) {
355 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
358 // Unknown session ID
359 $id = $manager->generateSessionId();
360 $session = $manager->getSessionById( $id, true );
361 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
362 $this->assertSame( $id, $session->getId() );
364 $id = $manager->generateSessionId();
365 $this->assertNull( $manager->getSessionById( $id, false ) );
367 // Known but unloadable session ID
368 $this->logger
->setCollect( true );
369 $id = $manager->generateSessionId();
370 $this->store
->setSession( $id, [ 'metadata' => [
371 'userId' => User
::idFromName( 'UTSysop' ),
372 'userToken' => 'bad',
375 $this->assertNull( $manager->getSessionById( $id, true ) );
376 $this->assertNull( $manager->getSessionById( $id, false ) );
377 $this->logger
->setCollect( false );
380 $this->store
->setSession( $id, [] );
381 $session = $manager->getSessionById( $id, false );
382 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
383 $this->assertSame( $id, $session->getId() );
386 public function testGetEmptySession() {
387 $manager = $this->getManager();
388 $pmanager = \TestingAccessWrapper
::newFromObject( $manager );
389 $request = new \
FauxRequest();
391 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
392 ->setMethods( [ 'provideSessionInfo', 'newSessionInfo', '__toString' ] );
398 $provider1 = $providerBuilder->getMock();
399 $provider1->expects( $this->any() )->method( 'provideSessionInfo' )
400 ->will( $this->returnValue( null ) );
401 $provider1->expects( $this->any() )->method( 'newSessionInfo' )
402 ->with( $this->callback( function ( $id ) use ( &$expectId ) {
403 return $id === $expectId;
405 ->will( $this->returnCallback( function () use ( &$info1 ) {
408 $provider1->expects( $this->any() )->method( '__toString' )
409 ->will( $this->returnValue( 'MockProvider1' ) );
411 $provider2 = $providerBuilder->getMock();
412 $provider2->expects( $this->any() )->method( 'provideSessionInfo' )
413 ->will( $this->returnValue( null ) );
414 $provider2->expects( $this->any() )->method( 'newSessionInfo' )
415 ->with( $this->callback( function ( $id ) use ( &$expectId ) {
416 return $id === $expectId;
418 ->will( $this->returnCallback( function () use ( &$info2 ) {
421 $provider1->expects( $this->any() )->method( '__toString' )
422 ->will( $this->returnValue( 'MockProvider2' ) );
424 $this->config
->set( 'SessionProviders', [
425 $this->objectCacheDef( $provider1 ),
426 $this->objectCacheDef( $provider2 ),
434 $manager->getEmptySession();
435 $this->fail( 'Expected exception not thrown' );
436 } catch ( \UnexpectedValueException
$ex ) {
438 'No provider could provide an empty session!',
445 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
446 'provider' => $provider1,
447 'id' => 'empty---------------------------',
452 $session = $manager->getEmptySession();
453 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
454 $this->assertSame( 'empty---------------------------', $session->getId() );
457 $expectId = 'expected------------------------';
458 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
459 'provider' => $provider1,
465 $session = $pmanager->getEmptySessionInternal( null, $expectId );
466 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
467 $this->assertSame( $expectId, $session->getId() );
470 $expectId = 'expected-----------------------2';
471 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
472 'provider' => $provider1,
473 'id' => "un$expectId",
479 $pmanager->getEmptySessionInternal( null, $expectId );
480 $this->fail( 'Expected exception not thrown' );
481 } catch ( \UnexpectedValueException
$ex ) {
483 'MockProvider1 returned empty session info with a wrong id: ' .
484 "un$expectId != $expectId",
490 $expectId = 'expected-----------------------2';
491 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
492 'provider' => $provider1,
498 $pmanager->getEmptySessionInternal( null, $expectId );
499 $this->fail( 'Expected exception not thrown' );
500 } catch ( \UnexpectedValueException
$ex ) {
502 'MockProvider1 returned empty session info with id flagged unsafe',
509 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
510 'provider' => $provider2,
511 'id' => 'empty---------------------------',
517 $manager->getEmptySession();
518 $this->fail( 'Expected exception not thrown' );
519 } catch ( \UnexpectedValueException
$ex ) {
521 'MockProvider1 returned an empty session info for a different provider: ' . $info1,
526 // Highest priority wins
528 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, [
529 'provider' => $provider1,
530 'id' => 'empty1--------------------------',
534 $info2 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
535 'provider' => $provider2,
536 'id' => 'empty2--------------------------',
540 $session = $manager->getEmptySession();
541 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
542 $this->assertSame( 'empty1--------------------------', $session->getId() );
545 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, [
546 'provider' => $provider1,
547 'id' => 'empty1--------------------------',
551 $info2 = new SessionInfo( SessionInfo
::MIN_PRIORITY +
2, [
552 'provider' => $provider2,
553 'id' => 'empty2--------------------------',
557 $session = $manager->getEmptySession();
558 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
559 $this->assertSame( 'empty2--------------------------', $session->getId() );
561 // Tied priorities throw an exception
563 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
564 'provider' => $provider1,
565 'id' => 'empty1--------------------------',
567 'userInfo' => UserInfo
::newAnonymous(),
570 $info2 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
571 'provider' => $provider2,
572 'id' => 'empty2--------------------------',
574 'userInfo' => UserInfo
::newAnonymous(),
578 $manager->getEmptySession();
579 $this->fail( 'Expected exception not thrown' );
580 } catch ( \UnexpectedValueException
$ex ) {
581 $this->assertStringStartsWith(
582 'Multiple empty sessions tied for top priority: ',
589 $pmanager->getEmptySessionInternal( null, 'bad' );
590 $this->fail( 'Expected exception not thrown' );
591 } catch ( \InvalidArgumentException
$ex ) {
592 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
595 // Session already exists
596 $expectId = 'expected-----------------------3';
597 $this->store
->setSessionMeta( $expectId, [
598 'provider' => 'MockProvider2',
604 $pmanager->getEmptySessionInternal( null, $expectId );
605 $this->fail( 'Expected exception not thrown' );
606 } catch ( \InvalidArgumentException
$ex ) {
607 $this->assertSame( 'Session ID already exists', $ex->getMessage() );
611 public function testGetVaryHeaders() {
612 $manager = $this->getManager();
614 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
615 ->setMethods( [ 'getVaryHeaders', '__toString' ] );
617 $provider1 = $providerBuilder->getMock();
618 $provider1->expects( $this->once() )->method( 'getVaryHeaders' )
619 ->will( $this->returnValue( [
621 'Bar' => [ 'X', 'Bar1' ],
624 $provider1->expects( $this->any() )->method( '__toString' )
625 ->will( $this->returnValue( 'MockProvider1' ) );
627 $provider2 = $providerBuilder->getMock();
628 $provider2->expects( $this->once() )->method( 'getVaryHeaders' )
629 ->will( $this->returnValue( [
631 'Bar' => [ 'X', 'Bar2' ],
632 'Quux' => [ 'Quux' ],
634 $provider2->expects( $this->any() )->method( '__toString' )
635 ->will( $this->returnValue( 'MockProvider2' ) );
637 $this->config
->set( 'SessionProviders', [
638 $this->objectCacheDef( $provider1 ),
639 $this->objectCacheDef( $provider2 ),
644 'Bar' => [ 'X', 'Bar1', 3 => 'Bar2' ],
645 'Quux' => [ 'Quux' ],
649 $this->assertEquals( $expect, $manager->getVaryHeaders() );
651 // Again, to ensure it's cached
652 $this->assertEquals( $expect, $manager->getVaryHeaders() );
655 public function testGetVaryCookies() {
656 $manager = $this->getManager();
658 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
659 ->setMethods( [ 'getVaryCookies', '__toString' ] );
661 $provider1 = $providerBuilder->getMock();
662 $provider1->expects( $this->once() )->method( 'getVaryCookies' )
663 ->will( $this->returnValue( [ 'Foo', 'Bar' ] ) );
664 $provider1->expects( $this->any() )->method( '__toString' )
665 ->will( $this->returnValue( 'MockProvider1' ) );
667 $provider2 = $providerBuilder->getMock();
668 $provider2->expects( $this->once() )->method( 'getVaryCookies' )
669 ->will( $this->returnValue( [ 'Foo', 'Baz' ] ) );
670 $provider2->expects( $this->any() )->method( '__toString' )
671 ->will( $this->returnValue( 'MockProvider2' ) );
673 $this->config
->set( 'SessionProviders', [
674 $this->objectCacheDef( $provider1 ),
675 $this->objectCacheDef( $provider2 ),
678 $expect = [ 'Foo', 'Bar', 'Baz' ];
680 $this->assertEquals( $expect, $manager->getVaryCookies() );
682 // Again, to ensure it's cached
683 $this->assertEquals( $expect, $manager->getVaryCookies() );
686 public function testGetProviders() {
687 $realManager = $this->getManager();
688 $manager = \TestingAccessWrapper
::newFromObject( $realManager );
690 $this->config
->set( 'SessionProviders', [
691 [ 'class' => 'DummySessionProvider' ],
693 $providers = $manager->getProviders();
694 $this->assertArrayHasKey( 'DummySessionProvider', $providers );
695 $provider = \TestingAccessWrapper
::newFromObject( $providers['DummySessionProvider'] );
696 $this->assertSame( $manager->logger
, $provider->logger
);
697 $this->assertSame( $manager->config
, $provider->config
);
698 $this->assertSame( $realManager, $provider->getManager() );
700 $this->config
->set( 'SessionProviders', [
701 [ 'class' => 'DummySessionProvider' ],
702 [ 'class' => 'DummySessionProvider' ],
704 $manager->sessionProviders
= null;
706 $manager->getProviders();
707 $this->fail( 'Expected exception not thrown' );
708 } catch ( \UnexpectedValueException
$ex ) {
710 'Duplicate provider name "DummySessionProvider"',
716 public function testShutdown() {
717 $manager = \TestingAccessWrapper
::newFromObject( $this->getManager() );
718 $manager->setLogger( new \Psr\Log\
NullLogger() );
720 $mock = $this->getMock( 'stdClass', [ 'save' ] );
721 $mock->expects( $this->once() )->method( 'save' );
723 $manager->allSessionBackends
= [ $mock ];
724 $manager->shutdown();
727 public function testGetSessionFromInfo() {
728 $manager = \TestingAccessWrapper
::newFromObject( $this->getManager() );
729 $request = new \
FauxRequest();
731 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
733 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
734 'provider' => $manager->getProvider( 'DummySessionProvider' ),
737 'userInfo' => UserInfo
::newFromName( 'UTSysop', true ),
740 \TestingAccessWrapper
::newFromObject( $info )->idIsSafe
= true;
741 $session1 = \TestingAccessWrapper
::newFromObject(
742 $manager->getSessionFromInfo( $info, $request )
744 $session2 = \TestingAccessWrapper
::newFromObject(
745 $manager->getSessionFromInfo( $info, $request )
748 $this->assertSame( $session1->backend
, $session2->backend
);
749 $this->assertNotEquals( $session1->index
, $session2->index
);
750 $this->assertSame( $session1->getSessionId(), $session2->getSessionId() );
751 $this->assertSame( $id, $session1->getId() );
753 \TestingAccessWrapper
::newFromObject( $info )->idIsSafe
= false;
754 $session3 = $manager->getSessionFromInfo( $info, $request );
755 $this->assertNotSame( $id, $session3->getId() );
758 public function testBackendRegistration() {
759 $manager = $this->getManager();
761 $session = $manager->getSessionForRequest( new \FauxRequest
);
762 $backend = \TestingAccessWrapper
::newFromObject( $session )->backend
;
763 $sessionId = $session->getSessionId();
764 $id = (string)$sessionId;
766 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
768 $manager->changeBackendId( $backend );
769 $this->assertSame( $sessionId, $session->getSessionId() );
770 $this->assertNotEquals( $id, (string)$sessionId );
771 $id = (string)$sessionId;
773 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
775 // Destruction of the session here causes the backend to be deregistered
779 $manager->changeBackendId( $backend );
780 $this->fail( 'Expected exception not thrown' );
781 } catch ( \InvalidArgumentException
$ex ) {
783 'Backend was not registered with this SessionManager', $ex->getMessage()
788 $manager->deregisterSessionBackend( $backend );
789 $this->fail( 'Expected exception not thrown' );
790 } catch ( \InvalidArgumentException
$ex ) {
792 'Backend was not registered with this SessionManager', $ex->getMessage()
796 $session = $manager->getSessionById( $id, true );
797 $this->assertSame( $sessionId, $session->getSessionId() );
800 public function testGenerateSessionId() {
801 $manager = $this->getManager();
803 $id = $manager->generateSessionId();
804 $this->assertTrue( SessionManager
::validateSessionId( $id ), "Generated ID: $id" );
807 public function testAutoCreateUser() {
808 global $wgGroupPermissions;
810 \ObjectCache
::$instances[__METHOD__
] = new TestBagOStuff();
811 $this->setMwGlobals( [ 'wgMainCacheType' => __METHOD__
] );
812 $this->setMWGlobals( [
813 'wgAuth' => new AuthPlugin
,
816 $this->stashMwGlobals( [ 'wgGroupPermissions' ] );
817 $wgGroupPermissions['*']['createaccount'] = true;
818 $wgGroupPermissions['*']['autocreateaccount'] = false;
820 // Replace the global singleton with one configured for testing
821 $manager = $this->getManager();
822 $reset = TestUtils
::setSessionManagerSingleton( $manager );
824 $logger = new \
TestLogger( true, function ( $m ) {
825 if ( substr( $m, 0, 15 ) === 'SessionBackend ' ) {
829 $m = str_replace( 'MediaWiki\Session\SessionManager::autoCreateUser: ', '', $m );
832 $manager->setLogger( $logger );
834 $session = SessionManager
::getGlobalSession();
836 // Can't create an already-existing user
837 $user = User
::newFromName( 'UTSysop' );
838 $id = $user->getId();
839 $this->assertFalse( $manager->autoCreateUser( $user ) );
840 $this->assertSame( $id, $user->getId() );
841 $this->assertSame( 'UTSysop', $user->getName() );
842 $this->assertSame( [], $logger->getBuffer() );
843 $logger->clearBuffer();
845 // Sanity check that creation works at all
846 $user = User
::newFromName( 'UTSessionAutoCreate1' );
847 $this->assertSame( 0, $user->getId(), 'sanity check' );
848 $this->assertTrue( $manager->autoCreateUser( $user ) );
849 $this->assertNotEquals( 0, $user->getId() );
850 $this->assertSame( 'UTSessionAutoCreate1', $user->getName() );
852 $user->getId(), User
::idFromName( 'UTSessionAutoCreate1', User
::READ_LATEST
)
855 [ LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ],
856 ], $logger->getBuffer() );
857 $logger->clearBuffer();
859 // Check lack of permissions
860 $wgGroupPermissions['*']['createaccount'] = false;
861 $wgGroupPermissions['*']['autocreateaccount'] = false;
862 $user = User
::newFromName( 'UTDoesNotExist' );
863 $this->assertFalse( $manager->autoCreateUser( $user ) );
864 $this->assertSame( 0, $user->getId() );
865 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
866 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
871 'user is blocked from this wiki, blacklisting',
873 ], $logger->getBuffer() );
874 $logger->clearBuffer();
876 // Check other permission
877 $wgGroupPermissions['*']['createaccount'] = false;
878 $wgGroupPermissions['*']['autocreateaccount'] = true;
879 $user = User
::newFromName( 'UTSessionAutoCreate2' );
880 $this->assertSame( 0, $user->getId(), 'sanity check' );
881 $this->assertTrue( $manager->autoCreateUser( $user ) );
882 $this->assertNotEquals( 0, $user->getId() );
883 $this->assertSame( 'UTSessionAutoCreate2', $user->getName() );
885 $user->getId(), User
::idFromName( 'UTSessionAutoCreate2', User
::READ_LATEST
)
888 [ LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ],
889 ], $logger->getBuffer() );
890 $logger->clearBuffer();
892 // Test account-creation block
894 $block = new \
Block( [
895 'address' => $anon->getName(),
897 'reason' => __METHOD__
,
898 'expiry' => time() +
100500,
899 'createAccount' => true,
902 $this->assertInstanceOf( 'Block', $anon->isBlockedFromCreateAccount(), 'sanity check' );
903 $reset2 = new \
ScopedCallback( [ $block, 'delete' ] );
904 $user = User
::newFromName( 'UTDoesNotExist' );
905 $this->assertFalse( $manager->autoCreateUser( $user ) );
906 $this->assertSame( 0, $user->getId() );
907 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
908 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
909 \ScopedCallback
::consume( $reset2 );
912 [ LogLevel
::DEBUG
, 'user is blocked from this wiki, blacklisting' ],
913 ], $logger->getBuffer() );
914 $logger->clearBuffer();
916 // Sanity check that creation still works
917 $user = User
::newFromName( 'UTSessionAutoCreate3' );
918 $this->assertSame( 0, $user->getId(), 'sanity check' );
919 $this->assertTrue( $manager->autoCreateUser( $user ) );
920 $this->assertNotEquals( 0, $user->getId() );
921 $this->assertSame( 'UTSessionAutoCreate3', $user->getName() );
923 $user->getId(), User
::idFromName( 'UTSessionAutoCreate3', User
::READ_LATEST
)
926 [ LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ],
927 ], $logger->getBuffer() );
928 $logger->clearBuffer();
930 // Test prevention by AuthPlugin
932 $oldWgAuth = $wgAuth;
933 $mockWgAuth = $this->getMock( 'AuthPlugin', [ 'autoCreate' ] );
934 $mockWgAuth->expects( $this->once() )->method( 'autoCreate' )
935 ->will( $this->returnValue( false ) );
936 $this->setMwGlobals( [
937 'wgAuth' => $mockWgAuth,
939 $user = User
::newFromName( 'UTDoesNotExist' );
940 $this->assertFalse( $manager->autoCreateUser( $user ) );
941 $this->assertSame( 0, $user->getId() );
942 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
943 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
944 $this->setMwGlobals( [
945 'wgAuth' => $oldWgAuth,
949 [ LogLevel
::DEBUG
, 'denied by AuthPlugin' ],
950 ], $logger->getBuffer() );
951 $logger->clearBuffer();
953 // Test prevention by wfReadOnly()
954 $this->setMwGlobals( [
955 'wgReadOnly' => 'Because',
957 $user = User
::newFromName( 'UTDoesNotExist' );
958 $this->assertFalse( $manager->autoCreateUser( $user ) );
959 $this->assertSame( 0, $user->getId() );
960 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
961 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
962 $this->setMwGlobals( [
963 'wgReadOnly' => false,
967 [ LogLevel
::DEBUG
, 'denied by wfReadOnly()' ],
968 ], $logger->getBuffer() );
969 $logger->clearBuffer();
971 // Test prevention by a previous session
972 $session->set( 'MWSession::AutoCreateBlacklist', 'test' );
973 $user = User
::newFromName( 'UTDoesNotExist' );
974 $this->assertFalse( $manager->autoCreateUser( $user ) );
975 $this->assertSame( 0, $user->getId() );
976 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
977 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
980 [ LogLevel
::DEBUG
, 'blacklisted in session (test)' ],
981 ], $logger->getBuffer() );
982 $logger->clearBuffer();
984 // Test uncreatable name
985 $user = User
::newFromName( 'UTDoesNotExist@' );
986 $this->assertFalse( $manager->autoCreateUser( $user ) );
987 $this->assertSame( 0, $user->getId() );
988 $this->assertNotSame( 'UTDoesNotExist@', $user->getName() );
989 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
992 [ LogLevel
::DEBUG
, 'Invalid username, blacklisting' ],
993 ], $logger->getBuffer() );
994 $logger->clearBuffer();
996 // Test AbortAutoAccount hook
997 $mock = $this->getMock( __CLASS__
, [ 'onAbortAutoAccount' ] );
998 $mock->expects( $this->once() )->method( 'onAbortAutoAccount' )
999 ->will( $this->returnCallback( function ( User
$user, &$msg ) {
1003 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'AbortAutoAccount' => [ $mock ] ] );
1004 $user = User
::newFromName( 'UTDoesNotExist' );
1005 $this->assertFalse( $manager->autoCreateUser( $user ) );
1006 $this->assertSame( 0, $user->getId() );
1007 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
1008 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
1009 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'AbortAutoAccount' => [] ] );
1011 $this->assertSame( [
1012 [ LogLevel
::DEBUG
, 'denied by hook: No way!' ],
1013 ], $logger->getBuffer() );
1014 $logger->clearBuffer();
1016 // Test AbortAutoAccount hook screwing up the name
1017 $mock = $this->getMock( 'stdClass', [ 'onAbortAutoAccount' ] );
1018 $mock->expects( $this->once() )->method( 'onAbortAutoAccount' )
1019 ->will( $this->returnCallback( function ( User
$user ) {
1020 $user->setName( 'UTDoesNotExistEither' );
1022 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'AbortAutoAccount' => [ $mock ] ] );
1024 $user = User
::newFromName( 'UTDoesNotExist' );
1025 $manager->autoCreateUser( $user );
1026 $this->fail( 'Expected exception not thrown' );
1027 } catch ( \UnexpectedValueException
$ex ) {
1029 'AbortAutoAccount hook tried to change the user name',
1033 $this->assertSame( 0, $user->getId() );
1034 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
1035 $this->assertNotSame( 'UTDoesNotExistEither', $user->getName() );
1036 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
1037 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExistEither', User
::READ_LATEST
) );
1038 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'AbortAutoAccount' => [] ] );
1040 $this->assertSame( [], $logger->getBuffer() );
1041 $logger->clearBuffer();
1043 // Test for "exception backoff"
1044 $user = User
::newFromName( 'UTDoesNotExist' );
1045 $cache = \ObjectCache
::getLocalClusterInstance();
1046 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $user->getName() ) );
1047 $cache->set( $backoffKey, 1, 60 * 10 );
1048 $this->assertFalse( $manager->autoCreateUser( $user ) );
1049 $this->assertSame( 0, $user->getId() );
1050 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
1051 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
1052 $cache->delete( $backoffKey );
1054 $this->assertSame( [
1055 [ LogLevel
::DEBUG
, 'denied by prior creation attempt failures' ],
1056 ], $logger->getBuffer() );
1057 $logger->clearBuffer();
1059 // Sanity check that creation still works, and test completion hook
1060 $cb = $this->callback( function ( User
$user ) {
1061 $this->assertNotEquals( 0, $user->getId() );
1062 $this->assertSame( 'UTSessionAutoCreate4', $user->getName() );
1063 $this->assertEquals(
1064 $user->getId(), User
::idFromName( 'UTSessionAutoCreate4', User
::READ_LATEST
)
1068 $mock = $this->getMock( 'stdClass',
1069 [ 'onAuthPluginAutoCreate', 'onLocalUserCreated' ] );
1070 $mock->expects( $this->once() )->method( 'onAuthPluginAutoCreate' )
1072 $mock->expects( $this->once() )->method( 'onLocalUserCreated' )
1073 ->with( $cb, $this->identicalTo( true ) );
1074 $this->mergeMwGlobalArrayValue( 'wgHooks', [
1075 'AuthPluginAutoCreate' => [ $mock ],
1076 'LocalUserCreated' => [ $mock ],
1078 $user = User
::newFromName( 'UTSessionAutoCreate4' );
1079 $this->assertSame( 0, $user->getId(), 'sanity check' );
1080 $this->assertTrue( $manager->autoCreateUser( $user ) );
1081 $this->assertNotEquals( 0, $user->getId() );
1082 $this->assertSame( 'UTSessionAutoCreate4', $user->getName() );
1083 $this->assertEquals(
1085 User
::idFromName( 'UTSessionAutoCreate4', User
::READ_LATEST
)
1087 $this->mergeMwGlobalArrayValue( 'wgHooks', [
1088 'AuthPluginAutoCreate' => [],
1089 'LocalUserCreated' => [],
1091 $this->assertSame( [
1092 [ LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ],
1093 ], $logger->getBuffer() );
1094 $logger->clearBuffer();
1097 public function onAbortAutoAccount( User
$user, &$msg ) {
1100 public function testPreventSessionsForUser() {
1101 $manager = $this->getManager();
1103 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
1104 ->setMethods( [ 'preventSessionsForUser', '__toString' ] );
1106 $provider1 = $providerBuilder->getMock();
1107 $provider1->expects( $this->once() )->method( 'preventSessionsForUser' )
1108 ->with( $this->equalTo( 'UTSysop' ) );
1109 $provider1->expects( $this->any() )->method( '__toString' )
1110 ->will( $this->returnValue( 'MockProvider1' ) );
1112 $this->config
->set( 'SessionProviders', [
1113 $this->objectCacheDef( $provider1 ),
1116 $this->assertFalse( $manager->isUserSessionPrevented( 'UTSysop' ) );
1117 $manager->preventSessionsForUser( 'UTSysop' );
1118 $this->assertTrue( $manager->isUserSessionPrevented( 'UTSysop' ) );
1121 public function testLoadSessionInfoFromStore() {
1122 $manager = $this->getManager();
1123 $logger = new \
TestLogger( true );
1124 $manager->setLogger( $logger );
1125 $request = new \
FauxRequest();
1127 // TestingAccessWrapper can't handle methods with reference arguments, sigh.
1128 $rClass = new \
ReflectionClass( $manager );
1129 $rMethod = $rClass->getMethod( 'loadSessionInfoFromStore' );
1130 $rMethod->setAccessible( true );
1131 $loadSessionInfoFromStore = function ( &$info ) use ( $rMethod, $manager, $request ) {
1132 return $rMethod->invokeArgs( $manager, [ &$info, $request ] );
1135 $userInfo = UserInfo
::newFromName( 'UTSysop', true );
1136 $unverifiedUserInfo = UserInfo
::newFromName( 'UTSysop', false );
1138 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
1140 'userId' => $userInfo->getId(),
1141 'userName' => $userInfo->getName(),
1142 'userToken' => $userInfo->getToken( true ),
1143 'provider' => 'Mock',
1146 $builder = $this->getMockBuilder( 'MediaWiki\\Session\\SessionProvider' )
1147 ->setMethods( [ '__toString', 'mergeMetadata', 'refreshSessionInfo' ] );
1149 $provider = $builder->getMockForAbstractClass();
1150 $provider->setManager( $manager );
1151 $provider->expects( $this->any() )->method( 'persistsSessionId' )
1152 ->will( $this->returnValue( true ) );
1153 $provider->expects( $this->any() )->method( 'canChangeUser' )
1154 ->will( $this->returnValue( true ) );
1155 $provider->expects( $this->any() )->method( 'refreshSessionInfo' )
1156 ->will( $this->returnValue( true ) );
1157 $provider->expects( $this->any() )->method( '__toString' )
1158 ->will( $this->returnValue( 'Mock' ) );
1159 $provider->expects( $this->any() )->method( 'mergeMetadata' )
1160 ->will( $this->returnCallback( function ( $a, $b ) {
1161 if ( $b === [ 'Throw' ] ) {
1162 throw new MetadataMergeException( 'no merge!' );
1164 return [ 'Merged' ];
1167 $provider2 = $builder->getMockForAbstractClass();
1168 $provider2->setManager( $manager );
1169 $provider2->expects( $this->any() )->method( 'persistsSessionId' )
1170 ->will( $this->returnValue( false ) );
1171 $provider2->expects( $this->any() )->method( 'canChangeUser' )
1172 ->will( $this->returnValue( false ) );
1173 $provider2->expects( $this->any() )->method( '__toString' )
1174 ->will( $this->returnValue( 'Mock2' ) );
1175 $provider2->expects( $this->any() )->method( 'refreshSessionInfo' )
1176 ->will( $this->returnCallback( function ( $info, $request, &$metadata ) {
1177 $metadata['changed'] = true;
1181 $provider3 = $builder->getMockForAbstractClass();
1182 $provider3->setManager( $manager );
1183 $provider3->expects( $this->any() )->method( 'persistsSessionId' )
1184 ->will( $this->returnValue( true ) );
1185 $provider3->expects( $this->any() )->method( 'canChangeUser' )
1186 ->will( $this->returnValue( true ) );
1187 $provider3->expects( $this->once() )->method( 'refreshSessionInfo' )
1188 ->will( $this->returnValue( false ) );
1189 $provider3->expects( $this->any() )->method( '__toString' )
1190 ->will( $this->returnValue( 'Mock3' ) );
1192 \TestingAccessWrapper
::newFromObject( $manager )->sessionProviders
= [
1193 (string)$provider => $provider,
1194 (string)$provider2 => $provider2,
1195 (string)$provider3 => $provider3,
1198 // No metadata, basic usage
1199 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1200 'provider' => $provider,
1202 'userInfo' => $userInfo
1204 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1205 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1206 $this->assertFalse( $info->isIdSafe() );
1207 $this->assertSame( [], $logger->getBuffer() );
1209 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1210 'provider' => $provider,
1211 'userInfo' => $userInfo
1213 $this->assertTrue( $info->isIdSafe(), 'sanity check' );
1214 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1215 $this->assertTrue( $info->isIdSafe() );
1216 $this->assertSame( [], $logger->getBuffer() );
1218 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1219 'provider' => $provider2,
1221 'userInfo' => $userInfo
1223 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1224 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1225 $this->assertTrue( $info->isIdSafe() );
1226 $this->assertSame( [], $logger->getBuffer() );
1228 // Unverified user, no metadata
1229 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1230 'provider' => $provider,
1232 'userInfo' => $unverifiedUserInfo
1234 $this->assertSame( $unverifiedUserInfo, $info->getUserInfo() );
1235 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1236 $this->assertSame( [
1239 'Session "{session}": Unverified user provided and no metadata to auth it',
1241 ], $logger->getBuffer() );
1242 $logger->clearBuffer();
1244 // No metadata, missing data
1245 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1247 'userInfo' => $userInfo
1249 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1250 $this->assertSame( [
1251 [ LogLevel
::WARNING
, 'Session "{session}": Null provider and no metadata' ],
1252 ], $logger->getBuffer() );
1253 $logger->clearBuffer();
1255 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1256 'provider' => $provider,
1259 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1260 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1261 $this->assertInstanceOf( 'MediaWiki\\Session\\UserInfo', $info->getUserInfo() );
1262 $this->assertTrue( $info->getUserInfo()->isVerified() );
1263 $this->assertTrue( $info->getUserInfo()->isAnon() );
1264 $this->assertFalse( $info->isIdSafe() );
1265 $this->assertSame( [], $logger->getBuffer() );
1267 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1268 'provider' => $provider2,
1271 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1272 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1273 $this->assertSame( [
1274 [ LogLevel
::INFO
, 'Session "{session}": No user provided and provider cannot set user' ]
1275 ], $logger->getBuffer() );
1276 $logger->clearBuffer();
1278 // Incomplete/bad metadata
1279 $this->store
->setRawSession( $id, true );
1280 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1281 $this->assertSame( [
1282 [ LogLevel
::WARNING
, 'Session "{session}": Bad data' ],
1283 ], $logger->getBuffer() );
1284 $logger->clearBuffer();
1286 $this->store
->setRawSession( $id, [ 'data' => [] ] );
1287 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1288 $this->assertSame( [
1289 [ LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ],
1290 ], $logger->getBuffer() );
1291 $logger->clearBuffer();
1293 $this->store
->deleteSession( $id );
1294 $this->store
->setRawSession( $id, [ 'metadata' => $metadata ] );
1295 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1296 $this->assertSame( [
1297 [ LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ],
1298 ], $logger->getBuffer() );
1299 $logger->clearBuffer();
1301 $this->store
->setRawSession( $id, [ 'metadata' => $metadata, 'data' => true ] );
1302 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1303 $this->assertSame( [
1304 [ LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ],
1305 ], $logger->getBuffer() );
1306 $logger->clearBuffer();
1308 $this->store
->setRawSession( $id, [ 'metadata' => true, 'data' => [] ] );
1309 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1310 $this->assertSame( [
1311 [ LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ],
1312 ], $logger->getBuffer() );
1313 $logger->clearBuffer();
1315 foreach ( $metadata as $key => $dummy ) {
1317 unset( $tmp[$key] );
1318 $this->store
->setRawSession( $id, [ 'metadata' => $tmp, 'data' => [] ] );
1319 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1320 $this->assertSame( [
1321 [ LogLevel
::WARNING
, 'Session "{session}": Bad metadata' ],
1322 ], $logger->getBuffer() );
1323 $logger->clearBuffer();
1326 // Basic usage with metadata
1327 $this->store
->setRawSession( $id, [ 'metadata' => $metadata, 'data' => [] ] );
1328 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1329 'provider' => $provider,
1331 'userInfo' => $userInfo
1333 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1334 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1335 $this->assertTrue( $info->isIdSafe() );
1336 $this->assertSame( [], $logger->getBuffer() );
1338 // Mismatched provider
1339 $this->store
->setSessionMeta( $id, [ 'provider' => 'Bad' ] +
$metadata );
1340 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1341 'provider' => $provider,
1343 'userInfo' => $userInfo
1345 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1346 $this->assertSame( [
1347 [ LogLevel
::WARNING
, 'Session "{session}": Wrong provider Bad !== Mock' ],
1348 ], $logger->getBuffer() );
1349 $logger->clearBuffer();
1352 $this->store
->setSessionMeta( $id, [ 'provider' => 'Bad' ] +
$metadata );
1353 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1355 'userInfo' => $userInfo
1357 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1358 $this->assertSame( [
1359 [ LogLevel
::WARNING
, 'Session "{session}": Unknown provider Bad' ],
1360 ], $logger->getBuffer() );
1361 $logger->clearBuffer();
1364 $this->store
->setSessionMeta( $id, $metadata );
1365 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1367 'userInfo' => $userInfo
1369 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1370 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1371 $this->assertTrue( $info->isIdSafe() );
1372 $this->assertSame( [], $logger->getBuffer() );
1374 // Bad user metadata
1375 $this->store
->setSessionMeta( $id, [ 'userId' => -1, 'userToken' => null ] +
$metadata );
1376 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1377 'provider' => $provider,
1380 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1381 $this->assertSame( [
1382 [ LogLevel
::ERROR
, 'Session "{session}": {exception}' ],
1383 ], $logger->getBuffer() );
1384 $logger->clearBuffer();
1386 $this->store
->setSessionMeta(
1387 $id, [ 'userId' => 0, 'userName' => '<X>', 'userToken' => null ] +
$metadata
1389 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1390 'provider' => $provider,
1393 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1394 $this->assertSame( [
1395 [ LogLevel
::ERROR
, 'Session "{session}": {exception}', ],
1396 ], $logger->getBuffer() );
1397 $logger->clearBuffer();
1399 // Mismatched user by ID
1400 $this->store
->setSessionMeta(
1401 $id, [ 'userId' => $userInfo->getId() +
1, 'userToken' => null ] +
$metadata
1403 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1404 'provider' => $provider,
1406 'userInfo' => $userInfo
1408 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1409 $this->assertSame( [
1410 [ LogLevel
::WARNING
, 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}' ],
1411 ], $logger->getBuffer() );
1412 $logger->clearBuffer();
1414 // Mismatched user by name
1415 $this->store
->setSessionMeta(
1416 $id, [ 'userId' => 0, 'userName' => 'X', 'userToken' => null ] +
$metadata
1418 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1419 'provider' => $provider,
1421 'userInfo' => $userInfo
1423 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1424 $this->assertSame( [
1425 [ LogLevel
::WARNING
, 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}' ],
1426 ], $logger->getBuffer() );
1427 $logger->clearBuffer();
1429 // ID matches, name doesn't
1430 $this->store
->setSessionMeta(
1431 $id, [ 'userId' => $userInfo->getId(), 'userName' => 'X', 'userToken' => null ] +
$metadata
1433 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1434 'provider' => $provider,
1436 'userInfo' => $userInfo
1438 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1439 $this->assertSame( [
1442 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}'
1444 ], $logger->getBuffer() );
1445 $logger->clearBuffer();
1447 // Mismatched anon user
1448 $this->store
->setSessionMeta(
1449 $id, [ 'userId' => 0, 'userName' => null, 'userToken' => null ] +
$metadata
1451 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1452 'provider' => $provider,
1454 'userInfo' => $userInfo
1456 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1457 $this->assertSame( [
1460 'Session "{session}": Metadata has an anonymous user, ' .
1461 'but a non-anon user was provided',
1463 ], $logger->getBuffer() );
1464 $logger->clearBuffer();
1466 // Lookup user by ID
1467 $this->store
->setSessionMeta( $id, [ 'userToken' => null ] +
$metadata );
1468 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1469 'provider' => $provider,
1472 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1473 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1474 $this->assertSame( $userInfo->getId(), $info->getUserInfo()->getId() );
1475 $this->assertTrue( $info->isIdSafe() );
1476 $this->assertSame( [], $logger->getBuffer() );
1478 // Lookup user by name
1479 $this->store
->setSessionMeta(
1480 $id, [ 'userId' => 0, 'userName' => 'UTSysop', 'userToken' => null ] +
$metadata
1482 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1483 'provider' => $provider,
1486 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1487 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1488 $this->assertSame( $userInfo->getId(), $info->getUserInfo()->getId() );
1489 $this->assertTrue( $info->isIdSafe() );
1490 $this->assertSame( [], $logger->getBuffer() );
1492 // Lookup anonymous user
1493 $this->store
->setSessionMeta(
1494 $id, [ 'userId' => 0, 'userName' => null, 'userToken' => null ] +
$metadata
1496 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1497 'provider' => $provider,
1500 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1501 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1502 $this->assertTrue( $info->getUserInfo()->isAnon() );
1503 $this->assertTrue( $info->isIdSafe() );
1504 $this->assertSame( [], $logger->getBuffer() );
1506 // Unverified user with metadata
1507 $this->store
->setSessionMeta( $id, $metadata );
1508 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1509 'provider' => $provider,
1511 'userInfo' => $unverifiedUserInfo
1513 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1514 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1515 $this->assertTrue( $info->getUserInfo()->isVerified() );
1516 $this->assertSame( $unverifiedUserInfo->getId(), $info->getUserInfo()->getId() );
1517 $this->assertSame( $unverifiedUserInfo->getName(), $info->getUserInfo()->getName() );
1518 $this->assertTrue( $info->isIdSafe() );
1519 $this->assertSame( [], $logger->getBuffer() );
1521 // Unverified user with metadata
1522 $this->store
->setSessionMeta( $id, $metadata );
1523 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1524 'provider' => $provider,
1526 'userInfo' => $unverifiedUserInfo
1528 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1529 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1530 $this->assertTrue( $info->getUserInfo()->isVerified() );
1531 $this->assertSame( $unverifiedUserInfo->getId(), $info->getUserInfo()->getId() );
1532 $this->assertSame( $unverifiedUserInfo->getName(), $info->getUserInfo()->getName() );
1533 $this->assertTrue( $info->isIdSafe() );
1534 $this->assertSame( [], $logger->getBuffer() );
1537 $this->store
->setSessionMeta( $id, [ 'userToken' => 'Bad' ] +
$metadata );
1538 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1539 'provider' => $provider,
1541 'userInfo' => $userInfo
1543 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1544 $this->assertSame( [
1545 [ LogLevel
::WARNING
, 'Session "{session}": User token mismatch' ],
1546 ], $logger->getBuffer() );
1547 $logger->clearBuffer();
1549 // Provider metadata
1550 $this->store
->setSessionMeta( $id, [ 'provider' => 'Mock2' ] +
$metadata );
1551 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1552 'provider' => $provider2,
1554 'userInfo' => $userInfo,
1555 'metadata' => [ 'Info' ],
1557 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1558 $this->assertSame( [ 'Info', 'changed' => true ], $info->getProviderMetadata() );
1559 $this->assertSame( [], $logger->getBuffer() );
1561 $this->store
->setSessionMeta( $id, [ 'providerMetadata' => [ 'Saved' ] ] +
$metadata );
1562 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1563 'provider' => $provider,
1565 'userInfo' => $userInfo,
1567 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1568 $this->assertSame( [ 'Saved' ], $info->getProviderMetadata() );
1569 $this->assertSame( [], $logger->getBuffer() );
1571 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1572 'provider' => $provider,
1574 'userInfo' => $userInfo,
1575 'metadata' => [ 'Info' ],
1577 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1578 $this->assertSame( [ 'Merged' ], $info->getProviderMetadata() );
1579 $this->assertSame( [], $logger->getBuffer() );
1581 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1582 'provider' => $provider,
1584 'userInfo' => $userInfo,
1585 'metadata' => [ 'Throw' ],
1587 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1588 $this->assertSame( [
1591 'Session "{session}": Metadata merge failed: {exception}',
1593 ], $logger->getBuffer() );
1594 $logger->clearBuffer();
1596 // Remember from session
1597 $this->store
->setSessionMeta( $id, $metadata );
1598 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1599 'provider' => $provider,
1602 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1603 $this->assertFalse( $info->wasRemembered() );
1604 $this->assertSame( [], $logger->getBuffer() );
1606 $this->store
->setSessionMeta( $id, [ 'remember' => true ] +
$metadata );
1607 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1608 'provider' => $provider,
1611 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1612 $this->assertTrue( $info->wasRemembered() );
1613 $this->assertSame( [], $logger->getBuffer() );
1615 $this->store
->setSessionMeta( $id, [ 'remember' => false ] +
$metadata );
1616 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1617 'provider' => $provider,
1619 'userInfo' => $userInfo
1621 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1622 $this->assertTrue( $info->wasRemembered() );
1623 $this->assertSame( [], $logger->getBuffer() );
1625 // forceHTTPS from session
1626 $this->store
->setSessionMeta( $id, $metadata );
1627 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1628 'provider' => $provider,
1630 'userInfo' => $userInfo
1632 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1633 $this->assertFalse( $info->forceHTTPS() );
1634 $this->assertSame( [], $logger->getBuffer() );
1636 $this->store
->setSessionMeta( $id, [ 'forceHTTPS' => true ] +
$metadata );
1637 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1638 'provider' => $provider,
1640 'userInfo' => $userInfo
1642 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1643 $this->assertTrue( $info->forceHTTPS() );
1644 $this->assertSame( [], $logger->getBuffer() );
1646 $this->store
->setSessionMeta( $id, [ 'forceHTTPS' => false ] +
$metadata );
1647 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1648 'provider' => $provider,
1650 'userInfo' => $userInfo,
1651 'forceHTTPS' => true
1653 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1654 $this->assertTrue( $info->forceHTTPS() );
1655 $this->assertSame( [], $logger->getBuffer() );
1657 // "Persist" flag from session
1658 $this->store
->setSessionMeta( $id, $metadata );
1659 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1660 'provider' => $provider,
1662 'userInfo' => $userInfo
1664 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1665 $this->assertFalse( $info->wasPersisted() );
1666 $this->assertSame( [], $logger->getBuffer() );
1668 $this->store
->setSessionMeta( $id, [ 'persisted' => true ] +
$metadata );
1669 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1670 'provider' => $provider,
1672 'userInfo' => $userInfo
1674 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1675 $this->assertTrue( $info->wasPersisted() );
1676 $this->assertSame( [], $logger->getBuffer() );
1678 $this->store
->setSessionMeta( $id, [ 'persisted' => false ] +
$metadata );
1679 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1680 'provider' => $provider,
1682 'userInfo' => $userInfo,
1685 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1686 $this->assertTrue( $info->wasPersisted() );
1687 $this->assertSame( [], $logger->getBuffer() );
1689 // Provider refreshSessionInfo() returning false
1690 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1691 'provider' => $provider3,
1693 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1694 $this->assertSame( [], $logger->getBuffer() );
1698 $data = [ 'foo' => 1 ];
1699 $this->store
->setSession( $id, [ 'metadata' => $metadata, 'data' => $data ] );
1700 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1701 'provider' => $provider,
1703 'userInfo' => $userInfo
1705 $this->mergeMwGlobalArrayValue( 'wgHooks', [
1706 'SessionCheckInfo' => [ function ( &$reason, $i, $r, $m, $d ) use (
1707 $info, $metadata, $data, $request, &$called
1709 $this->assertSame( $info->getId(), $i->getId() );
1710 $this->assertSame( $info->getProvider(), $i->getProvider() );
1711 $this->assertSame( $info->getUserInfo(), $i->getUserInfo() );
1712 $this->assertSame( $request, $r );
1713 $this->assertEquals( $metadata, $m );
1714 $this->assertEquals( $data, $d );
1719 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1720 $this->assertTrue( $called );
1721 $this->assertSame( [
1722 [ LogLevel
::WARNING
, 'Session "{session}": Hook aborted' ],
1723 ], $logger->getBuffer() );
1724 $logger->clearBuffer();