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