Merge "Log multiple IPs using the same session or the same user account"
[lhc/web/wiklou.git] / tests / phpunit / includes / session / SessionManagerTest.php
1 <?php
2
3 namespace MediaWiki\Session;
4
5 use AuthPlugin;
6 use MediaWiki\Logger\LoggerFactory;
7 use MediaWikiTestCase;
8 use Psr\Log\LogLevel;
9 use User;
10
11 /**
12 * @group Session
13 * @group Database
14 * @covers MediaWiki\Session\SessionManager
15 */
16 class SessionManagerTest extends MediaWikiTestCase {
17
18 protected $config, $logger, $store;
19
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' ),
28 )
29 ) );
30 $this->logger = new \TestLogger( false, function ( $m ) {
31 return substr( $m, 0, 15 ) === 'SessionBackend ' ? null : $m;
32 } );
33 $this->store = new TestBagOStuff();
34
35 return new SessionManager( array(
36 'config' => $this->config,
37 'logger' => $this->logger,
38 'store' => $this->store,
39 ) );
40 }
41
42 protected function objectCacheDef( $object ) {
43 return array( 'factory' => function () use ( $object ) {
44 return $object;
45 } );
46 }
47
48 public function testSingleton() {
49 $reset = TestUtils::setSessionManagerSingleton( null );
50
51 $singleton = SessionManager::singleton();
52 $this->assertInstanceOf( 'MediaWiki\\Session\\SessionManager', $singleton );
53 $this->assertSame( $singleton, SessionManager::singleton() );
54 }
55
56 public function testGetGlobalSession() {
57 $context = \RequestContext::getMain();
58
59 if ( !PHPSessionHandler::isInstalled() ) {
60 PHPSessionHandler::install( SessionManager::singleton() );
61 }
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();
69 }
70 $handler->enable = $oldEnable;
71 } );
72 $reset[] = TestUtils::setSessionManagerSingleton( $this->getManager() );
73
74 $handler->enable = true;
75 $request = new \FauxRequest();
76 $context->setRequest( $request );
77 $id = $request->getSession()->getId();
78
79 session_id( '' );
80 $session = SessionManager::getGlobalSession();
81 $this->assertSame( $id, $session->getId() );
82
83 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
84 $session = SessionManager::getGlobalSession();
85 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $session->getId() );
86 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $request->getSession()->getId() );
87
88 session_write_close();
89 $handler->enable = false;
90 $request = new \FauxRequest();
91 $context->setRequest( $request );
92 $id = $request->getSession()->getId();
93
94 session_id( '' );
95 $session = SessionManager::getGlobalSession();
96 $this->assertSame( $id, $session->getId() );
97
98 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
99 $session = SessionManager::getGlobalSession();
100 $this->assertSame( $id, $session->getId() );
101 $this->assertSame( $id, $request->getSession()->getId() );
102 }
103
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 );
109
110 $manager = \TestingAccessWrapper::newFromObject( new SessionManager() );
111 $this->assertSame( \RequestContext::getMain()->getConfig(), $manager->config );
112
113 $manager = \TestingAccessWrapper::newFromObject( new SessionManager( array(
114 'config' => $this->config,
115 ) ) );
116 $this->assertSame( \ObjectCache::$instances['testSessionStore'], $manager->store );
117
118 foreach ( array(
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 ) {
123 try {
124 new SessionManager( array( $key => new \stdClass ) );
125 $this->fail( 'Expected exception not thrown' );
126 } catch ( \InvalidArgumentException $ex ) {
127 $this->assertSame( $error, $ex->getMessage() );
128 }
129 }
130 }
131
132 public function testGetSessionForRequest() {
133 $manager = $this->getManager();
134 $request = new \FauxRequest();
135
136 $id1 = '';
137 $id2 = '';
138 $idEmpty = 'empty-session-------------------';
139
140 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
141 ->setMethods(
142 array( 'provideSessionInfo', 'newSessionInfo', '__toString', 'describe' )
143 );
144
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;
150 } ) );
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,
155 'id' => $idEmpty,
156 'persisted' => true,
157 'idIsSafe' => true,
158 ) );
159 } ) );
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' ) );
164
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;
170 } ) );
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' ) );
175
176 $this->config->set( 'SessionProviders', array(
177 $this->objectCacheDef( $provider1 ),
178 $this->objectCacheDef( $provider2 ),
179 ) );
180
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() );
187
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() ),
192 'persisted' => true,
193 'idIsSafe' => true,
194 ) );
195 $request->info2 = new SessionInfo( SessionInfo::MIN_PRIORITY + 2, array(
196 'provider' => $provider2,
197 'id' => ( $id2 = $manager->generateSessionId() ),
198 'persisted' => true,
199 'idIsSafe' => true,
200 ) );
201 $session = $manager->getSessionForRequest( $request );
202 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
203 $this->assertSame( $id2, $session->getId() );
204
205 $request->info1 = new SessionInfo( SessionInfo::MIN_PRIORITY + 2, array(
206 'provider' => $provider1,
207 'id' => ( $id1 = $manager->generateSessionId() ),
208 'persisted' => true,
209 'idIsSafe' => true,
210 ) );
211 $request->info2 = new SessionInfo( SessionInfo::MIN_PRIORITY + 1, array(
212 'provider' => $provider2,
213 'id' => ( $id2 = $manager->generateSessionId() ),
214 'persisted' => true,
215 'idIsSafe' => true,
216 ) );
217 $session = $manager->getSessionForRequest( $request );
218 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
219 $this->assertSame( $id1, $session->getId() );
220
221 // Tied priorities
222 $request->info1 = new SessionInfo( SessionInfo::MAX_PRIORITY, array(
223 'provider' => $provider1,
224 'id' => ( $id1 = $manager->generateSessionId() ),
225 'persisted' => true,
226 'userInfo' => UserInfo::newAnonymous(),
227 'idIsSafe' => true,
228 ) );
229 $request->info2 = new SessionInfo( SessionInfo::MAX_PRIORITY, array(
230 'provider' => $provider2,
231 'id' => ( $id2 = $manager->generateSessionId() ),
232 'persisted' => true,
233 'userInfo' => UserInfo::newAnonymous(),
234 'idIsSafe' => true,
235 ) );
236 try {
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: ',
242 $ex->getMessage()
243 );
244 $this->assertCount( 2, $ex->sessionInfos );
245 $this->assertContains( $request->info1, $ex->sessionInfos );
246 $this->assertContains( $request->info2, $ex->sessionInfos );
247 }
248
249 // Bad provider
250 $request->info1 = new SessionInfo( SessionInfo::MAX_PRIORITY, array(
251 'provider' => $provider2,
252 'id' => ( $id1 = $manager->generateSessionId() ),
253 'persisted' => true,
254 'idIsSafe' => true,
255 ) );
256 $request->info2 = null;
257 try {
258 $manager->getSessionForRequest( $request );
259 $this->fail( 'Expcected exception not thrown' );
260 } catch ( \UnexpectedValueException $ex ) {
261 $this->assertSame(
262 'Provider1 returned session info for a different provider: ' . $request->info1,
263 $ex->getMessage()
264 );
265 }
266
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() ),
272 'persisted' => true,
273 'userInfo' => UserInfo::newFromName( 'UTSysop', false ),
274 'idIsSafe' => true,
275 ) );
276 $request->info2 = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
277 'provider' => $provider2,
278 'id' => ( $id2 = $manager->generateSessionId() ),
279 'persisted' => true,
280 'idIsSafe' => true,
281 ) );
282 $session = $manager->getSessionForRequest( $request );
283 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
284 $this->assertSame( $id2, $session->getId() );
285 $this->logger->setCollect( false );
286
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 ),
293 'idIsSafe' => true,
294 ) );
295 $request->info2 = null;
296 $session = $manager->getSessionForRequest( $request );
297 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
298 $this->assertSame( $id1, $session->getId() );
299 $session->persist();
300 $this->assertTrue( $session->isPersistent(), 'sanity check' );
301 }
302
303 public function testGetSessionById() {
304 $manager = $this->getManager();
305 try {
306 $manager->getSessionById( 'bad' );
307 $this->fail( 'Expected exception not thrown' );
308 } catch ( \InvalidArgumentException $ex ) {
309 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
310 }
311
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() );
317
318 $id = $manager->generateSessionId();
319 $this->assertNull( $manager->getSessionById( $id, false ) );
320
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',
327 ) ) );
328
329 $this->assertNull( $manager->getSessionById( $id, true ) );
330 $this->assertNull( $manager->getSessionById( $id, false ) );
331 $this->logger->setCollect( false );
332
333 // Known session ID
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() );
338 }
339
340 public function testGetEmptySession() {
341 $manager = $this->getManager();
342 $pmanager = \TestingAccessWrapper::newFromObject( $manager );
343 $request = new \FauxRequest();
344
345 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
346 ->setMethods( array( 'provideSessionInfo', 'newSessionInfo', '__toString' ) );
347
348 $expectId = null;
349 $info1 = null;
350 $info2 = null;
351
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;
358 } ) )
359 ->will( $this->returnCallback( function () use ( &$info1 ) {
360 return $info1;
361 } ) );
362 $provider1->expects( $this->any() )->method( '__toString' )
363 ->will( $this->returnValue( 'MockProvider1' ) );
364
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;
371 } ) )
372 ->will( $this->returnCallback( function () use ( &$info2 ) {
373 return $info2;
374 } ) );
375 $provider1->expects( $this->any() )->method( '__toString' )
376 ->will( $this->returnValue( 'MockProvider2' ) );
377
378 $this->config->set( 'SessionProviders', array(
379 $this->objectCacheDef( $provider1 ),
380 $this->objectCacheDef( $provider2 ),
381 ) );
382
383 // No info
384 $expectId = null;
385 $info1 = null;
386 $info2 = null;
387 try {
388 $manager->getEmptySession();
389 $this->fail( 'Expected exception not thrown' );
390 } catch ( \UnexpectedValueException $ex ) {
391 $this->assertSame(
392 'No provider could provide an empty session!',
393 $ex->getMessage()
394 );
395 }
396
397 // Info
398 $expectId = null;
399 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
400 'provider' => $provider1,
401 'id' => 'empty---------------------------',
402 'persisted' => true,
403 'idIsSafe' => true,
404 ) );
405 $info2 = null;
406 $session = $manager->getEmptySession();
407 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
408 $this->assertSame( 'empty---------------------------', $session->getId() );
409
410 // Info, explicitly
411 $expectId = 'expected------------------------';
412 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
413 'provider' => $provider1,
414 'id' => $expectId,
415 'persisted' => true,
416 'idIsSafe' => true,
417 ) );
418 $info2 = null;
419 $session = $pmanager->getEmptySessionInternal( null, $expectId );
420 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
421 $this->assertSame( $expectId, $session->getId() );
422
423 // Wrong ID
424 $expectId = 'expected-----------------------2';
425 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
426 'provider' => $provider1,
427 'id' => "un$expectId",
428 'persisted' => true,
429 'idIsSafe' => true,
430 ) );
431 $info2 = null;
432 try {
433 $pmanager->getEmptySessionInternal( null, $expectId );
434 $this->fail( 'Expected exception not thrown' );
435 } catch ( \UnexpectedValueException $ex ) {
436 $this->assertSame(
437 'MockProvider1 returned empty session info with a wrong id: ' .
438 "un$expectId != $expectId",
439 $ex->getMessage()
440 );
441 }
442
443 // Unsafe ID
444 $expectId = 'expected-----------------------2';
445 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
446 'provider' => $provider1,
447 'id' => $expectId,
448 'persisted' => true,
449 ) );
450 $info2 = null;
451 try {
452 $pmanager->getEmptySessionInternal( null, $expectId );
453 $this->fail( 'Expected exception not thrown' );
454 } catch ( \UnexpectedValueException $ex ) {
455 $this->assertSame(
456 'MockProvider1 returned empty session info with id flagged unsafe',
457 $ex->getMessage()
458 );
459 }
460
461 // Wrong provider
462 $expectId = null;
463 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
464 'provider' => $provider2,
465 'id' => 'empty---------------------------',
466 'persisted' => true,
467 'idIsSafe' => true,
468 ) );
469 $info2 = null;
470 try {
471 $manager->getEmptySession();
472 $this->fail( 'Expected exception not thrown' );
473 } catch ( \UnexpectedValueException $ex ) {
474 $this->assertSame(
475 'MockProvider1 returned an empty session info for a different provider: ' . $info1,
476 $ex->getMessage()
477 );
478 }
479
480 // Highest priority wins
481 $expectId = null;
482 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY + 1, array(
483 'provider' => $provider1,
484 'id' => 'empty1--------------------------',
485 'persisted' => true,
486 'idIsSafe' => true,
487 ) );
488 $info2 = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
489 'provider' => $provider2,
490 'id' => 'empty2--------------------------',
491 'persisted' => true,
492 'idIsSafe' => true,
493 ) );
494 $session = $manager->getEmptySession();
495 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
496 $this->assertSame( 'empty1--------------------------', $session->getId() );
497
498 $expectId = null;
499 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY + 1, array(
500 'provider' => $provider1,
501 'id' => 'empty1--------------------------',
502 'persisted' => true,
503 'idIsSafe' => true,
504 ) );
505 $info2 = new SessionInfo( SessionInfo::MIN_PRIORITY + 2, array(
506 'provider' => $provider2,
507 'id' => 'empty2--------------------------',
508 'persisted' => true,
509 'idIsSafe' => true,
510 ) );
511 $session = $manager->getEmptySession();
512 $this->assertInstanceOf( 'MediaWiki\\Session\\Session', $session );
513 $this->assertSame( 'empty2--------------------------', $session->getId() );
514
515 // Tied priorities throw an exception
516 $expectId = null;
517 $info1 = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
518 'provider' => $provider1,
519 'id' => 'empty1--------------------------',
520 'persisted' => true,
521 'userInfo' => UserInfo::newAnonymous(),
522 'idIsSafe' => true,
523 ) );
524 $info2 = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
525 'provider' => $provider2,
526 'id' => 'empty2--------------------------',
527 'persisted' => true,
528 'userInfo' => UserInfo::newAnonymous(),
529 'idIsSafe' => true,
530 ) );
531 try {
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: ',
537 $ex->getMessage()
538 );
539 }
540
541 // Bad id
542 try {
543 $pmanager->getEmptySessionInternal( null, 'bad' );
544 $this->fail( 'Expected exception not thrown' );
545 } catch ( \InvalidArgumentException $ex ) {
546 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
547 }
548
549 // Session already exists
550 $expectId = 'expected-----------------------3';
551 $this->store->setSessionMeta( $expectId, array(
552 'provider' => 'MockProvider2',
553 'userId' => 0,
554 'userName' => null,
555 'userToken' => null,
556 ) );
557 try {
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() );
562 }
563 }
564
565 public function testGetVaryHeaders() {
566 $manager = $this->getManager();
567
568 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
569 ->setMethods( array( 'getVaryHeaders', '__toString' ) );
570
571 $provider1 = $providerBuilder->getMock();
572 $provider1->expects( $this->once() )->method( 'getVaryHeaders' )
573 ->will( $this->returnValue( array(
574 'Foo' => null,
575 'Bar' => array( 'X', 'Bar1' ),
576 'Quux' => null,
577 ) ) );
578 $provider1->expects( $this->any() )->method( '__toString' )
579 ->will( $this->returnValue( 'MockProvider1' ) );
580
581 $provider2 = $providerBuilder->getMock();
582 $provider2->expects( $this->once() )->method( 'getVaryHeaders' )
583 ->will( $this->returnValue( array(
584 'Baz' => null,
585 'Bar' => array( 'X', 'Bar2' ),
586 'Quux' => array( 'Quux' ),
587 ) ) );
588 $provider2->expects( $this->any() )->method( '__toString' )
589 ->will( $this->returnValue( 'MockProvider2' ) );
590
591 $this->config->set( 'SessionProviders', array(
592 $this->objectCacheDef( $provider1 ),
593 $this->objectCacheDef( $provider2 ),
594 ) );
595
596 $expect = array(
597 'Foo' => array(),
598 'Bar' => array( 'X', 'Bar1', 3 => 'Bar2' ),
599 'Quux' => array( 'Quux' ),
600 'Baz' => array(),
601 );
602
603 $this->assertEquals( $expect, $manager->getVaryHeaders() );
604
605 // Again, to ensure it's cached
606 $this->assertEquals( $expect, $manager->getVaryHeaders() );
607 }
608
609 public function testGetVaryCookies() {
610 $manager = $this->getManager();
611
612 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
613 ->setMethods( array( 'getVaryCookies', '__toString' ) );
614
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' ) );
620
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' ) );
626
627 $this->config->set( 'SessionProviders', array(
628 $this->objectCacheDef( $provider1 ),
629 $this->objectCacheDef( $provider2 ),
630 ) );
631
632 $expect = array( 'Foo', 'Bar', 'Baz' );
633
634 $this->assertEquals( $expect, $manager->getVaryCookies() );
635
636 // Again, to ensure it's cached
637 $this->assertEquals( $expect, $manager->getVaryCookies() );
638 }
639
640 public function testGetProviders() {
641 $realManager = $this->getManager();
642 $manager = \TestingAccessWrapper::newFromObject( $realManager );
643
644 $this->config->set( 'SessionProviders', array(
645 array( 'class' => 'DummySessionProvider' ),
646 ) );
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() );
653
654 $this->config->set( 'SessionProviders', array(
655 array( 'class' => 'DummySessionProvider' ),
656 array( 'class' => 'DummySessionProvider' ),
657 ) );
658 $manager->sessionProviders = null;
659 try {
660 $manager->getProviders();
661 $this->fail( 'Expected exception not thrown' );
662 } catch ( \UnexpectedValueException $ex ) {
663 $this->assertSame(
664 'Duplicate provider name "DummySessionProvider"',
665 $ex->getMessage()
666 );
667 }
668 }
669
670 public function testShutdown() {
671 $manager = \TestingAccessWrapper::newFromObject( $this->getManager() );
672 $manager->setLogger( new \Psr\Log\NullLogger() );
673
674 $mock = $this->getMock( 'stdClass', array( 'save' ) );
675 $mock->expects( $this->once() )->method( 'save' );
676
677 $manager->allSessionBackends = array( $mock );
678 $manager->shutdown();
679 }
680
681 public function testGetSessionFromInfo() {
682 $manager = \TestingAccessWrapper::newFromObject( $this->getManager() );
683 $request = new \FauxRequest();
684
685 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
686
687 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
688 'provider' => $manager->getProvider( 'DummySessionProvider' ),
689 'id' => $id,
690 'persisted' => true,
691 'userInfo' => UserInfo::newFromName( 'UTSysop', true ),
692 'idIsSafe' => true,
693 ) );
694 \TestingAccessWrapper::newFromObject( $info )->idIsSafe = true;
695 $session1 = \TestingAccessWrapper::newFromObject(
696 $manager->getSessionFromInfo( $info, $request )
697 );
698 $session2 = \TestingAccessWrapper::newFromObject(
699 $manager->getSessionFromInfo( $info, $request )
700 );
701
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() );
706
707 \TestingAccessWrapper::newFromObject( $info )->idIsSafe = false;
708 $session3 = $manager->getSessionFromInfo( $info, $request );
709 $this->assertNotSame( $id, $session3->getId() );
710 }
711
712 public function testBackendRegistration() {
713 $manager = $this->getManager();
714
715 $session = $manager->getSessionForRequest( new \FauxRequest );
716 $backend = \TestingAccessWrapper::newFromObject( $session )->backend;
717 $sessionId = $session->getSessionId();
718 $id = (string)$sessionId;
719
720 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
721
722 $manager->changeBackendId( $backend );
723 $this->assertSame( $sessionId, $session->getSessionId() );
724 $this->assertNotEquals( $id, (string)$sessionId );
725 $id = (string)$sessionId;
726
727 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
728
729 // Destruction of the session here causes the backend to be deregistered
730 $session = null;
731
732 try {
733 $manager->changeBackendId( $backend );
734 $this->fail( 'Expected exception not thrown' );
735 } catch ( \InvalidArgumentException $ex ) {
736 $this->assertSame(
737 'Backend was not registered with this SessionManager', $ex->getMessage()
738 );
739 }
740
741 try {
742 $manager->deregisterSessionBackend( $backend );
743 $this->fail( 'Expected exception not thrown' );
744 } catch ( \InvalidArgumentException $ex ) {
745 $this->assertSame(
746 'Backend was not registered with this SessionManager', $ex->getMessage()
747 );
748 }
749
750 $session = $manager->getSessionById( $id, true );
751 $this->assertSame( $sessionId, $session->getSessionId() );
752 }
753
754 public function testGenerateSessionId() {
755 $manager = $this->getManager();
756
757 $id = $manager->generateSessionId();
758 $this->assertTrue( SessionManager::validateSessionId( $id ), "Generated ID: $id" );
759 }
760
761 public function testAutoCreateUser() {
762 global $wgGroupPermissions;
763
764 \ObjectCache::$instances[__METHOD__] = new TestBagOStuff();
765 $this->setMwGlobals( array( 'wgMainCacheType' => __METHOD__ ) );
766 $this->setMWGlobals( array(
767 'wgAuth' => new AuthPlugin,
768 ) );
769
770 $this->stashMwGlobals( array( 'wgGroupPermissions' ) );
771 $wgGroupPermissions['*']['createaccount'] = true;
772 $wgGroupPermissions['*']['autocreateaccount'] = false;
773
774 // Replace the global singleton with one configured for testing
775 $manager = $this->getManager();
776 $reset = TestUtils::setSessionManagerSingleton( $manager );
777
778 $logger = new \TestLogger( true, function ( $m ) {
779 if ( substr( $m, 0, 15 ) === 'SessionBackend ' ) {
780 // Don't care.
781 return null;
782 }
783 $m = str_replace( 'MediaWiki\Session\SessionManager::autoCreateUser: ', '', $m );
784 return $m;
785 } );
786 $manager->setLogger( $logger );
787
788 $session = SessionManager::getGlobalSession();
789
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();
798
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() );
805 $this->assertEquals(
806 $user->getId(), User::idFromName( 'UTSessionAutoCreate1', User::READ_LATEST )
807 );
808 $this->assertSame( array(
809 array( LogLevel::INFO, 'creating new user ({username}) - from: {url}' ),
810 ), $logger->getBuffer() );
811 $logger->clearBuffer();
812
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 ) );
821 $session->clear();
822 $this->assertSame( array(
823 array(
824 LogLevel::DEBUG,
825 'user is blocked from this wiki, blacklisting',
826 ),
827 ), $logger->getBuffer() );
828 $logger->clearBuffer();
829
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() );
838 $this->assertEquals(
839 $user->getId(), User::idFromName( 'UTSessionAutoCreate2', User::READ_LATEST )
840 );
841 $this->assertSame( array(
842 array( LogLevel::INFO, 'creating new user ({username}) - from: {url}' ),
843 ), $logger->getBuffer() );
844 $logger->clearBuffer();
845
846 // Test account-creation block
847 $anon = new User;
848 $block = new \Block( array(
849 'address' => $anon->getName(),
850 'user' => $id,
851 'reason' => __METHOD__,
852 'expiry' => time() + 100500,
853 'createAccount' => true,
854 ) );
855 $block->insert();
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 );
864 $session->clear();
865 $this->assertSame( array(
866 array( LogLevel::DEBUG, 'user is blocked from this wiki, blacklisting' ),
867 ), $logger->getBuffer() );
868 $logger->clearBuffer();
869
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() );
876 $this->assertEquals(
877 $user->getId(), User::idFromName( 'UTSessionAutoCreate3', User::READ_LATEST )
878 );
879 $this->assertSame( array(
880 array( LogLevel::INFO, 'creating new user ({username}) - from: {url}' ),
881 ), $logger->getBuffer() );
882 $logger->clearBuffer();
883
884 // Test prevention by AuthPlugin
885 global $wgAuth;
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,
892 ) );
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,
900 ) );
901 $session->clear();
902 $this->assertSame( array(
903 array( LogLevel::DEBUG, 'denied by AuthPlugin' ),
904 ), $logger->getBuffer() );
905 $logger->clearBuffer();
906
907 // Test prevention by wfReadOnly()
908 $this->setMwGlobals( array(
909 'wgReadOnly' => 'Because',
910 ) );
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,
918 ) );
919 $session->clear();
920 $this->assertSame( array(
921 array( LogLevel::DEBUG, 'denied by wfReadOnly()' ),
922 ), $logger->getBuffer() );
923 $logger->clearBuffer();
924
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 ) );
932 $session->clear();
933 $this->assertSame( array(
934 array( LogLevel::DEBUG, 'blacklisted in session (test)' ),
935 ), $logger->getBuffer() );
936 $logger->clearBuffer();
937
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 ) );
944 $session->clear();
945 $this->assertSame( array(
946 array( LogLevel::DEBUG, 'Invalid username, blacklisting' ),
947 ), $logger->getBuffer() );
948 $logger->clearBuffer();
949
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 ) {
954 $msg = 'No way!';
955 return false;
956 } ) );
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() ) );
964 $session->clear();
965 $this->assertSame( array(
966 array( LogLevel::DEBUG, 'denied by hook: No way!' ),
967 ), $logger->getBuffer() );
968 $logger->clearBuffer();
969
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' );
975 } ) );
976 $this->mergeMwGlobalArrayValue( 'wgHooks', array( 'AbortAutoAccount' => array( $mock ) ) );
977 try {
978 $user = User::newFromName( 'UTDoesNotExist' );
979 $manager->autoCreateUser( $user );
980 $this->fail( 'Expected exception not thrown' );
981 } catch ( \UnexpectedValueException $ex ) {
982 $this->assertSame(
983 'AbortAutoAccount hook tried to change the user name',
984 $ex->getMessage()
985 );
986 }
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() ) );
993 $session->clear();
994 $this->assertSame( array(), $logger->getBuffer() );
995 $logger->clearBuffer();
996
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 );
1007 $session->clear();
1008 $this->assertSame( array(
1009 array( LogLevel::DEBUG, 'denied by prior creation attempt failures' ),
1010 ), $logger->getBuffer() );
1011 $logger->clearBuffer();
1012
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 )
1019 );
1020 return true;
1021 } );
1022 $mock = $this->getMock( 'stdClass',
1023 array( 'onAuthPluginAutoCreate', 'onLocalUserCreated' ) );
1024 $mock->expects( $this->once() )->method( 'onAuthPluginAutoCreate' )
1025 ->with( $cb );
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 ),
1031 ) );
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(
1038 $user->getId(),
1039 User::idFromName( 'UTSessionAutoCreate4', User::READ_LATEST )
1040 );
1041 $this->mergeMwGlobalArrayValue( 'wgHooks', array(
1042 'AuthPluginAutoCreate' => array(),
1043 'LocalUserCreated' => array(),
1044 ) );
1045 $this->assertSame( array(
1046 array( LogLevel::INFO, 'creating new user ({username}) - from: {url}' ),
1047 ), $logger->getBuffer() );
1048 $logger->clearBuffer();
1049 }
1050
1051 public function onAbortAutoAccount( User $user, &$msg ) {
1052 }
1053
1054 public function testPreventSessionsForUser() {
1055 $manager = $this->getManager();
1056
1057 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
1058 ->setMethods( array( 'preventSessionsForUser', '__toString' ) );
1059
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' ) );
1065
1066 $this->config->set( 'SessionProviders', array(
1067 $this->objectCacheDef( $provider1 ),
1068 ) );
1069
1070 $this->assertFalse( $manager->isUserSessionPrevented( 'UTSysop' ) );
1071 $manager->preventSessionsForUser( 'UTSysop' );
1072 $this->assertTrue( $manager->isUserSessionPrevented( 'UTSysop' ) );
1073 }
1074
1075 public function testLoadSessionInfoFromStore() {
1076 $manager = $this->getManager();
1077 $logger = new \TestLogger( true );
1078 $manager->setLogger( $logger );
1079 $request = new \FauxRequest();
1080
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 ) );
1087 };
1088
1089 $userInfo = UserInfo::newFromName( 'UTSysop', true );
1090 $unverifiedUserInfo = UserInfo::newFromName( 'UTSysop', false );
1091
1092 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
1093 $metadata = array(
1094 'userId' => $userInfo->getId(),
1095 'userName' => $userInfo->getName(),
1096 'userToken' => $userInfo->getToken( true ),
1097 'provider' => 'Mock',
1098 );
1099
1100 $builder = $this->getMockBuilder( 'MediaWiki\\Session\\SessionProvider' )
1101 ->setMethods( array( '__toString', 'mergeMetadata', 'refreshSessionInfo' ) );
1102
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!' );
1117 }
1118 return array( 'Merged' );
1119 } ) );
1120
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;
1132 return true;
1133 } ) );
1134
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' ) );
1145
1146 \TestingAccessWrapper::newFromObject( $manager )->sessionProviders = array(
1147 (string)$provider => $provider,
1148 (string)$provider2 => $provider2,
1149 (string)$provider3 => $provider3,
1150 );
1151
1152 // No metadata, basic usage
1153 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1154 'provider' => $provider,
1155 'id' => $id,
1156 'userInfo' => $userInfo
1157 ) );
1158 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1159 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1160 $this->assertFalse( $info->isIdSafe() );
1161 $this->assertSame( array(), $logger->getBuffer() );
1162
1163 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1164 'provider' => $provider,
1165 'userInfo' => $userInfo
1166 ) );
1167 $this->assertTrue( $info->isIdSafe(), 'sanity check' );
1168 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1169 $this->assertTrue( $info->isIdSafe() );
1170 $this->assertSame( array(), $logger->getBuffer() );
1171
1172 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1173 'provider' => $provider2,
1174 'id' => $id,
1175 'userInfo' => $userInfo
1176 ) );
1177 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1178 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1179 $this->assertTrue( $info->isIdSafe() );
1180 $this->assertSame( array(), $logger->getBuffer() );
1181
1182 // Unverified user, no metadata
1183 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1184 'provider' => $provider,
1185 'id' => $id,
1186 'userInfo' => $unverifiedUserInfo
1187 ) );
1188 $this->assertSame( $unverifiedUserInfo, $info->getUserInfo() );
1189 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1190 $this->assertSame( array(
1191 array(
1192 LogLevel::WARNING,
1193 'Session "{session}": Unverified user provided and no metadata to auth it',
1194 )
1195 ), $logger->getBuffer() );
1196 $logger->clearBuffer();
1197
1198 // No metadata, missing data
1199 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1200 'id' => $id,
1201 'userInfo' => $userInfo
1202 ) );
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();
1208
1209 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1210 'provider' => $provider,
1211 'id' => $id,
1212 ) );
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() );
1220
1221 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1222 'provider' => $provider2,
1223 'id' => $id,
1224 ) );
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();
1231
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();
1239
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();
1246
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();
1254
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();
1261
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();
1268
1269 foreach ( $metadata as $key => $dummy ) {
1270 $tmp = $metadata;
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();
1278 }
1279
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,
1284 'id' => $id,
1285 'userInfo' => $userInfo
1286 ) );
1287 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1288 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1289 $this->assertTrue( $info->isIdSafe() );
1290 $this->assertSame( array(), $logger->getBuffer() );
1291
1292 // Mismatched provider
1293 $this->store->setSessionMeta( $id, array( 'provider' => 'Bad' ) + $metadata );
1294 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1295 'provider' => $provider,
1296 'id' => $id,
1297 'userInfo' => $userInfo
1298 ) );
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();
1304
1305 // Unknown provider
1306 $this->store->setSessionMeta( $id, array( 'provider' => 'Bad' ) + $metadata );
1307 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1308 'id' => $id,
1309 'userInfo' => $userInfo
1310 ) );
1311 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1312 $this->assertSame( array(
1313 array( LogLevel::WARNING, 'Session "{session}": Unknown provider Bad' ),
1314 ), $logger->getBuffer() );
1315 $logger->clearBuffer();
1316
1317 // Fill in provider
1318 $this->store->setSessionMeta( $id, $metadata );
1319 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1320 'id' => $id,
1321 'userInfo' => $userInfo
1322 ) );
1323 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1324 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1325 $this->assertTrue( $info->isIdSafe() );
1326 $this->assertSame( array(), $logger->getBuffer() );
1327
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,
1332 'id' => $id,
1333 ) );
1334 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1335 $this->assertSame( array(
1336 array( LogLevel::ERROR, 'Session "{session}": {exception}' ),
1337 ), $logger->getBuffer() );
1338 $logger->clearBuffer();
1339
1340 $this->store->setSessionMeta(
1341 $id, array( 'userId' => 0, 'userName' => '<X>', 'userToken' => null ) + $metadata
1342 );
1343 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1344 'provider' => $provider,
1345 'id' => $id,
1346 ) );
1347 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1348 $this->assertSame( array(
1349 array( LogLevel::ERROR, 'Session "{session}": {exception}', ),
1350 ), $logger->getBuffer() );
1351 $logger->clearBuffer();
1352
1353 // Mismatched user by ID
1354 $this->store->setSessionMeta(
1355 $id, array( 'userId' => $userInfo->getId() + 1, 'userToken' => null ) + $metadata
1356 );
1357 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1358 'provider' => $provider,
1359 'id' => $id,
1360 'userInfo' => $userInfo
1361 ) );
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();
1367
1368 // Mismatched user by name
1369 $this->store->setSessionMeta(
1370 $id, array( 'userId' => 0, 'userName' => 'X', 'userToken' => null ) + $metadata
1371 );
1372 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1373 'provider' => $provider,
1374 'id' => $id,
1375 'userInfo' => $userInfo
1376 ) );
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();
1382
1383 // ID matches, name doesn't
1384 $this->store->setSessionMeta(
1385 $id, array( 'userId' => $userInfo->getId(), 'userName' => 'X', 'userToken' => null ) + $metadata
1386 );
1387 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1388 'provider' => $provider,
1389 'id' => $id,
1390 'userInfo' => $userInfo
1391 ) );
1392 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1393 $this->assertSame( array(
1394 array(
1395 LogLevel::WARNING,
1396 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}'
1397 ),
1398 ), $logger->getBuffer() );
1399 $logger->clearBuffer();
1400
1401 // Mismatched anon user
1402 $this->store->setSessionMeta(
1403 $id, array( 'userId' => 0, 'userName' => null, 'userToken' => null ) + $metadata
1404 );
1405 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1406 'provider' => $provider,
1407 'id' => $id,
1408 'userInfo' => $userInfo
1409 ) );
1410 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1411 $this->assertSame( array(
1412 array(
1413 LogLevel::WARNING,
1414 'Session "{session}": Metadata has an anonymous user, ' .
1415 'but a non-anon user was provided',
1416 ),
1417 ), $logger->getBuffer() );
1418 $logger->clearBuffer();
1419
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,
1424 'id' => $id,
1425 ) );
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() );
1431
1432 // Lookup user by name
1433 $this->store->setSessionMeta(
1434 $id, array( 'userId' => 0, 'userName' => 'UTSysop', 'userToken' => null ) + $metadata
1435 );
1436 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1437 'provider' => $provider,
1438 'id' => $id,
1439 ) );
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() );
1445
1446 // Lookup anonymous user
1447 $this->store->setSessionMeta(
1448 $id, array( 'userId' => 0, 'userName' => null, 'userToken' => null ) + $metadata
1449 );
1450 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1451 'provider' => $provider,
1452 'id' => $id,
1453 ) );
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() );
1459
1460 // Unverified user with metadata
1461 $this->store->setSessionMeta( $id, $metadata );
1462 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1463 'provider' => $provider,
1464 'id' => $id,
1465 'userInfo' => $unverifiedUserInfo
1466 ) );
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() );
1474
1475 // Unverified user with metadata
1476 $this->store->setSessionMeta( $id, $metadata );
1477 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1478 'provider' => $provider,
1479 'id' => $id,
1480 'userInfo' => $unverifiedUserInfo
1481 ) );
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() );
1489
1490 // Wrong token
1491 $this->store->setSessionMeta( $id, array( 'userToken' => 'Bad' ) + $metadata );
1492 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1493 'provider' => $provider,
1494 'id' => $id,
1495 'userInfo' => $userInfo
1496 ) );
1497 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1498 $this->assertSame( array(
1499 array( LogLevel::WARNING, 'Session "{session}": User token mismatch' ),
1500 ), $logger->getBuffer() );
1501 $logger->clearBuffer();
1502
1503 // Provider metadata
1504 $this->store->setSessionMeta( $id, array( 'provider' => 'Mock2' ) + $metadata );
1505 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1506 'provider' => $provider2,
1507 'id' => $id,
1508 'userInfo' => $userInfo,
1509 'metadata' => array( 'Info' ),
1510 ) );
1511 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1512 $this->assertSame( array( 'Info', 'changed' => true ), $info->getProviderMetadata() );
1513 $this->assertSame( array(), $logger->getBuffer() );
1514
1515 $this->store->setSessionMeta( $id, array( 'providerMetadata' => array( 'Saved' ) ) + $metadata );
1516 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1517 'provider' => $provider,
1518 'id' => $id,
1519 'userInfo' => $userInfo,
1520 ) );
1521 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1522 $this->assertSame( array( 'Saved' ), $info->getProviderMetadata() );
1523 $this->assertSame( array(), $logger->getBuffer() );
1524
1525 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1526 'provider' => $provider,
1527 'id' => $id,
1528 'userInfo' => $userInfo,
1529 'metadata' => array( 'Info' ),
1530 ) );
1531 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1532 $this->assertSame( array( 'Merged' ), $info->getProviderMetadata() );
1533 $this->assertSame( array(), $logger->getBuffer() );
1534
1535 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1536 'provider' => $provider,
1537 'id' => $id,
1538 'userInfo' => $userInfo,
1539 'metadata' => array( 'Throw' ),
1540 ) );
1541 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1542 $this->assertSame( array(
1543 array(
1544 LogLevel::WARNING,
1545 'Session "{session}": Metadata merge failed: {exception}',
1546 ),
1547 ), $logger->getBuffer() );
1548 $logger->clearBuffer();
1549
1550 // Remember from session
1551 $this->store->setSessionMeta( $id, $metadata );
1552 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1553 'provider' => $provider,
1554 'id' => $id,
1555 ) );
1556 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1557 $this->assertFalse( $info->wasRemembered() );
1558 $this->assertSame( array(), $logger->getBuffer() );
1559
1560 $this->store->setSessionMeta( $id, array( 'remember' => true ) + $metadata );
1561 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1562 'provider' => $provider,
1563 'id' => $id,
1564 ) );
1565 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1566 $this->assertTrue( $info->wasRemembered() );
1567 $this->assertSame( array(), $logger->getBuffer() );
1568
1569 $this->store->setSessionMeta( $id, array( 'remember' => false ) + $metadata );
1570 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1571 'provider' => $provider,
1572 'id' => $id,
1573 'userInfo' => $userInfo
1574 ) );
1575 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1576 $this->assertTrue( $info->wasRemembered() );
1577 $this->assertSame( array(), $logger->getBuffer() );
1578
1579 // forceHTTPS from session
1580 $this->store->setSessionMeta( $id, $metadata );
1581 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1582 'provider' => $provider,
1583 'id' => $id,
1584 'userInfo' => $userInfo
1585 ) );
1586 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1587 $this->assertFalse( $info->forceHTTPS() );
1588 $this->assertSame( array(), $logger->getBuffer() );
1589
1590 $this->store->setSessionMeta( $id, array( 'forceHTTPS' => true ) + $metadata );
1591 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1592 'provider' => $provider,
1593 'id' => $id,
1594 'userInfo' => $userInfo
1595 ) );
1596 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1597 $this->assertTrue( $info->forceHTTPS() );
1598 $this->assertSame( array(), $logger->getBuffer() );
1599
1600 $this->store->setSessionMeta( $id, array( 'forceHTTPS' => false ) + $metadata );
1601 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1602 'provider' => $provider,
1603 'id' => $id,
1604 'userInfo' => $userInfo,
1605 'forceHTTPS' => true
1606 ) );
1607 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1608 $this->assertTrue( $info->forceHTTPS() );
1609 $this->assertSame( array(), $logger->getBuffer() );
1610
1611 // "Persist" flag from session
1612 $this->store->setSessionMeta( $id, $metadata );
1613 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1614 'provider' => $provider,
1615 'id' => $id,
1616 'userInfo' => $userInfo
1617 ) );
1618 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1619 $this->assertFalse( $info->wasPersisted() );
1620 $this->assertSame( array(), $logger->getBuffer() );
1621
1622 $this->store->setSessionMeta( $id, array( 'persisted' => true ) + $metadata );
1623 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1624 'provider' => $provider,
1625 'id' => $id,
1626 'userInfo' => $userInfo
1627 ) );
1628 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1629 $this->assertTrue( $info->wasPersisted() );
1630 $this->assertSame( array(), $logger->getBuffer() );
1631
1632 $this->store->setSessionMeta( $id, array( 'persisted' => false ) + $metadata );
1633 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1634 'provider' => $provider,
1635 'id' => $id,
1636 'userInfo' => $userInfo,
1637 'persisted' => true
1638 ) );
1639 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1640 $this->assertTrue( $info->wasPersisted() );
1641 $this->assertSame( array(), $logger->getBuffer() );
1642
1643 // Provider refreshSessionInfo() returning false
1644 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, array(
1645 'provider' => $provider3,
1646 ) );
1647 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1648 $this->assertSame( array(), $logger->getBuffer() );
1649
1650 // Hook
1651 $called = false;
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,
1656 'id' => $id,
1657 'userInfo' => $userInfo
1658 ) );
1659 $this->mergeMwGlobalArrayValue( 'wgHooks', array(
1660 'SessionCheckInfo' => array( function ( &$reason, $i, $r, $m, $d ) use (
1661 $info, $metadata, $data, $request, &$called
1662 ) {
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 );
1669 $called = true;
1670 return false;
1671 } )
1672 ) );
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();
1679 }
1680
1681 /**
1682 * @dataProvider provideCheckIpLimits
1683 */
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' ),
1690 ) );
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 );
1696
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 );
1705
1706 $logger->expects( $this->exactly( isset( $logLevel1 ) + isset( $logLevel2 ) ) )->method( 'log' );
1707 if ( $logLevel1 ) {
1708 $logger->expects( $this->at( 0 ) )->method( 'log' )->with( $logLevel1,
1709 'Same session used from {count} IPs', $this->isType( 'array' ) );
1710 }
1711 if ( $logLevel2 ) {
1712 $logger->expects( $this->at( isset( $logLevel1 ) ) )->method( 'log' )->with( $logLevel2,
1713 'Same user had sessions from {count} IPs', $this->isType( 'array' ) );
1714 }
1715
1716 $manager->checkIpLimits( $session );
1717 }
1718
1719 public function provideCheckIpLimits() {
1720 $future = time() + 1000;
1721 $past = time() - 1000;
1722 return array(
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 ),
1727 null, null ),
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
1737
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 ),
1748 );
1749 }
1750 }