MediaWiki  1.28.0
CookieSessionProviderTest.php
Go to the documentation of this file.
1 <?php
2 
3 namespace MediaWiki\Session;
4 
6 use User;
8 
15 
16  private function getConfig() {
17  return new \HashConfig( [
18  'CookiePrefix' => 'CookiePrefix',
19  'CookiePath' => 'CookiePath',
20  'CookieDomain' => 'CookieDomain',
21  'CookieSecure' => true,
22  'CookieHttpOnly' => true,
23  'SessionName' => false,
24  'CookieExpiration' => 100,
25  'ExtendedLoginCookieExpiration' => 200,
26  ] );
27  }
28 
29  public function testConstructor() {
30  try {
32  $this->fail( 'Expected exception not thrown' );
33  } catch ( \InvalidArgumentException $ex ) {
34  $this->assertSame(
35  'MediaWiki\\Session\\CookieSessionProvider::__construct: priority must be specified',
36  $ex->getMessage()
37  );
38  }
39 
40  try {
41  new CookieSessionProvider( [ 'priority' => 'foo' ] );
42  $this->fail( 'Expected exception not thrown' );
43  } catch ( \InvalidArgumentException $ex ) {
44  $this->assertSame(
45  'MediaWiki\\Session\\CookieSessionProvider::__construct: Invalid priority',
46  $ex->getMessage()
47  );
48  }
49  try {
50  new CookieSessionProvider( [ 'priority' => SessionInfo::MIN_PRIORITY - 1 ] );
51  $this->fail( 'Expected exception not thrown' );
52  } catch ( \InvalidArgumentException $ex ) {
53  $this->assertSame(
54  'MediaWiki\\Session\\CookieSessionProvider::__construct: Invalid priority',
55  $ex->getMessage()
56  );
57  }
58  try {
59  new CookieSessionProvider( [ 'priority' => SessionInfo::MAX_PRIORITY + 1 ] );
60  $this->fail( 'Expected exception not thrown' );
61  } catch ( \InvalidArgumentException $ex ) {
62  $this->assertSame(
63  'MediaWiki\\Session\\CookieSessionProvider::__construct: Invalid priority',
64  $ex->getMessage()
65  );
66  }
67 
68  try {
69  new CookieSessionProvider( [ 'priority' => 1, 'cookieOptions' => null ] );
70  $this->fail( 'Expected exception not thrown' );
71  } catch ( \InvalidArgumentException $ex ) {
72  $this->assertSame(
73  'MediaWiki\\Session\\CookieSessionProvider::__construct: cookieOptions must be an array',
74  $ex->getMessage()
75  );
76  }
77 
78  $config = $this->getConfig();
80  new CookieSessionProvider( [ 'priority' => 1 ] )
81  );
82  $p->setLogger( new \TestLogger() );
83  $p->setConfig( $config );
84  $this->assertEquals( 1, $p->priority );
85  $this->assertEquals( [
86  'callUserSetCookiesHook' => false,
87  'sessionName' => 'CookiePrefix_session',
88  ], $p->params );
89  $this->assertEquals( [
90  'prefix' => 'CookiePrefix',
91  'path' => 'CookiePath',
92  'domain' => 'CookieDomain',
93  'secure' => true,
94  'httpOnly' => true,
95  ], $p->cookieOptions );
96 
97  $config->set( 'SessionName', 'SessionName' );
99  new CookieSessionProvider( [ 'priority' => 3 ] )
100  );
101  $p->setLogger( new \TestLogger() );
102  $p->setConfig( $config );
103  $this->assertEquals( 3, $p->priority );
104  $this->assertEquals( [
105  'callUserSetCookiesHook' => false,
106  'sessionName' => 'SessionName',
107  ], $p->params );
108  $this->assertEquals( [
109  'prefix' => 'CookiePrefix',
110  'path' => 'CookiePath',
111  'domain' => 'CookieDomain',
112  'secure' => true,
113  'httpOnly' => true,
114  ], $p->cookieOptions );
115 
117  'priority' => 10,
118  'callUserSetCookiesHook' => true,
119  'cookieOptions' => [
120  'prefix' => 'XPrefix',
121  'path' => 'XPath',
122  'domain' => 'XDomain',
123  'secure' => 'XSecure',
124  'httpOnly' => 'XHttpOnly',
125  ],
126  'sessionName' => 'XSession',
127  ] ) );
128  $p->setLogger( new \TestLogger() );
129  $p->setConfig( $config );
130  $this->assertEquals( 10, $p->priority );
131  $this->assertEquals( [
132  'callUserSetCookiesHook' => true,
133  'sessionName' => 'XSession',
134  ], $p->params );
135  $this->assertEquals( [
136  'prefix' => 'XPrefix',
137  'path' => 'XPath',
138  'domain' => 'XDomain',
139  'secure' => 'XSecure',
140  'httpOnly' => 'XHttpOnly',
141  ], $p->cookieOptions );
142  }
143 
144  public function testBasics() {
145  $provider = new CookieSessionProvider( [ 'priority' => 10 ] );
146 
147  $this->assertTrue( $provider->persistsSessionId() );
148  $this->assertTrue( $provider->canChangeUser() );
149 
150  $extendedCookies = [ 'UserID', 'UserName', 'Token' ];
151 
152  $this->assertEquals(
153  $extendedCookies,
154  \TestingAccessWrapper::newFromObject( $provider )->getExtendedLoginCookies(),
155  'List of extended cookies (subclasses can add values, but we\'re calling the core one here)'
156  );
157 
158  $msg = $provider->whyNoSession();
159  $this->assertInstanceOf( 'Message', $msg );
160  $this->assertSame( 'sessionprovider-nocookies', $msg->getKey() );
161  }
162 
163  public function testProvideSessionInfo() {
164  $params = [
165  'priority' => 20,
166  'sessionName' => 'session',
167  'cookieOptions' => [ 'prefix' => 'x' ],
168  ];
169  $provider = new CookieSessionProvider( $params );
170  $logger = new \TestLogger( true );
171  $provider->setLogger( $logger );
172  $provider->setConfig( $this->getConfig() );
173  $provider->setManager( new SessionManager() );
174 
175  $user = static::getTestSysop()->getUser();
176  $id = $user->getId();
177  $name = $user->getName();
178  $token = $user->getToken( true );
179 
180  $sessionId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
181 
182  // No data
183  $request = new \FauxRequest();
184  $info = $provider->provideSessionInfo( $request );
185  $this->assertNull( $info );
186  $this->assertSame( [], $logger->getBuffer() );
187  $logger->clearBuffer();
188 
189  // Session key only
190  $request = new \FauxRequest();
191  $request->setCookies( [
192  'session' => $sessionId,
193  ], '' );
194  $info = $provider->provideSessionInfo( $request );
195  $this->assertNotNull( $info );
196  $this->assertSame( $params['priority'], $info->getPriority() );
197  $this->assertSame( $sessionId, $info->getId() );
198  $this->assertNotNull( $info->getUserInfo() );
199  $this->assertSame( 0, $info->getUserInfo()->getId() );
200  $this->assertNull( $info->getUserInfo()->getName() );
201  $this->assertFalse( $info->forceHTTPS() );
202  $this->assertSame( [
203  [
204  LogLevel::DEBUG,
205  'Session "{session}" requested without UserID cookie',
206  ],
207  ], $logger->getBuffer() );
208  $logger->clearBuffer();
209 
210  // User, no session key
211  $request = new \FauxRequest();
212  $request->setCookies( [
213  'xUserID' => $id,
214  'xToken' => $token,
215  ], '' );
216  $info = $provider->provideSessionInfo( $request );
217  $this->assertNotNull( $info );
218  $this->assertSame( $params['priority'], $info->getPriority() );
219  $this->assertNotSame( $sessionId, $info->getId() );
220  $this->assertNotNull( $info->getUserInfo() );
221  $this->assertSame( $id, $info->getUserInfo()->getId() );
222  $this->assertSame( $name, $info->getUserInfo()->getName() );
223  $this->assertFalse( $info->forceHTTPS() );
224  $this->assertSame( [], $logger->getBuffer() );
225  $logger->clearBuffer();
226 
227  // User and session key
228  $request = new \FauxRequest();
229  $request->setCookies( [
230  'session' => $sessionId,
231  'xUserID' => $id,
232  'xToken' => $token,
233  ], '' );
234  $info = $provider->provideSessionInfo( $request );
235  $this->assertNotNull( $info );
236  $this->assertSame( $params['priority'], $info->getPriority() );
237  $this->assertSame( $sessionId, $info->getId() );
238  $this->assertNotNull( $info->getUserInfo() );
239  $this->assertSame( $id, $info->getUserInfo()->getId() );
240  $this->assertSame( $name, $info->getUserInfo()->getName() );
241  $this->assertFalse( $info->forceHTTPS() );
242  $this->assertSame( [], $logger->getBuffer() );
243  $logger->clearBuffer();
244 
245  // User with bad token
246  $request = new \FauxRequest();
247  $request->setCookies( [
248  'session' => $sessionId,
249  'xUserID' => $id,
250  'xToken' => 'BADTOKEN',
251  ], '' );
252  $info = $provider->provideSessionInfo( $request );
253  $this->assertNull( $info );
254  $this->assertSame( [
255  [
256  LogLevel::WARNING,
257  'Session "{session}" requested with invalid Token cookie.'
258  ],
259  ], $logger->getBuffer() );
260  $logger->clearBuffer();
261 
262  // User id with no token
263  $request = new \FauxRequest();
264  $request->setCookies( [
265  'session' => $sessionId,
266  'xUserID' => $id,
267  ], '' );
268  $info = $provider->provideSessionInfo( $request );
269  $this->assertNotNull( $info );
270  $this->assertSame( $params['priority'], $info->getPriority() );
271  $this->assertSame( $sessionId, $info->getId() );
272  $this->assertNotNull( $info->getUserInfo() );
273  $this->assertFalse( $info->getUserInfo()->isVerified() );
274  $this->assertSame( $id, $info->getUserInfo()->getId() );
275  $this->assertSame( $name, $info->getUserInfo()->getName() );
276  $this->assertFalse( $info->forceHTTPS() );
277  $this->assertSame( [], $logger->getBuffer() );
278  $logger->clearBuffer();
279 
280  $request = new \FauxRequest();
281  $request->setCookies( [
282  'xUserID' => $id,
283  ], '' );
284  $info = $provider->provideSessionInfo( $request );
285  $this->assertNull( $info );
286  $this->assertSame( [], $logger->getBuffer() );
287  $logger->clearBuffer();
288 
289  // User and session key, with forceHTTPS flag
290  $request = new \FauxRequest();
291  $request->setCookies( [
292  'session' => $sessionId,
293  'xUserID' => $id,
294  'xToken' => $token,
295  'forceHTTPS' => true,
296  ], '' );
297  $info = $provider->provideSessionInfo( $request );
298  $this->assertNotNull( $info );
299  $this->assertSame( $params['priority'], $info->getPriority() );
300  $this->assertSame( $sessionId, $info->getId() );
301  $this->assertNotNull( $info->getUserInfo() );
302  $this->assertSame( $id, $info->getUserInfo()->getId() );
303  $this->assertSame( $name, $info->getUserInfo()->getName() );
304  $this->assertTrue( $info->forceHTTPS() );
305  $this->assertSame( [], $logger->getBuffer() );
306  $logger->clearBuffer();
307 
308  // Invalid user id
309  $request = new \FauxRequest();
310  $request->setCookies( [
311  'session' => $sessionId,
312  'xUserID' => '-1',
313  ], '' );
314  $info = $provider->provideSessionInfo( $request );
315  $this->assertNull( $info );
316  $this->assertSame( [], $logger->getBuffer() );
317  $logger->clearBuffer();
318 
319  // User id with matching name
320  $request = new \FauxRequest();
321  $request->setCookies( [
322  'session' => $sessionId,
323  'xUserID' => $id,
324  'xUserName' => $name,
325  ], '' );
326  $info = $provider->provideSessionInfo( $request );
327  $this->assertNotNull( $info );
328  $this->assertSame( $params['priority'], $info->getPriority() );
329  $this->assertSame( $sessionId, $info->getId() );
330  $this->assertNotNull( $info->getUserInfo() );
331  $this->assertFalse( $info->getUserInfo()->isVerified() );
332  $this->assertSame( $id, $info->getUserInfo()->getId() );
333  $this->assertSame( $name, $info->getUserInfo()->getName() );
334  $this->assertFalse( $info->forceHTTPS() );
335  $this->assertSame( [], $logger->getBuffer() );
336  $logger->clearBuffer();
337 
338  // User id with wrong name
339  $request = new \FauxRequest();
340  $request->setCookies( [
341  'session' => $sessionId,
342  'xUserID' => $id,
343  'xUserName' => 'Wrong',
344  ], '' );
345  $info = $provider->provideSessionInfo( $request );
346  $this->assertNull( $info );
347  $this->assertSame( [
348  [
349  LogLevel::WARNING,
350  'Session "{session}" requested with mismatched UserID and UserName cookies.',
351  ],
352  ], $logger->getBuffer() );
353  $logger->clearBuffer();
354  }
355 
356  public function testGetVaryCookies() {
357  $provider = new CookieSessionProvider( [
358  'priority' => 1,
359  'sessionName' => 'MySessionName',
360  'cookieOptions' => [ 'prefix' => 'MyCookiePrefix' ],
361  ] );
362  $this->assertArrayEquals( [
363  'MyCookiePrefixToken',
364  'MyCookiePrefixLoggedOut',
365  'MySessionName',
366  'forceHTTPS',
367  ], $provider->getVaryCookies() );
368  }
369 
370  public function testSuggestLoginUsername() {
371  $provider = new CookieSessionProvider( [
372  'priority' => 1,
373  'sessionName' => 'MySessionName',
374  'cookieOptions' => [ 'prefix' => 'x' ],
375  ] );
376 
377  $request = new \FauxRequest();
378  $this->assertEquals( null, $provider->suggestLoginUsername( $request ) );
379 
380  $request->setCookies( [
381  'xUserName' => 'Example',
382  ], '' );
383  $this->assertEquals( 'Example', $provider->suggestLoginUsername( $request ) );
384  }
385 
386  public function testPersistSession() {
387  $provider = new CookieSessionProvider( [
388  'priority' => 1,
389  'sessionName' => 'MySessionName',
390  'callUserSetCookiesHook' => false,
391  'cookieOptions' => [ 'prefix' => 'x' ],
392  ] );
393  $config = $this->getConfig();
394  $provider->setLogger( new \TestLogger() );
395  $provider->setConfig( $config );
396  $provider->setManager( SessionManager::singleton() );
397 
398  $sessionId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
399  $store = new TestBagOStuff();
400  $user = static::getTestSysop()->getUser();
401  $anon = new User;
402 
403  $backend = new SessionBackend(
404  new SessionId( $sessionId ),
406  'provider' => $provider,
407  'id' => $sessionId,
408  'persisted' => true,
409  'idIsSafe' => true,
410  ] ),
411  $store,
412  new \Psr\Log\NullLogger(),
413  10
414  );
415  \TestingAccessWrapper::newFromObject( $backend )->usePhpSessionHandling = false;
416 
417  $mock = $this->getMock( 'stdClass', [ 'onUserSetCookies' ] );
418  $mock->expects( $this->never() )->method( 'onUserSetCookies' );
419  $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserSetCookies' => [ $mock ] ] );
420 
421  // Anonymous user
422  $backend->setUser( $anon );
423  $backend->setRememberUser( true );
424  $backend->setForceHTTPS( false );
425  $request = new \FauxRequest();
426  $provider->persistSession( $backend, $request );
427  $this->assertSame( $sessionId, $request->response()->getCookie( 'MySessionName' ) );
428  $this->assertSame( '', $request->response()->getCookie( 'xUserID' ) );
429  $this->assertSame( null, $request->response()->getCookie( 'xUserName' ) );
430  $this->assertSame( '', $request->response()->getCookie( 'xToken' ) );
431  $this->assertSame( '', $request->response()->getCookie( 'forceHTTPS' ) );
432  $this->assertSame( [], $backend->getData() );
433 
434  // Logged-in user, no remember
435  $backend->setUser( $user );
436  $backend->setRememberUser( false );
437  $backend->setForceHTTPS( false );
438  $request = new \FauxRequest();
439  $provider->persistSession( $backend, $request );
440  $this->assertSame( $sessionId, $request->response()->getCookie( 'MySessionName' ) );
441  $this->assertSame( (string)$user->getId(), $request->response()->getCookie( 'xUserID' ) );
442  $this->assertSame( $user->getName(), $request->response()->getCookie( 'xUserName' ) );
443  $this->assertSame( '', $request->response()->getCookie( 'xToken' ) );
444  $this->assertSame( '', $request->response()->getCookie( 'forceHTTPS' ) );
445  $this->assertSame( [], $backend->getData() );
446 
447  // Logged-in user, remember
448  $backend->setUser( $user );
449  $backend->setRememberUser( true );
450  $backend->setForceHTTPS( true );
451  $request = new \FauxRequest();
452  $time = time();
453  $provider->persistSession( $backend, $request );
454  $this->assertSame( $sessionId, $request->response()->getCookie( 'MySessionName' ) );
455  $this->assertSame( (string)$user->getId(), $request->response()->getCookie( 'xUserID' ) );
456  $this->assertSame( $user->getName(), $request->response()->getCookie( 'xUserName' ) );
457  $this->assertSame( $user->getToken(), $request->response()->getCookie( 'xToken' ) );
458  $this->assertSame( 'true', $request->response()->getCookie( 'forceHTTPS' ) );
459  $this->assertSame( [], $backend->getData() );
460  }
461 
467  public function testCookieData( $secure, $remember ) {
468  $this->setMwGlobals( [
469  'wgSecureLogin' => false,
470  ] );
471 
472  $provider = new CookieSessionProvider( [
473  'priority' => 1,
474  'sessionName' => 'MySessionName',
475  'callUserSetCookiesHook' => false,
476  'cookieOptions' => [ 'prefix' => 'x' ],
477  ] );
478  $config = $this->getConfig();
479  $config->set( 'CookieSecure', $secure );
480  $provider->setLogger( new \TestLogger() );
481  $provider->setConfig( $config );
482  $provider->setManager( SessionManager::singleton() );
483 
484  $sessionId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
485  $user = static::getTestSysop()->getUser();
486  $this->assertFalse( $user->requiresHTTPS(), 'sanity check' );
487 
488  $backend = new SessionBackend(
489  new SessionId( $sessionId ),
491  'provider' => $provider,
492  'id' => $sessionId,
493  'persisted' => true,
494  'idIsSafe' => true,
495  ] ),
496  new TestBagOStuff(),
497  new \Psr\Log\NullLogger(),
498  10
499  );
500  \TestingAccessWrapper::newFromObject( $backend )->usePhpSessionHandling = false;
501  $backend->setUser( $user );
502  $backend->setRememberUser( $remember );
503  $backend->setForceHTTPS( $secure );
504  $request = new \FauxRequest();
505  $time = time();
506  $provider->persistSession( $backend, $request );
507 
508  $defaults = [
509  'expire' => (int)100,
510  'path' => $config->get( 'CookiePath' ),
511  'domain' => $config->get( 'CookieDomain' ),
512  'secure' => $secure,
513  'httpOnly' => $config->get( 'CookieHttpOnly' ),
514  'raw' => false,
515  ];
516 
517  $normalExpiry = $config->get( 'CookieExpiration' );
518  $extendedExpiry = $config->get( 'ExtendedLoginCookieExpiration' );
519  $extendedExpiry = (int)( $extendedExpiry === null ? 0 : $extendedExpiry );
520  $expect = [
521  'MySessionName' => [
522  'value' => (string)$sessionId,
523  'expire' => 0,
524  ] + $defaults,
525  'xUserID' => [
526  'value' => (string)$user->getId(),
527  'expire' => $remember ? $extendedExpiry : $normalExpiry,
528  ] + $defaults,
529  'xUserName' => [
530  'value' => $user->getName(),
531  'expire' => $remember ? $extendedExpiry : $normalExpiry
532  ] + $defaults,
533  'xToken' => [
534  'value' => $remember ? $user->getToken() : '',
535  'expire' => $remember ? $extendedExpiry : -31536000,
536  ] + $defaults,
537  'forceHTTPS' => [
538  'value' => $secure ? 'true' : '',
539  'secure' => false,
540  'expire' => $secure ? $remember ? $defaults['expire'] : 0 : -31536000,
541  ] + $defaults,
542  ];
543  foreach ( $expect as $key => $value ) {
544  $actual = $request->response()->getCookieData( $key );
545  if ( $actual && $actual['expire'] > 0 ) {
546  // Round expiry so we don't randomly fail if the seconds ticked during the test.
547  $actual['expire'] = round( $actual['expire'] - $time, -2 );
548  }
549  $this->assertEquals( $value, $actual, "Cookie $key" );
550  }
551  }
552 
553  public static function provideCookieData() {
554  return [
555  [ false, false ],
556  [ false, true ],
557  [ true, false ],
558  [ true, true ],
559  ];
560  }
561 
562  protected function getSentRequest() {
563  $sentResponse = $this->getMock( 'FauxResponse', [ 'headersSent', 'setCookie', 'header' ] );
564  $sentResponse->expects( $this->any() )->method( 'headersSent' )
565  ->will( $this->returnValue( true ) );
566  $sentResponse->expects( $this->never() )->method( 'setCookie' );
567  $sentResponse->expects( $this->never() )->method( 'header' );
568 
569  $sentRequest = $this->getMock( 'FauxRequest', [ 'response' ] );
570  $sentRequest->expects( $this->any() )->method( 'response' )
571  ->will( $this->returnValue( $sentResponse ) );
572  return $sentRequest;
573  }
574 
575  public function testPersistSessionWithHook() {
576  $provider = new CookieSessionProvider( [
577  'priority' => 1,
578  'sessionName' => 'MySessionName',
579  'callUserSetCookiesHook' => true,
580  'cookieOptions' => [ 'prefix' => 'x' ],
581  ] );
582  $provider->setLogger( new \Psr\Log\NullLogger() );
583  $provider->setConfig( $this->getConfig() );
584  $provider->setManager( SessionManager::singleton() );
585 
586  $sessionId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
587  $store = new TestBagOStuff();
588  $user = static::getTestSysop()->getUser();
589  $anon = new User;
590 
591  $backend = new SessionBackend(
592  new SessionId( $sessionId ),
594  'provider' => $provider,
595  'id' => $sessionId,
596  'persisted' => true,
597  'idIsSafe' => true,
598  ] ),
599  $store,
600  new \Psr\Log\NullLogger(),
601  10
602  );
603  \TestingAccessWrapper::newFromObject( $backend )->usePhpSessionHandling = false;
604 
605  // Anonymous user
606  $mock = $this->getMock( 'stdClass', [ 'onUserSetCookies' ] );
607  $mock->expects( $this->never() )->method( 'onUserSetCookies' );
608  $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserSetCookies' => [ $mock ] ] );
609  $backend->setUser( $anon );
610  $backend->setRememberUser( true );
611  $backend->setForceHTTPS( false );
612  $request = new \FauxRequest();
613  $provider->persistSession( $backend, $request );
614  $this->assertSame( $sessionId, $request->response()->getCookie( 'MySessionName' ) );
615  $this->assertSame( '', $request->response()->getCookie( 'xUserID' ) );
616  $this->assertSame( null, $request->response()->getCookie( 'xUserName' ) );
617  $this->assertSame( '', $request->response()->getCookie( 'xToken' ) );
618  $this->assertSame( '', $request->response()->getCookie( 'forceHTTPS' ) );
619  $this->assertSame( [], $backend->getData() );
620 
621  $provider->persistSession( $backend, $this->getSentRequest() );
622 
623  // Logged-in user, no remember
624  $mock = $this->getMock( __CLASS__, [ 'onUserSetCookies' ] );
625  $mock->expects( $this->once() )->method( 'onUserSetCookies' )
626  ->will( $this->returnCallback( function ( $u, &$sessionData, &$cookies ) use ( $user ) {
627  $this->assertSame( $user, $u );
628  $this->assertEquals( [
629  'wsUserID' => $user->getId(),
630  'wsUserName' => $user->getName(),
631  'wsToken' => $user->getToken(),
632  ], $sessionData );
633  $this->assertEquals( [
634  'UserID' => $user->getId(),
635  'UserName' => $user->getName(),
636  'Token' => false,
637  ], $cookies );
638 
639  $sessionData['foo'] = 'foo!';
640  $cookies['bar'] = 'bar!';
641  return true;
642  } ) );
643  $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserSetCookies' => [ $mock ] ] );
644  $backend->setUser( $user );
645  $backend->setRememberUser( false );
646  $backend->setForceHTTPS( false );
647  $backend->setLoggedOutTimestamp( $loggedOut = time() );
648  $request = new \FauxRequest();
649  $provider->persistSession( $backend, $request );
650  $this->assertSame( $sessionId, $request->response()->getCookie( 'MySessionName' ) );
651  $this->assertSame( (string)$user->getId(), $request->response()->getCookie( 'xUserID' ) );
652  $this->assertSame( $user->getName(), $request->response()->getCookie( 'xUserName' ) );
653  $this->assertSame( '', $request->response()->getCookie( 'xToken' ) );
654  $this->assertSame( '', $request->response()->getCookie( 'forceHTTPS' ) );
655  $this->assertSame( 'bar!', $request->response()->getCookie( 'xbar' ) );
656  $this->assertSame( (string)$loggedOut, $request->response()->getCookie( 'xLoggedOut' ) );
657  $this->assertEquals( [
658  'wsUserID' => $user->getId(),
659  'wsUserName' => $user->getName(),
660  'wsToken' => $user->getToken(),
661  'foo' => 'foo!',
662  ], $backend->getData() );
663 
664  $provider->persistSession( $backend, $this->getSentRequest() );
665 
666  // Logged-in user, remember
667  $mock = $this->getMock( __CLASS__, [ 'onUserSetCookies' ] );
668  $mock->expects( $this->once() )->method( 'onUserSetCookies' )
669  ->will( $this->returnCallback( function ( $u, &$sessionData, &$cookies ) use ( $user ) {
670  $this->assertSame( $user, $u );
671  $this->assertEquals( [
672  'wsUserID' => $user->getId(),
673  'wsUserName' => $user->getName(),
674  'wsToken' => $user->getToken(),
675  ], $sessionData );
676  $this->assertEquals( [
677  'UserID' => $user->getId(),
678  'UserName' => $user->getName(),
679  'Token' => $user->getToken(),
680  ], $cookies );
681 
682  $sessionData['foo'] = 'foo 2!';
683  $cookies['bar'] = 'bar 2!';
684  return true;
685  } ) );
686  $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserSetCookies' => [ $mock ] ] );
687  $backend->setUser( $user );
688  $backend->setRememberUser( true );
689  $backend->setForceHTTPS( true );
690  $backend->setLoggedOutTimestamp( 0 );
691  $request = new \FauxRequest();
692  $provider->persistSession( $backend, $request );
693  $this->assertSame( $sessionId, $request->response()->getCookie( 'MySessionName' ) );
694  $this->assertSame( (string)$user->getId(), $request->response()->getCookie( 'xUserID' ) );
695  $this->assertSame( $user->getName(), $request->response()->getCookie( 'xUserName' ) );
696  $this->assertSame( $user->getToken(), $request->response()->getCookie( 'xToken' ) );
697  $this->assertSame( 'true', $request->response()->getCookie( 'forceHTTPS' ) );
698  $this->assertSame( 'bar 2!', $request->response()->getCookie( 'xbar' ) );
699  $this->assertSame( null, $request->response()->getCookie( 'xLoggedOut' ) );
700  $this->assertEquals( [
701  'wsUserID' => $user->getId(),
702  'wsUserName' => $user->getName(),
703  'wsToken' => $user->getToken(),
704  'foo' => 'foo 2!',
705  ], $backend->getData() );
706 
707  $provider->persistSession( $backend, $this->getSentRequest() );
708  }
709 
710  public function testUnpersistSession() {
711  $provider = new CookieSessionProvider( [
712  'priority' => 1,
713  'sessionName' => 'MySessionName',
714  'cookieOptions' => [ 'prefix' => 'x' ],
715  ] );
716  $provider->setLogger( new \Psr\Log\NullLogger() );
717  $provider->setConfig( $this->getConfig() );
718  $provider->setManager( SessionManager::singleton() );
719 
720  $request = new \FauxRequest();
721  $provider->unpersistSession( $request );
722  $this->assertSame( '', $request->response()->getCookie( 'MySessionName' ) );
723  $this->assertSame( '', $request->response()->getCookie( 'xUserID' ) );
724  $this->assertSame( null, $request->response()->getCookie( 'xUserName' ) );
725  $this->assertSame( '', $request->response()->getCookie( 'xToken' ) );
726  $this->assertSame( '', $request->response()->getCookie( 'forceHTTPS' ) );
727 
728  $provider->unpersistSession( $this->getSentRequest() );
729  }
730 
731  public function testSetLoggedOutCookie() {
733  'priority' => 1,
734  'sessionName' => 'MySessionName',
735  'cookieOptions' => [ 'prefix' => 'x' ],
736  ] ) );
737  $provider->setLogger( new \Psr\Log\NullLogger() );
738  $provider->setConfig( $this->getConfig() );
739  $provider->setManager( SessionManager::singleton() );
740 
741  $t1 = time();
742  $t2 = time() - 86400 * 2;
743 
744  // Set it
745  $request = new \FauxRequest();
746  $provider->setLoggedOutCookie( $t1, $request );
747  $this->assertSame( (string)$t1, $request->response()->getCookie( 'xLoggedOut' ) );
748 
749  // Too old
750  $request = new \FauxRequest();
751  $provider->setLoggedOutCookie( $t2, $request );
752  $this->assertSame( null, $request->response()->getCookie( 'xLoggedOut' ) );
753 
754  // Don't reset if it's already set
755  $request = new \FauxRequest();
756  $request->setCookies( [
757  'xLoggedOut' => $t1,
758  ], '' );
759  $provider->setLoggedOutCookie( $t1, $request );
760  $this->assertSame( null, $request->response()->getCookie( 'xLoggedOut' ) );
761  }
762 
767  public function onUserSetCookies( $user, &$sessionData, &$cookies ) {
768  }
769 
770  public function testGetCookie() {
771  $provider = new CookieSessionProvider( [
772  'priority' => 1,
773  'sessionName' => 'MySessionName',
774  'cookieOptions' => [ 'prefix' => 'x' ],
775  ] );
776  $provider->setLogger( new \Psr\Log\NullLogger() );
777  $provider->setConfig( $this->getConfig() );
778  $provider->setManager( SessionManager::singleton() );
779  $provider = \TestingAccessWrapper::newFromObject( $provider );
780 
781  $request = new \FauxRequest();
782  $request->setCookies( [
783  'xFoo' => 'foo!',
784  'xBar' => 'deleted',
785  ], '' );
786  $this->assertSame( 'foo!', $provider->getCookie( $request, 'Foo', 'x' ) );
787  $this->assertNull( $provider->getCookie( $request, 'Bar', 'x' ) );
788  $this->assertNull( $provider->getCookie( $request, 'Baz', 'x' ) );
789  }
790 
791  public function testGetRememberUserDuration() {
792  $config = $this->getConfig();
793  $provider = new CookieSessionProvider( [ 'priority' => 10 ] );
794  $provider->setLogger( new \Psr\Log\NullLogger() );
795  $provider->setConfig( $config );
796  $provider->setManager( SessionManager::singleton() );
797 
798  $this->assertSame( 200, $provider->getRememberUserDuration() );
799 
800  $config->set( 'ExtendedLoginCookieExpiration', null );
801 
802  $this->assertSame( 100, $provider->getRememberUserDuration() );
803 
804  $config->set( 'ExtendedLoginCookieExpiration', 0 );
805 
806  $this->assertSame( null, $provider->getRememberUserDuration() );
807  }
808 
809  public function testGetLoginCookieExpiration() {
810  $config = $this->getConfig();
812  'priority' => 10
813  ] ) );
814  $provider->setLogger( new \Psr\Log\NullLogger() );
815  $provider->setConfig( $config );
816  $provider->setManager( SessionManager::singleton() );
817 
818  // First cookie is an extended cookie, remember me true
819  $this->assertSame( 200, $provider->getLoginCookieExpiration( 'Token', true ) );
820  $this->assertSame( 100, $provider->getLoginCookieExpiration( 'User', true ) );
821 
822  // First cookie is an extended cookie, remember me false
823  $this->assertSame( 100, $provider->getLoginCookieExpiration( 'UserID', false ) );
824  $this->assertSame( 100, $provider->getLoginCookieExpiration( 'User', false ) );
825 
826  $config->set( 'ExtendedLoginCookieExpiration', null );
827 
828  $this->assertSame( 100, $provider->getLoginCookieExpiration( 'Token', true ) );
829  $this->assertSame( 100, $provider->getLoginCookieExpiration( 'User', true ) );
830 
831  $this->assertSame( 100, $provider->getLoginCookieExpiration( 'Token', false ) );
832  $this->assertSame( 100, $provider->getLoginCookieExpiration( 'User', false ) );
833  }
834 }
const MIN_PRIORITY
Minimum allowed priority.
Definition: SessionInfo.php:36
Config $config
Definition: MediaWiki.php:38
mergeMwGlobalArrayValue($name, $values)
Merges the given values into a MW global array variable.
This is the actual workhorse for Session.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
assertArrayEquals(array $expected, array $actual, $ordered=false, $named=false)
Assert that two arrays are equal.
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:177
$value
get($name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1936
BagOStuff with utility functions for MediaWiki\\Session\\* testing.
A logger that may be configured to either buffer logs or to print them to the output where PHPUnit wi...
Definition: TestLogger.php:34
testCookieData($secure, $remember)
provideCookieData
$params
onUserSetCookies($user, &$sessionData, &$cookies)
To be mocked for hooks, since PHPUnit can't otherwise mock methods that take references.
Session Database MediaWiki\Session\CookieSessionProvider.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static singleton()
Get the global SessionManager.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
A CookieSessionProvider persists sessions using cookies.
const MAX_PRIORITY
Maximum allowed priority.
Definition: SessionInfo.php:39
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2573
Value object holding the session ID in a manner that can be globally updated.
Definition: SessionId.php:38
This serves as the entry point to the MediaWiki session handling system.
static newFromObject($object)
Return the same object, without access restrictions.
setMwGlobals($pairs, $value=null)
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1749
Value object returned by SessionProvider.
Definition: SessionInfo.php:34
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300