3 namespace MediaWiki\Session
;
6 use MediaWiki\Logger\LoggerFactory
;
14 * @covers MediaWiki\Session\SessionManager
16 class SessionManagerTest
extends MediaWikiTestCase
{
18 protected $config, $logger, $store;
20 protected function getManager() {
21 \ObjectCache
::$instances['testSessionStore'] = new TestBagOStuff();
22 $this->config
= new \
HashConfig( array(
23 'LanguageCode' => 'en',
24 'SessionCacheType' => 'testSessionStore',
25 'ObjectCacheSessionExpiry' => 100,
26 'SessionProviders' => array(
27 array( 'class' => 'DummySessionProvider' ),
30 $this->logger
= new \
TestLogger( false, function ( $m ) {
31 return substr( $m, 0, 15 ) === 'SessionBackend ' ?
null : $m;
33 $this->store
= new TestBagOStuff();
35 return new SessionManager( array(
36 'config' => $this->config
,
37 'logger' => $this->logger
,
38 'store' => $this->store
,
42 protected function objectCacheDef( $object ) {
43 return array( 'factory' => function () use ( $object ) {
48 public function testSingleton() {
49 $reset = TestUtils
::setSessionManagerSingleton( null );
51 $singleton = SessionManager
::singleton();
52 $this->assertInstanceOf( 'MediaWiki\\Session\\SessionManager', $singleton );
53 $this->assertSame( $singleton, SessionManager
::singleton() );
56 public function testGetGlobalSession() {
57 $context = \RequestContext
::getMain();
59 if ( !PHPSessionHandler
::isInstalled() ) {
60 PHPSessionHandler
::install( SessionManager
::singleton() );
62 $rProp = new \
ReflectionProperty( 'MediaWiki\\Session\\PHPSessionHandler', 'instance' );
63 $rProp->setAccessible( true );
64 $handler = \TestingAccessWrapper
::newFromObject( $rProp->getValue() );
65 $oldEnable = $handler->enable
;
66 $reset[] = new \
ScopedCallback( function () use ( $handler, $oldEnable ) {
67 if ( $handler->enable
) {
68 session_write_close();
70 $handler->enable
= $oldEnable;
72 $reset[] = TestUtils
::setSessionManagerSingleton( $this->getManager() );
74 $handler->enable
= true;
75 $request = new \
FauxRequest();
76 $context->setRequest( $request );
77 $id = $request->getSession()->getId();
80 $session = SessionManager
::getGlobalSession();
81 $this->assertSame( $id, $session->getId() );
83 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
84 $session = SessionManager
::getGlobalSession();
85 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $session->getId() );
86 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $request->getSession()->getId() );
88 session_write_close();
89 $handler->enable
= false;
90 $request = new \
FauxRequest();
91 $context->setRequest( $request );
92 $id = $request->getSession()->getId();
95 $session = SessionManager
::getGlobalSession();
96 $this->assertSame( $id, $session->getId() );
98 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
99 $session = SessionManager
::getGlobalSession();
100 $this->assertSame( $id, $session->getId() );
101 $this->assertSame( $id, $request->getSession()->getId() );
104 public function testConstructor() {
105 $manager = \TestingAccessWrapper
::newFromObject( $this->getManager() );
106 $this->assertSame( $this->config
, $manager->config
);
107 $this->assertSame( $this->logger
, $manager->logger
);
108 $this->assertSame( $this->store
, $manager->store
);
110 $manager = \TestingAccessWrapper
::newFromObject( new SessionManager() );
111 $this->assertSame( \RequestContext
::getMain()->getConfig(), $manager->config
);
113 $manager = \TestingAccessWrapper
::newFromObject( new SessionManager( array(
114 'config' => $this->config
,
116 $this->assertSame( \ObjectCache
::$instances['testSessionStore'], $manager->store
);
119 'config' => '$options[\'config\'] must be an instance of Config',
120 'logger' => '$options[\'logger\'] must be an instance of LoggerInterface',
121 'store' => '$options[\'store\'] must be an instance of BagOStuff',
122 ) as $key => $error ) {
124 new SessionManager( array( $key => new \stdClass
) );
125 $this->fail( 'Expected exception not thrown' );
126 } catch ( \InvalidArgumentException
$ex ) {
127 $this->assertSame( $error, $ex->getMessage() );
132 public function testGetSessionForRequest() {
133 $manager = $this->getManager();
134 $request = new \
FauxRequest();
138 $idEmpty = 'empty-session-------------------';
140 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
142 array( 'provideSessionInfo', 'newSessionInfo', '__toString', 'describe' )
145 $provider1 = $providerBuilder->getMock();
146 $provider1->expects( $this->any() )->method( 'provideSessionInfo' )
147 ->with( $this->identicalTo( $request ) )
148 ->will( $this->returnCallback( function ( $request ) {
149 return $request->info1
;
151 $provider1->expects( $this->any() )->method( 'newSessionInfo' )
152 ->will( $this->returnCallback( function () use ( $idEmpty, $provider1 ) {
153 return new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
154 'provider' => $provider1,
160 $provider1->expects( $this->any() )->method( '__toString' )
161 ->will( $this->returnValue( 'Provider1' ) );
162 $provider1->expects( $this->any() )->method( 'describe' )
163 ->will( $this->returnValue( '#1 sessions' ) );
165 $provider2 = $providerBuilder->getMock();
166 $provider2->expects( $this->any() )->method( 'provideSessionInfo' )
167 ->with( $this->identicalTo( $request ) )
168 ->will( $this->returnCallback( function ( $request ) {
169 return $request->info2
;
171 $provider2->expects( $this->any() )->method( '__toString' )
172 ->will( $this->returnValue( 'Provider2' ) );
173 $provider2->expects( $this->any() )->method( 'describe' )
174 ->will( $this->returnValue( '#2 sessions' ) );
176 $this->config
->set( 'SessionProviders', array(
177 $this->objectCacheDef( $provider1 ),
178 $this->objectCacheDef( $provider2 ),
181 // No provider returns info
182 $request->info1
= null;
183 $request->info2
= null;
184 $session = $manager->getSessionForRequest( $request );
185 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
186 $this->assertSame( $idEmpty, $session->getId() );
188 // Both providers return info, picks best one
189 $request->info1
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, array(
190 'provider' => $provider1,
191 'id' => ( $id1 = $manager->generateSessionId() ),
195 $request->info2
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
2, array(
196 'provider' => $provider2,
197 'id' => ( $id2 = $manager->generateSessionId() ),
201 $session = $manager->getSessionForRequest( $request );
202 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
203 $this->assertSame( $id2, $session->getId() );
205 $request->info1
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
2, array(
206 'provider' => $provider1,
207 'id' => ( $id1 = $manager->generateSessionId() ),
211 $request->info2
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, array(
212 'provider' => $provider2,
213 'id' => ( $id2 = $manager->generateSessionId() ),
217 $session = $manager->getSessionForRequest( $request );
218 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
219 $this->assertSame( $id1, $session->getId() );
222 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, array(
223 'provider' => $provider1,
224 'id' => ( $id1 = $manager->generateSessionId() ),
226 'userInfo' => UserInfo
::newAnonymous(),
229 $request->info2
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, array(
230 'provider' => $provider2,
231 'id' => ( $id2 = $manager->generateSessionId() ),
233 'userInfo' => UserInfo
::newAnonymous(),
237 $manager->getSessionForRequest( $request );
238 $this->fail( 'Expcected exception not thrown' );
239 } catch ( \OverFlowException
$ex ) {
240 $this->assertStringStartsWith(
241 'Multiple sessions for this request tied for top priority: ',
244 $this->assertCount( 2, $ex->sessionInfos
);
245 $this->assertContains( $request->info1
, $ex->sessionInfos
);
246 $this->assertContains( $request->info2
, $ex->sessionInfos
);
250 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, array(
251 'provider' => $provider2,
252 'id' => ( $id1 = $manager->generateSessionId() ),
256 $request->info2
= null;
258 $manager->getSessionForRequest( $request );
259 $this->fail( 'Expcected exception not thrown' );
260 } catch ( \UnexpectedValueException
$ex ) {
262 'Provider1 returned session info for a different provider: ' . $request->info1
,
267 // Unusable session info
268 $this->logger
->setCollect( true );
269 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, array(
270 'provider' => $provider1,
271 'id' => ( $id1 = $manager->generateSessionId() ),
273 'userInfo' => UserInfo
::newFromName( 'UTSysop', false ),
276 $request->info2
= new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
277 'provider' => $provider2,
278 'id' => ( $id2 = $manager->generateSessionId() ),
282 $session = $manager->getSessionForRequest( $request );
283 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
284 $this->assertSame( $id2, $session->getId() );
285 $this->logger
->setCollect( false );
287 // Unpersisted session ID
288 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, array(
289 'provider' => $provider1,
290 'id' => ( $id1 = $manager->generateSessionId() ),
291 'persisted' => false,
292 'userInfo' => UserInfo
::newFromName( 'UTSysop', true ),
295 $request->info2
= null;
296 $session = $manager->getSessionForRequest( $request );
297 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
298 $this->assertSame( $id1, $session->getId() );
300 $this->assertTrue( $session->isPersistent(), 'sanity check' );
303 public function testGetSessionById() {
304 $manager = $this->getManager();
306 $manager->getSessionById( 'bad' );
307 $this->fail( 'Expected exception not thrown' );
308 } catch ( \InvalidArgumentException
$ex ) {
309 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
312 // Unknown session ID
313 $id = $manager->generateSessionId();
314 $session = $manager->getSessionById( $id, true );
315 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
316 $this->assertSame( $id, $session->getId() );
318 $id = $manager->generateSessionId();
319 $this->assertNull( $manager->getSessionById( $id, false ) );
321 // Known but unloadable session ID
322 $this->logger
->setCollect( true );
323 $id = $manager->generateSessionId();
324 $this->store
->setSession( $id, array( 'metadata' => array(
325 'userId' => User
::idFromName( 'UTSysop' ),
326 'userToken' => 'bad',
329 $this->assertNull( $manager->getSessionById( $id, true ) );
330 $this->assertNull( $manager->getSessionById( $id, false ) );
331 $this->logger
->setCollect( false );
334 $this->store
->setSession( $id, array() );
335 $session = $manager->getSessionById( $id, false );
336 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
337 $this->assertSame( $id, $session->getId() );
340 public function testGetEmptySession() {
341 $manager = $this->getManager();
342 $pmanager = \TestingAccessWrapper
::newFromObject( $manager );
343 $request = new \
FauxRequest();
345 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
346 ->setMethods( array( 'provideSessionInfo', 'newSessionInfo', '__toString' ) );
352 $provider1 = $providerBuilder->getMock();
353 $provider1->expects( $this->any() )->method( 'provideSessionInfo' )
354 ->will( $this->returnValue( null ) );
355 $provider1->expects( $this->any() )->method( 'newSessionInfo' )
356 ->with( $this->callback( function ( $id ) use ( &$expectId ) {
357 return $id === $expectId;
359 ->will( $this->returnCallback( function () use ( &$info1 ) {
362 $provider1->expects( $this->any() )->method( '__toString' )
363 ->will( $this->returnValue( 'MockProvider1' ) );
365 $provider2 = $providerBuilder->getMock();
366 $provider2->expects( $this->any() )->method( 'provideSessionInfo' )
367 ->will( $this->returnValue( null ) );
368 $provider2->expects( $this->any() )->method( 'newSessionInfo' )
369 ->with( $this->callback( function ( $id ) use ( &$expectId ) {
370 return $id === $expectId;
372 ->will( $this->returnCallback( function () use ( &$info2 ) {
375 $provider1->expects( $this->any() )->method( '__toString' )
376 ->will( $this->returnValue( 'MockProvider2' ) );
378 $this->config
->set( 'SessionProviders', array(
379 $this->objectCacheDef( $provider1 ),
380 $this->objectCacheDef( $provider2 ),
388 $manager->getEmptySession();
389 $this->fail( 'Expected exception not thrown' );
390 } catch ( \UnexpectedValueException
$ex ) {
392 'No provider could provide an empty session!',
399 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
400 'provider' => $provider1,
401 'id' => 'empty---------------------------',
406 $session = $manager->getEmptySession();
407 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
408 $this->assertSame( 'empty---------------------------', $session->getId() );
411 $expectId = 'expected------------------------';
412 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
413 'provider' => $provider1,
419 $session = $pmanager->getEmptySessionInternal( null, $expectId );
420 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
421 $this->assertSame( $expectId, $session->getId() );
424 $expectId = 'expected-----------------------2';
425 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
426 'provider' => $provider1,
427 'id' => "un$expectId",
433 $pmanager->getEmptySessionInternal( null, $expectId );
434 $this->fail( 'Expected exception not thrown' );
435 } catch ( \UnexpectedValueException
$ex ) {
437 'MockProvider1 returned empty session info with a wrong id: ' .
438 "un$expectId != $expectId",
444 $expectId = 'expected-----------------------2';
445 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
446 'provider' => $provider1,
452 $pmanager->getEmptySessionInternal( null, $expectId );
453 $this->fail( 'Expected exception not thrown' );
454 } catch ( \UnexpectedValueException
$ex ) {
456 'MockProvider1 returned empty session info with id flagged unsafe',
463 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
464 'provider' => $provider2,
465 'id' => 'empty---------------------------',
471 $manager->getEmptySession();
472 $this->fail( 'Expected exception not thrown' );
473 } catch ( \UnexpectedValueException
$ex ) {
475 'MockProvider1 returned an empty session info for a different provider: ' . $info1,
480 // Highest priority wins
482 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, array(
483 'provider' => $provider1,
484 'id' => 'empty1--------------------------',
488 $info2 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
489 'provider' => $provider2,
490 'id' => 'empty2--------------------------',
494 $session = $manager->getEmptySession();
495 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
496 $this->assertSame( 'empty1--------------------------', $session->getId() );
499 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, array(
500 'provider' => $provider1,
501 'id' => 'empty1--------------------------',
505 $info2 = new SessionInfo( SessionInfo
::MIN_PRIORITY +
2, array(
506 'provider' => $provider2,
507 'id' => 'empty2--------------------------',
511 $session = $manager->getEmptySession();
512 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
513 $this->assertSame( 'empty2--------------------------', $session->getId() );
515 // Tied priorities throw an exception
517 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
518 'provider' => $provider1,
519 'id' => 'empty1--------------------------',
521 'userInfo' => UserInfo
::newAnonymous(),
524 $info2 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
525 'provider' => $provider2,
526 'id' => 'empty2--------------------------',
528 'userInfo' => UserInfo
::newAnonymous(),
532 $manager->getEmptySession();
533 $this->fail( 'Expected exception not thrown' );
534 } catch ( \UnexpectedValueException
$ex ) {
535 $this->assertStringStartsWith(
536 'Multiple empty sessions tied for top priority: ',
543 $pmanager->getEmptySessionInternal( null, 'bad' );
544 $this->fail( 'Expected exception not thrown' );
545 } catch ( \InvalidArgumentException
$ex ) {
546 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
549 // Session already exists
550 $expectId = 'expected-----------------------3';
551 $this->store
->setSessionMeta( $expectId, array(
552 'provider' => 'MockProvider2',
558 $pmanager->getEmptySessionInternal( null, $expectId );
559 $this->fail( 'Expected exception not thrown' );
560 } catch ( \InvalidArgumentException
$ex ) {
561 $this->assertSame( 'Session ID already exists', $ex->getMessage() );
565 public function testGetVaryHeaders() {
566 $manager = $this->getManager();
568 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
569 ->setMethods( array( 'getVaryHeaders', '__toString' ) );
571 $provider1 = $providerBuilder->getMock();
572 $provider1->expects( $this->once() )->method( 'getVaryHeaders' )
573 ->will( $this->returnValue( array(
575 'Bar' => array( 'X', 'Bar1' ),
578 $provider1->expects( $this->any() )->method( '__toString' )
579 ->will( $this->returnValue( 'MockProvider1' ) );
581 $provider2 = $providerBuilder->getMock();
582 $provider2->expects( $this->once() )->method( 'getVaryHeaders' )
583 ->will( $this->returnValue( array(
585 'Bar' => array( 'X', 'Bar2' ),
586 'Quux' => array( 'Quux' ),
588 $provider2->expects( $this->any() )->method( '__toString' )
589 ->will( $this->returnValue( 'MockProvider2' ) );
591 $this->config
->set( 'SessionProviders', array(
592 $this->objectCacheDef( $provider1 ),
593 $this->objectCacheDef( $provider2 ),
598 'Bar' => array( 'X', 'Bar1', 3 => 'Bar2' ),
599 'Quux' => array( 'Quux' ),
603 $this->assertEquals( $expect, $manager->getVaryHeaders() );
605 // Again, to ensure it's cached
606 $this->assertEquals( $expect, $manager->getVaryHeaders() );
609 public function testGetVaryCookies() {
610 $manager = $this->getManager();
612 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
613 ->setMethods( array( 'getVaryCookies', '__toString' ) );
615 $provider1 = $providerBuilder->getMock();
616 $provider1->expects( $this->once() )->method( 'getVaryCookies' )
617 ->will( $this->returnValue( array( 'Foo', 'Bar' ) ) );
618 $provider1->expects( $this->any() )->method( '__toString' )
619 ->will( $this->returnValue( 'MockProvider1' ) );
621 $provider2 = $providerBuilder->getMock();
622 $provider2->expects( $this->once() )->method( 'getVaryCookies' )
623 ->will( $this->returnValue( array( 'Foo', 'Baz' ) ) );
624 $provider2->expects( $this->any() )->method( '__toString' )
625 ->will( $this->returnValue( 'MockProvider2' ) );
627 $this->config
->set( 'SessionProviders', array(
628 $this->objectCacheDef( $provider1 ),
629 $this->objectCacheDef( $provider2 ),
632 $expect = array( 'Foo', 'Bar', 'Baz' );
634 $this->assertEquals( $expect, $manager->getVaryCookies() );
636 // Again, to ensure it's cached
637 $this->assertEquals( $expect, $manager->getVaryCookies() );
640 public function testGetProviders() {
641 $realManager = $this->getManager();
642 $manager = \TestingAccessWrapper
::newFromObject( $realManager );
644 $this->config
->set( 'SessionProviders', array(
645 array( 'class' => 'DummySessionProvider' ),
647 $providers = $manager->getProviders();
648 $this->assertArrayHasKey( 'DummySessionProvider', $providers );
649 $provider = \TestingAccessWrapper
::newFromObject( $providers['DummySessionProvider'] );
650 $this->assertSame( $manager->logger
, $provider->logger
);
651 $this->assertSame( $manager->config
, $provider->config
);
652 $this->assertSame( $realManager, $provider->getManager() );
654 $this->config
->set( 'SessionProviders', array(
655 array( 'class' => 'DummySessionProvider' ),
656 array( 'class' => 'DummySessionProvider' ),
658 $manager->sessionProviders
= null;
660 $manager->getProviders();
661 $this->fail( 'Expected exception not thrown' );
662 } catch ( \UnexpectedValueException
$ex ) {
664 'Duplicate provider name "DummySessionProvider"',
670 public function testShutdown() {
671 $manager = \TestingAccessWrapper
::newFromObject( $this->getManager() );
672 $manager->setLogger( new \Psr\Log\
NullLogger() );
674 $mock = $this->getMock( 'stdClass', array( 'save' ) );
675 $mock->expects( $this->once() )->method( 'save' );
677 $manager->allSessionBackends
= array( $mock );
678 $manager->shutdown();
681 public function testGetSessionFromInfo() {
682 $manager = \TestingAccessWrapper
::newFromObject( $this->getManager() );
683 $request = new \
FauxRequest();
685 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
687 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
688 'provider' => $manager->getProvider( 'DummySessionProvider' ),
691 'userInfo' => UserInfo
::newFromName( 'UTSysop', true ),
694 \TestingAccessWrapper
::newFromObject( $info )->idIsSafe
= true;
695 $session1 = \TestingAccessWrapper
::newFromObject(
696 $manager->getSessionFromInfo( $info, $request )
698 $session2 = \TestingAccessWrapper
::newFromObject(
699 $manager->getSessionFromInfo( $info, $request )
702 $this->assertSame( $session1->backend
, $session2->backend
);
703 $this->assertNotEquals( $session1->index
, $session2->index
);
704 $this->assertSame( $session1->getSessionId(), $session2->getSessionId() );
705 $this->assertSame( $id, $session1->getId() );
707 \TestingAccessWrapper
::newFromObject( $info )->idIsSafe
= false;
708 $session3 = $manager->getSessionFromInfo( $info, $request );
709 $this->assertNotSame( $id, $session3->getId() );
712 public function testBackendRegistration() {
713 $manager = $this->getManager();
715 $session = $manager->getSessionForRequest( new \FauxRequest
);
716 $backend = \TestingAccessWrapper
::newFromObject( $session )->backend
;
717 $sessionId = $session->getSessionId();
718 $id = (string)$sessionId;
720 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
722 $manager->changeBackendId( $backend );
723 $this->assertSame( $sessionId, $session->getSessionId() );
724 $this->assertNotEquals( $id, (string)$sessionId );
725 $id = (string)$sessionId;
727 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
729 // Destruction of the session here causes the backend to be deregistered
733 $manager->changeBackendId( $backend );
734 $this->fail( 'Expected exception not thrown' );
735 } catch ( \InvalidArgumentException
$ex ) {
737 'Backend was not registered with this SessionManager', $ex->getMessage()
742 $manager->deregisterSessionBackend( $backend );
743 $this->fail( 'Expected exception not thrown' );
744 } catch ( \InvalidArgumentException
$ex ) {
746 'Backend was not registered with this SessionManager', $ex->getMessage()
750 $session = $manager->getSessionById( $id, true );
751 $this->assertSame( $sessionId, $session->getSessionId() );
754 public function testGenerateSessionId() {
755 $manager = $this->getManager();
757 $id = $manager->generateSessionId();
758 $this->assertTrue( SessionManager
::validateSessionId( $id ), "Generated ID: $id" );
761 public function testAutoCreateUser() {
762 global $wgGroupPermissions;
764 \ObjectCache
::$instances[__METHOD__
] = new TestBagOStuff();
765 $this->setMwGlobals( array( 'wgMainCacheType' => __METHOD__
) );
766 $this->setMWGlobals( array(
767 'wgAuth' => new AuthPlugin
,
770 $this->stashMwGlobals( array( 'wgGroupPermissions' ) );
771 $wgGroupPermissions['*']['createaccount'] = true;
772 $wgGroupPermissions['*']['autocreateaccount'] = false;
774 // Replace the global singleton with one configured for testing
775 $manager = $this->getManager();
776 $reset = TestUtils
::setSessionManagerSingleton( $manager );
778 $logger = new \
TestLogger( true, function ( $m ) {
779 if ( substr( $m, 0, 15 ) === 'SessionBackend ' ) {
783 $m = str_replace( 'MediaWiki\Session\SessionManager::autoCreateUser: ', '', $m );
786 $manager->setLogger( $logger );
788 $session = SessionManager
::getGlobalSession();
790 // Can't create an already-existing user
791 $user = User
::newFromName( 'UTSysop' );
792 $id = $user->getId();
793 $this->assertFalse( $manager->autoCreateUser( $user ) );
794 $this->assertSame( $id, $user->getId() );
795 $this->assertSame( 'UTSysop', $user->getName() );
796 $this->assertSame( array(), $logger->getBuffer() );
797 $logger->clearBuffer();
799 // Sanity check that creation works at all
800 $user = User
::newFromName( 'UTSessionAutoCreate1' );
801 $this->assertSame( 0, $user->getId(), 'sanity check' );
802 $this->assertTrue( $manager->autoCreateUser( $user ) );
803 $this->assertNotEquals( 0, $user->getId() );
804 $this->assertSame( 'UTSessionAutoCreate1', $user->getName() );
806 $user->getId(), User
::idFromName( 'UTSessionAutoCreate1', User
::READ_LATEST
)
808 $this->assertSame( array(
809 array( LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ),
810 ), $logger->getBuffer() );
811 $logger->clearBuffer();
813 // Check lack of permissions
814 $wgGroupPermissions['*']['createaccount'] = false;
815 $wgGroupPermissions['*']['autocreateaccount'] = false;
816 $user = User
::newFromName( 'UTDoesNotExist' );
817 $this->assertFalse( $manager->autoCreateUser( $user ) );
818 $this->assertSame( 0, $user->getId() );
819 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
820 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
822 $this->assertSame( array(
825 'user is blocked from this wiki, blacklisting',
827 ), $logger->getBuffer() );
828 $logger->clearBuffer();
830 // Check other permission
831 $wgGroupPermissions['*']['createaccount'] = false;
832 $wgGroupPermissions['*']['autocreateaccount'] = true;
833 $user = User
::newFromName( 'UTSessionAutoCreate2' );
834 $this->assertSame( 0, $user->getId(), 'sanity check' );
835 $this->assertTrue( $manager->autoCreateUser( $user ) );
836 $this->assertNotEquals( 0, $user->getId() );
837 $this->assertSame( 'UTSessionAutoCreate2', $user->getName() );
839 $user->getId(), User
::idFromName( 'UTSessionAutoCreate2', User
::READ_LATEST
)
841 $this->assertSame( array(
842 array( LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ),
843 ), $logger->getBuffer() );
844 $logger->clearBuffer();
846 // Test account-creation block
848 $block = new \
Block( array(
849 'address' => $anon->getName(),
851 'reason' => __METHOD__
,
852 'expiry' => time() +
100500,
853 'createAccount' => true,
856 $this->assertInstanceOf( 'Block', $anon->isBlockedFromCreateAccount(), 'sanity check' );
857 $reset2 = new \
ScopedCallback( array( $block, 'delete' ) );
858 $user = User
::newFromName( 'UTDoesNotExist' );
859 $this->assertFalse( $manager->autoCreateUser( $user ) );
860 $this->assertSame( 0, $user->getId() );
861 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
862 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
863 \ScopedCallback
::consume( $reset2 );
865 $this->assertSame( array(
866 array( LogLevel
::DEBUG
, 'user is blocked from this wiki, blacklisting' ),
867 ), $logger->getBuffer() );
868 $logger->clearBuffer();
870 // Sanity check that creation still works
871 $user = User
::newFromName( 'UTSessionAutoCreate3' );
872 $this->assertSame( 0, $user->getId(), 'sanity check' );
873 $this->assertTrue( $manager->autoCreateUser( $user ) );
874 $this->assertNotEquals( 0, $user->getId() );
875 $this->assertSame( 'UTSessionAutoCreate3', $user->getName() );
877 $user->getId(), User
::idFromName( 'UTSessionAutoCreate3', User
::READ_LATEST
)
879 $this->assertSame( array(
880 array( LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ),
881 ), $logger->getBuffer() );
882 $logger->clearBuffer();
884 // Test prevention by AuthPlugin
886 $oldWgAuth = $wgAuth;
887 $mockWgAuth = $this->getMock( 'AuthPlugin', array( 'autoCreate' ) );
888 $mockWgAuth->expects( $this->once() )->method( 'autoCreate' )
889 ->will( $this->returnValue( false ) );
890 $this->setMwGlobals( array(
891 'wgAuth' => $mockWgAuth,
893 $user = User
::newFromName( 'UTDoesNotExist' );
894 $this->assertFalse( $manager->autoCreateUser( $user ) );
895 $this->assertSame( 0, $user->getId() );
896 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
897 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
898 $this->setMwGlobals( array(
899 'wgAuth' => $oldWgAuth,
902 $this->assertSame( array(
903 array( LogLevel
::DEBUG
, 'denied by AuthPlugin' ),
904 ), $logger->getBuffer() );
905 $logger->clearBuffer();
907 // Test prevention by wfReadOnly()
908 $this->setMwGlobals( array(
909 'wgReadOnly' => 'Because',
911 $user = User
::newFromName( 'UTDoesNotExist' );
912 $this->assertFalse( $manager->autoCreateUser( $user ) );
913 $this->assertSame( 0, $user->getId() );
914 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
915 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
916 $this->setMwGlobals( array(
917 'wgReadOnly' => false,
920 $this->assertSame( array(
921 array( LogLevel
::DEBUG
, 'denied by wfReadOnly()' ),
922 ), $logger->getBuffer() );
923 $logger->clearBuffer();
925 // Test prevention by a previous session
926 $session->set( 'MWSession::AutoCreateBlacklist', 'test' );
927 $user = User
::newFromName( 'UTDoesNotExist' );
928 $this->assertFalse( $manager->autoCreateUser( $user ) );
929 $this->assertSame( 0, $user->getId() );
930 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
931 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
933 $this->assertSame( array(
934 array( LogLevel
::DEBUG
, 'blacklisted in session (test)' ),
935 ), $logger->getBuffer() );
936 $logger->clearBuffer();
938 // Test uncreatable name
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
) );
945 $this->assertSame( array(
946 array( LogLevel
::DEBUG
, 'Invalid username, blacklisting' ),
947 ), $logger->getBuffer() );
948 $logger->clearBuffer();
950 // Test AbortAutoAccount hook
951 $mock = $this->getMock( __CLASS__
, array( 'onAbortAutoAccount' ) );
952 $mock->expects( $this->once() )->method( 'onAbortAutoAccount' )
953 ->will( $this->returnCallback( function ( User
$user, &$msg ) {
957 $this->mergeMwGlobalArrayValue( 'wgHooks', array( 'AbortAutoAccount' => array( $mock ) ) );
958 $user = User
::newFromName( 'UTDoesNotExist' );
959 $this->assertFalse( $manager->autoCreateUser( $user ) );
960 $this->assertSame( 0, $user->getId() );
961 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
962 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
963 $this->mergeMwGlobalArrayValue( 'wgHooks', array( 'AbortAutoAccount' => array() ) );
965 $this->assertSame( array(
966 array( LogLevel
::DEBUG
, 'denied by hook: No way!' ),
967 ), $logger->getBuffer() );
968 $logger->clearBuffer();
970 // Test AbortAutoAccount hook screwing up the name
971 $mock = $this->getMock( 'stdClass', array( 'onAbortAutoAccount' ) );
972 $mock->expects( $this->once() )->method( 'onAbortAutoAccount' )
973 ->will( $this->returnCallback( function ( User
$user ) {
974 $user->setName( 'UTDoesNotExistEither' );
976 $this->mergeMwGlobalArrayValue( 'wgHooks', array( 'AbortAutoAccount' => array( $mock ) ) );
978 $user = User
::newFromName( 'UTDoesNotExist' );
979 $manager->autoCreateUser( $user );
980 $this->fail( 'Expected exception not thrown' );
981 } catch ( \UnexpectedValueException
$ex ) {
983 'AbortAutoAccount hook tried to change the user name',
987 $this->assertSame( 0, $user->getId() );
988 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
989 $this->assertNotSame( 'UTDoesNotExistEither', $user->getName() );
990 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
991 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExistEither', User
::READ_LATEST
) );
992 $this->mergeMwGlobalArrayValue( 'wgHooks', array( 'AbortAutoAccount' => array() ) );
994 $this->assertSame( array(), $logger->getBuffer() );
995 $logger->clearBuffer();
997 // Test for "exception backoff"
998 $user = User
::newFromName( 'UTDoesNotExist' );
999 $cache = \ObjectCache
::getLocalClusterInstance();
1000 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $user->getName() ) );
1001 $cache->set( $backoffKey, 1, 60 * 10 );
1002 $this->assertFalse( $manager->autoCreateUser( $user ) );
1003 $this->assertSame( 0, $user->getId() );
1004 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
1005 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
1006 $cache->delete( $backoffKey );
1008 $this->assertSame( array(
1009 array( LogLevel
::DEBUG
, 'denied by prior creation attempt failures' ),
1010 ), $logger->getBuffer() );
1011 $logger->clearBuffer();
1013 // Sanity check that creation still works, and test completion hook
1014 $cb = $this->callback( function ( User
$user ) {
1015 $this->assertNotEquals( 0, $user->getId() );
1016 $this->assertSame( 'UTSessionAutoCreate4', $user->getName() );
1017 $this->assertEquals(
1018 $user->getId(), User
::idFromName( 'UTSessionAutoCreate4', User
::READ_LATEST
)
1022 $mock = $this->getMock( 'stdClass',
1023 array( 'onAuthPluginAutoCreate', 'onLocalUserCreated' ) );
1024 $mock->expects( $this->once() )->method( 'onAuthPluginAutoCreate' )
1026 $mock->expects( $this->once() )->method( 'onLocalUserCreated' )
1027 ->with( $cb, $this->identicalTo( true ) );
1028 $this->mergeMwGlobalArrayValue( 'wgHooks', array(
1029 'AuthPluginAutoCreate' => array( $mock ),
1030 'LocalUserCreated' => array( $mock ),
1032 $user = User
::newFromName( 'UTSessionAutoCreate4' );
1033 $this->assertSame( 0, $user->getId(), 'sanity check' );
1034 $this->assertTrue( $manager->autoCreateUser( $user ) );
1035 $this->assertNotEquals( 0, $user->getId() );
1036 $this->assertSame( 'UTSessionAutoCreate4', $user->getName() );
1037 $this->assertEquals(
1039 User
::idFromName( 'UTSessionAutoCreate4', User
::READ_LATEST
)
1041 $this->mergeMwGlobalArrayValue( 'wgHooks', array(
1042 'AuthPluginAutoCreate' => array(),
1043 'LocalUserCreated' => array(),
1045 $this->assertSame( array(
1046 array( LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ),
1047 ), $logger->getBuffer() );
1048 $logger->clearBuffer();
1051 public function onAbortAutoAccount( User
$user, &$msg ) {
1054 public function testPreventSessionsForUser() {
1055 $manager = $this->getManager();
1057 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
1058 ->setMethods( array( 'preventSessionsForUser', '__toString' ) );
1060 $provider1 = $providerBuilder->getMock();
1061 $provider1->expects( $this->once() )->method( 'preventSessionsForUser' )
1062 ->with( $this->equalTo( 'UTSysop' ) );
1063 $provider1->expects( $this->any() )->method( '__toString' )
1064 ->will( $this->returnValue( 'MockProvider1' ) );
1066 $this->config
->set( 'SessionProviders', array(
1067 $this->objectCacheDef( $provider1 ),
1070 $this->assertFalse( $manager->isUserSessionPrevented( 'UTSysop' ) );
1071 $manager->preventSessionsForUser( 'UTSysop' );
1072 $this->assertTrue( $manager->isUserSessionPrevented( 'UTSysop' ) );
1075 public function testLoadSessionInfoFromStore() {
1076 $manager = $this->getManager();
1077 $logger = new \
TestLogger( true );
1078 $manager->setLogger( $logger );
1079 $request = new \
FauxRequest();
1081 // TestingAccessWrapper can't handle methods with reference arguments, sigh.
1082 $rClass = new \
ReflectionClass( $manager );
1083 $rMethod = $rClass->getMethod( 'loadSessionInfoFromStore' );
1084 $rMethod->setAccessible( true );
1085 $loadSessionInfoFromStore = function ( &$info ) use ( $rMethod, $manager, $request ) {
1086 return $rMethod->invokeArgs( $manager, array( &$info, $request ) );
1089 $userInfo = UserInfo
::newFromName( 'UTSysop', true );
1090 $unverifiedUserInfo = UserInfo
::newFromName( 'UTSysop', false );
1092 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
1094 'userId' => $userInfo->getId(),
1095 'userName' => $userInfo->getName(),
1096 'userToken' => $userInfo->getToken( true ),
1097 'provider' => 'Mock',
1100 $builder = $this->getMockBuilder( 'MediaWiki\\Session\\SessionProvider' )
1101 ->setMethods( array( '__toString', 'mergeMetadata', 'refreshSessionInfo' ) );
1103 $provider = $builder->getMockForAbstractClass();
1104 $provider->setManager( $manager );
1105 $provider->expects( $this->any() )->method( 'persistsSessionId' )
1106 ->will( $this->returnValue( true ) );
1107 $provider->expects( $this->any() )->method( 'canChangeUser' )
1108 ->will( $this->returnValue( true ) );
1109 $provider->expects( $this->any() )->method( 'refreshSessionInfo' )
1110 ->will( $this->returnValue( true ) );
1111 $provider->expects( $this->any() )->method( '__toString' )
1112 ->will( $this->returnValue( 'Mock' ) );
1113 $provider->expects( $this->any() )->method( 'mergeMetadata' )
1114 ->will( $this->returnCallback( function ( $a, $b ) {
1115 if ( $b === array( 'Throw' ) ) {
1116 throw new MetadataMergeException( 'no merge!' );
1118 return array( 'Merged' );
1121 $provider2 = $builder->getMockForAbstractClass();
1122 $provider2->setManager( $manager );
1123 $provider2->expects( $this->any() )->method( 'persistsSessionId' )
1124 ->will( $this->returnValue( false ) );
1125 $provider2->expects( $this->any() )->method( 'canChangeUser' )
1126 ->will( $this->returnValue( false ) );
1127 $provider2->expects( $this->any() )->method( '__toString' )
1128 ->will( $this->returnValue( 'Mock2' ) );
1129 $provider2->expects( $this->any() )->method( 'refreshSessionInfo' )
1130 ->will( $this->returnCallback( function ( $info, $request, &$metadata ) {
1131 $metadata['changed'] = true;
1135 $provider3 = $builder->getMockForAbstractClass();
1136 $provider3->setManager( $manager );
1137 $provider3->expects( $this->any() )->method( 'persistsSessionId' )
1138 ->will( $this->returnValue( true ) );
1139 $provider3->expects( $this->any() )->method( 'canChangeUser' )
1140 ->will( $this->returnValue( true ) );
1141 $provider3->expects( $this->once() )->method( 'refreshSessionInfo' )
1142 ->will( $this->returnValue( false ) );
1143 $provider3->expects( $this->any() )->method( '__toString' )
1144 ->will( $this->returnValue( 'Mock3' ) );
1146 \TestingAccessWrapper
::newFromObject( $manager )->sessionProviders
= array(
1147 (string)$provider => $provider,
1148 (string)$provider2 => $provider2,
1149 (string)$provider3 => $provider3,
1152 // No metadata, basic usage
1153 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1154 'provider' => $provider,
1156 'userInfo' => $userInfo
1158 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1159 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1160 $this->assertFalse( $info->isIdSafe() );
1161 $this->assertSame( array(), $logger->getBuffer() );
1163 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1164 'provider' => $provider,
1165 'userInfo' => $userInfo
1167 $this->assertTrue( $info->isIdSafe(), 'sanity check' );
1168 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1169 $this->assertTrue( $info->isIdSafe() );
1170 $this->assertSame( array(), $logger->getBuffer() );
1172 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1173 'provider' => $provider2,
1175 'userInfo' => $userInfo
1177 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1178 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1179 $this->assertTrue( $info->isIdSafe() );
1180 $this->assertSame( array(), $logger->getBuffer() );
1182 // Unverified user, no metadata
1183 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1184 'provider' => $provider,
1186 'userInfo' => $unverifiedUserInfo
1188 $this->assertSame( $unverifiedUserInfo, $info->getUserInfo() );
1189 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1190 $this->assertSame( array(
1193 'Session "{session}": Unverified user provided and no metadata to auth it',
1195 ), $logger->getBuffer() );
1196 $logger->clearBuffer();
1198 // No metadata, missing data
1199 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1201 'userInfo' => $userInfo
1203 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1204 $this->assertSame( array(
1205 array( LogLevel
::WARNING
, 'Session "{session}": Null provider and no metadata' ),
1206 ), $logger->getBuffer() );
1207 $logger->clearBuffer();
1209 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1210 'provider' => $provider,
1213 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1214 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1215 $this->assertInstanceOf( 'MediaWiki\\Session\\UserInfo', $info->getUserInfo() );
1216 $this->assertTrue( $info->getUserInfo()->isVerified() );
1217 $this->assertTrue( $info->getUserInfo()->isAnon() );
1218 $this->assertFalse( $info->isIdSafe() );
1219 $this->assertSame( array(), $logger->getBuffer() );
1221 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1222 'provider' => $provider2,
1225 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1226 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1227 $this->assertSame( array(
1228 array( LogLevel
::INFO
, 'Session "{session}": No user provided and provider cannot set user' )
1229 ), $logger->getBuffer() );
1230 $logger->clearBuffer();
1232 // Incomplete/bad metadata
1233 $this->store
->setRawSession( $id, true );
1234 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1235 $this->assertSame( array(
1236 array( LogLevel
::WARNING
, 'Session "{session}": Bad data' ),
1237 ), $logger->getBuffer() );
1238 $logger->clearBuffer();
1240 $this->store
->setRawSession( $id, array( 'data' => array() ) );
1241 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1242 $this->assertSame( array(
1243 array( LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ),
1244 ), $logger->getBuffer() );
1245 $logger->clearBuffer();
1247 $this->store
->deleteSession( $id );
1248 $this->store
->setRawSession( $id, array( 'metadata' => $metadata ) );
1249 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1250 $this->assertSame( array(
1251 array( LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ),
1252 ), $logger->getBuffer() );
1253 $logger->clearBuffer();
1255 $this->store
->setRawSession( $id, array( 'metadata' => $metadata, 'data' => true ) );
1256 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1257 $this->assertSame( array(
1258 array( LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ),
1259 ), $logger->getBuffer() );
1260 $logger->clearBuffer();
1262 $this->store
->setRawSession( $id, array( 'metadata' => true, 'data' => array() ) );
1263 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1264 $this->assertSame( array(
1265 array( LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ),
1266 ), $logger->getBuffer() );
1267 $logger->clearBuffer();
1269 foreach ( $metadata as $key => $dummy ) {
1271 unset( $tmp[$key] );
1272 $this->store
->setRawSession( $id, array( 'metadata' => $tmp, 'data' => array() ) );
1273 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1274 $this->assertSame( array(
1275 array( LogLevel
::WARNING
, 'Session "{session}": Bad metadata' ),
1276 ), $logger->getBuffer() );
1277 $logger->clearBuffer();
1280 // Basic usage with metadata
1281 $this->store
->setRawSession( $id, array( 'metadata' => $metadata, 'data' => array() ) );
1282 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1283 'provider' => $provider,
1285 'userInfo' => $userInfo
1287 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1288 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1289 $this->assertTrue( $info->isIdSafe() );
1290 $this->assertSame( array(), $logger->getBuffer() );
1292 // Mismatched provider
1293 $this->store
->setSessionMeta( $id, array( 'provider' => 'Bad' ) +
$metadata );
1294 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1295 'provider' => $provider,
1297 'userInfo' => $userInfo
1299 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1300 $this->assertSame( array(
1301 array( LogLevel
::WARNING
, 'Session "{session}": Wrong provider Bad !== Mock' ),
1302 ), $logger->getBuffer() );
1303 $logger->clearBuffer();
1306 $this->store
->setSessionMeta( $id, array( 'provider' => 'Bad' ) +
$metadata );
1307 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1309 'userInfo' => $userInfo
1311 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1312 $this->assertSame( array(
1313 array( LogLevel
::WARNING
, 'Session "{session}": Unknown provider Bad' ),
1314 ), $logger->getBuffer() );
1315 $logger->clearBuffer();
1318 $this->store
->setSessionMeta( $id, $metadata );
1319 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1321 'userInfo' => $userInfo
1323 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1324 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1325 $this->assertTrue( $info->isIdSafe() );
1326 $this->assertSame( array(), $logger->getBuffer() );
1328 // Bad user metadata
1329 $this->store
->setSessionMeta( $id, array( 'userId' => -1, 'userToken' => null ) +
$metadata );
1330 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1331 'provider' => $provider,
1334 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1335 $this->assertSame( array(
1336 array( LogLevel
::ERROR
, 'Session "{session}": {exception}' ),
1337 ), $logger->getBuffer() );
1338 $logger->clearBuffer();
1340 $this->store
->setSessionMeta(
1341 $id, array( 'userId' => 0, 'userName' => '<X>', 'userToken' => null ) +
$metadata
1343 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1344 'provider' => $provider,
1347 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1348 $this->assertSame( array(
1349 array( LogLevel
::ERROR
, 'Session "{session}": {exception}', ),
1350 ), $logger->getBuffer() );
1351 $logger->clearBuffer();
1353 // Mismatched user by ID
1354 $this->store
->setSessionMeta(
1355 $id, array( 'userId' => $userInfo->getId() +
1, 'userToken' => null ) +
$metadata
1357 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1358 'provider' => $provider,
1360 'userInfo' => $userInfo
1362 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1363 $this->assertSame( array(
1364 array( LogLevel
::WARNING
, 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}' ),
1365 ), $logger->getBuffer() );
1366 $logger->clearBuffer();
1368 // Mismatched user by name
1369 $this->store
->setSessionMeta(
1370 $id, array( 'userId' => 0, 'userName' => 'X', 'userToken' => null ) +
$metadata
1372 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1373 'provider' => $provider,
1375 'userInfo' => $userInfo
1377 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1378 $this->assertSame( array(
1379 array( LogLevel
::WARNING
, 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}' ),
1380 ), $logger->getBuffer() );
1381 $logger->clearBuffer();
1383 // ID matches, name doesn't
1384 $this->store
->setSessionMeta(
1385 $id, array( 'userId' => $userInfo->getId(), 'userName' => 'X', 'userToken' => null ) +
$metadata
1387 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1388 'provider' => $provider,
1390 'userInfo' => $userInfo
1392 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1393 $this->assertSame( array(
1396 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}'
1398 ), $logger->getBuffer() );
1399 $logger->clearBuffer();
1401 // Mismatched anon user
1402 $this->store
->setSessionMeta(
1403 $id, array( 'userId' => 0, 'userName' => null, 'userToken' => null ) +
$metadata
1405 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1406 'provider' => $provider,
1408 'userInfo' => $userInfo
1410 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1411 $this->assertSame( array(
1414 'Session "{session}": Metadata has an anonymous user, ' .
1415 'but a non-anon user was provided',
1417 ), $logger->getBuffer() );
1418 $logger->clearBuffer();
1420 // Lookup user by ID
1421 $this->store
->setSessionMeta( $id, array( 'userToken' => null ) +
$metadata );
1422 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1423 'provider' => $provider,
1426 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1427 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1428 $this->assertSame( $userInfo->getId(), $info->getUserInfo()->getId() );
1429 $this->assertTrue( $info->isIdSafe() );
1430 $this->assertSame( array(), $logger->getBuffer() );
1432 // Lookup user by name
1433 $this->store
->setSessionMeta(
1434 $id, array( 'userId' => 0, 'userName' => 'UTSysop', 'userToken' => null ) +
$metadata
1436 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1437 'provider' => $provider,
1440 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1441 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1442 $this->assertSame( $userInfo->getId(), $info->getUserInfo()->getId() );
1443 $this->assertTrue( $info->isIdSafe() );
1444 $this->assertSame( array(), $logger->getBuffer() );
1446 // Lookup anonymous user
1447 $this->store
->setSessionMeta(
1448 $id, array( 'userId' => 0, 'userName' => null, 'userToken' => null ) +
$metadata
1450 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1451 'provider' => $provider,
1454 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1455 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1456 $this->assertTrue( $info->getUserInfo()->isAnon() );
1457 $this->assertTrue( $info->isIdSafe() );
1458 $this->assertSame( array(), $logger->getBuffer() );
1460 // Unverified user with metadata
1461 $this->store
->setSessionMeta( $id, $metadata );
1462 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1463 'provider' => $provider,
1465 'userInfo' => $unverifiedUserInfo
1467 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1468 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1469 $this->assertTrue( $info->getUserInfo()->isVerified() );
1470 $this->assertSame( $unverifiedUserInfo->getId(), $info->getUserInfo()->getId() );
1471 $this->assertSame( $unverifiedUserInfo->getName(), $info->getUserInfo()->getName() );
1472 $this->assertTrue( $info->isIdSafe() );
1473 $this->assertSame( array(), $logger->getBuffer() );
1475 // Unverified user with metadata
1476 $this->store
->setSessionMeta( $id, $metadata );
1477 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1478 'provider' => $provider,
1480 'userInfo' => $unverifiedUserInfo
1482 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1483 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1484 $this->assertTrue( $info->getUserInfo()->isVerified() );
1485 $this->assertSame( $unverifiedUserInfo->getId(), $info->getUserInfo()->getId() );
1486 $this->assertSame( $unverifiedUserInfo->getName(), $info->getUserInfo()->getName() );
1487 $this->assertTrue( $info->isIdSafe() );
1488 $this->assertSame( array(), $logger->getBuffer() );
1491 $this->store
->setSessionMeta( $id, array( 'userToken' => 'Bad' ) +
$metadata );
1492 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1493 'provider' => $provider,
1495 'userInfo' => $userInfo
1497 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1498 $this->assertSame( array(
1499 array( LogLevel
::WARNING
, 'Session "{session}": User token mismatch' ),
1500 ), $logger->getBuffer() );
1501 $logger->clearBuffer();
1503 // Provider metadata
1504 $this->store
->setSessionMeta( $id, array( 'provider' => 'Mock2' ) +
$metadata );
1505 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1506 'provider' => $provider2,
1508 'userInfo' => $userInfo,
1509 'metadata' => array( 'Info' ),
1511 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1512 $this->assertSame( array( 'Info', 'changed' => true ), $info->getProviderMetadata() );
1513 $this->assertSame( array(), $logger->getBuffer() );
1515 $this->store
->setSessionMeta( $id, array( 'providerMetadata' => array( 'Saved' ) ) +
$metadata );
1516 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1517 'provider' => $provider,
1519 'userInfo' => $userInfo,
1521 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1522 $this->assertSame( array( 'Saved' ), $info->getProviderMetadata() );
1523 $this->assertSame( array(), $logger->getBuffer() );
1525 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1526 'provider' => $provider,
1528 'userInfo' => $userInfo,
1529 'metadata' => array( 'Info' ),
1531 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1532 $this->assertSame( array( 'Merged' ), $info->getProviderMetadata() );
1533 $this->assertSame( array(), $logger->getBuffer() );
1535 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1536 'provider' => $provider,
1538 'userInfo' => $userInfo,
1539 'metadata' => array( 'Throw' ),
1541 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1542 $this->assertSame( array(
1545 'Session "{session}": Metadata merge failed: {exception}',
1547 ), $logger->getBuffer() );
1548 $logger->clearBuffer();
1550 // Remember from session
1551 $this->store
->setSessionMeta( $id, $metadata );
1552 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1553 'provider' => $provider,
1556 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1557 $this->assertFalse( $info->wasRemembered() );
1558 $this->assertSame( array(), $logger->getBuffer() );
1560 $this->store
->setSessionMeta( $id, array( 'remember' => true ) +
$metadata );
1561 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1562 'provider' => $provider,
1565 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1566 $this->assertTrue( $info->wasRemembered() );
1567 $this->assertSame( array(), $logger->getBuffer() );
1569 $this->store
->setSessionMeta( $id, array( 'remember' => false ) +
$metadata );
1570 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1571 'provider' => $provider,
1573 'userInfo' => $userInfo
1575 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1576 $this->assertTrue( $info->wasRemembered() );
1577 $this->assertSame( array(), $logger->getBuffer() );
1579 // forceHTTPS from session
1580 $this->store
->setSessionMeta( $id, $metadata );
1581 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1582 'provider' => $provider,
1584 'userInfo' => $userInfo
1586 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1587 $this->assertFalse( $info->forceHTTPS() );
1588 $this->assertSame( array(), $logger->getBuffer() );
1590 $this->store
->setSessionMeta( $id, array( 'forceHTTPS' => true ) +
$metadata );
1591 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1592 'provider' => $provider,
1594 'userInfo' => $userInfo
1596 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1597 $this->assertTrue( $info->forceHTTPS() );
1598 $this->assertSame( array(), $logger->getBuffer() );
1600 $this->store
->setSessionMeta( $id, array( 'forceHTTPS' => false ) +
$metadata );
1601 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1602 'provider' => $provider,
1604 'userInfo' => $userInfo,
1605 'forceHTTPS' => true
1607 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1608 $this->assertTrue( $info->forceHTTPS() );
1609 $this->assertSame( array(), $logger->getBuffer() );
1611 // "Persist" flag from session
1612 $this->store
->setSessionMeta( $id, $metadata );
1613 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1614 'provider' => $provider,
1616 'userInfo' => $userInfo
1618 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1619 $this->assertFalse( $info->wasPersisted() );
1620 $this->assertSame( array(), $logger->getBuffer() );
1622 $this->store
->setSessionMeta( $id, array( 'persisted' => true ) +
$metadata );
1623 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1624 'provider' => $provider,
1626 'userInfo' => $userInfo
1628 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1629 $this->assertTrue( $info->wasPersisted() );
1630 $this->assertSame( array(), $logger->getBuffer() );
1632 $this->store
->setSessionMeta( $id, array( 'persisted' => false ) +
$metadata );
1633 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1634 'provider' => $provider,
1636 'userInfo' => $userInfo,
1639 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1640 $this->assertTrue( $info->wasPersisted() );
1641 $this->assertSame( array(), $logger->getBuffer() );
1643 // Provider refreshSessionInfo() returning false
1644 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1645 'provider' => $provider3,
1647 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1648 $this->assertSame( array(), $logger->getBuffer() );
1652 $data = array( 'foo' => 1 );
1653 $this->store
->setSession( $id, array( 'metadata' => $metadata, 'data' => $data ) );
1654 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array(
1655 'provider' => $provider,
1657 'userInfo' => $userInfo
1659 $this->mergeMwGlobalArrayValue( 'wgHooks', array(
1660 'SessionCheckInfo' => array( function ( &$reason, $i, $r, $m, $d ) use (
1661 $info, $metadata, $data, $request, &$called
1663 $this->assertSame( $info->getId(), $i->getId() );
1664 $this->assertSame( $info->getProvider(), $i->getProvider() );
1665 $this->assertSame( $info->getUserInfo(), $i->getUserInfo() );
1666 $this->assertSame( $request, $r );
1667 $this->assertEquals( $metadata, $m );
1668 $this->assertEquals( $data, $d );
1673 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1674 $this->assertTrue( $called );
1675 $this->assertSame( array(
1676 array( LogLevel
::WARNING
, 'Session "{session}": Hook aborted' ),
1677 ), $logger->getBuffer() );
1678 $logger->clearBuffer();
1682 * @dataProvider provideCheckIpLimits
1684 public function testCheckIpLimits( $ip, $sessionData, $userData, $logLevel1, $logLevel2 ) {
1685 $this->setMwGlobals( array(
1686 'wgSuspiciousIpPerSessionLimit' => 5,
1687 'wgSuspiciousIpPerUserLimit' => 10,
1688 'wgSuspiciousIpExpiry' => 600,
1689 'wgSquidServers' => array( '11.22.33.44' ),
1691 $manager = new SessionManager();
1692 $logger = $this->getMock( '\Psr\Log\LoggerInterface' );
1693 $this->setLogger( 'session-ip', $logger );
1694 $request = new \
FauxRequest();
1695 $request->setIP( $ip );
1697 $session = $manager->getSessionForRequest( $request );
1698 /** @var SessionBackend $backend */
1699 $backend = \TestingAccessWrapper
::newFromObject( $session )->backend
;
1700 $data = &$backend->getData();
1701 $data = array( 'SessionManager-ip' => $sessionData );
1702 $backend->setUser( User
::newFromName( 'UTSysop' ) );
1703 $manager = \TestingAccessWrapper
::newFromObject( $manager );
1704 $manager->store
->set( 'SessionManager-ip:' . md5( 'UTSysop' ), $userData );
1706 $logger->expects( $this->exactly( isset( $logLevel1 ) +
isset( $logLevel2 ) ) )->method( 'log' );
1708 $logger->expects( $this->at( 0 ) )->method( 'log' )->with( $logLevel1,
1709 'Same session used from {count} IPs', $this->isType( 'array' ) );
1712 $logger->expects( $this->at( isset( $logLevel1 ) ) )->method( 'log' )->with( $logLevel2,
1713 'Same user had sessions from {count} IPs', $this->isType( 'array' ) );
1716 $manager->checkIpLimits( $session );
1719 public function provideCheckIpLimits() {
1720 $future = time() +
1000;
1721 $past = time() - 1000;
1723 // DEBUG log for first new IP
1724 array( '1.2.3.4', array(), array(), LogLevel
::DEBUG
, LogLevel
::DEBUG
),
1725 // no log for same IP
1726 array( '1.2.3.4', array( '1.2.3.4' => $future ), array( '1.2.3.4' => $future ),
1728 array( '1.2.3.4', array(), array( '1.2.3.4' => $future ),
1729 LogLevel
::DEBUG
, null ),
1730 // INFO log for second new IP
1731 array( '1.2.3.4', array( '10.20.30.40' => $future ), array( '10.20.30.40' => $future ),
1732 LogLevel
::INFO
, LogLevel
::INFO
),
1733 // WARNING above $wgSuspiciousIpPerSessionLimit
1734 array( '1.2.3.4', array_fill_keys( range( 1, 5 ), $future ),
1735 array_fill_keys( range( 1, 5 ), $future ), LogLevel
::WARNING
, LogLevel
::INFO
),
1736 // WARNING above $wgSuspiciousIpPerUserLimit
1738 array( '1.2.3.4', array_fill_keys( range( 1, 2 ), $future ),
1739 array_fill_keys( range( 1, 12 ), $future ), LogLevel
::INFO
, LogLevel
::WARNING
),
1740 // expired keys ignored
1741 array( '1.2.3.4', array( '1.2.3.4' => $past ), array( '1.2.3.4' => $past ),
1742 LogLevel
::DEBUG
, LogLevel
::DEBUG
),
1743 array( '1.2.3.4', array_fill_keys( range( 1, 5 ), $past ),
1744 array_fill_keys( range( 1, 5 ), $past ), LogLevel
::DEBUG
, LogLevel
::DEBUG
),
1745 // special IPs are ignored
1746 array( '127.0.0.1', array(), array(), null, null ),
1747 array( '11.22.33.44', array(), array(), null, null ),