MediaWiki  1.28.0
PHPSessionHandlerTest.php
Go to the documentation of this file.
1 <?php
2 
3 namespace MediaWiki\Session;
4 
7 
13 
14  private function getResetter( &$rProp = null ) {
15  $reset = [];
16 
17  // Ignore "headers already sent" warnings during this test
18  set_error_handler( function ( $errno, $errstr ) use ( &$warnings ) {
19  if ( preg_match( '/headers already sent/', $errstr ) ) {
20  return true;
21  }
22  return false;
23  } );
24  $reset[] = new \Wikimedia\ScopedCallback( 'restore_error_handler' );
25 
26  $rProp = new \ReflectionProperty( PHPSessionHandler::class, 'instance' );
27  $rProp->setAccessible( true );
28  if ( $rProp->getValue() ) {
29  $old = \TestingAccessWrapper::newFromObject( $rProp->getValue() );
30  $oldManager = $old->manager;
31  $oldStore = $old->store;
32  $oldLogger = $old->logger;
33  $reset[] = new \Wikimedia\ScopedCallback(
34  [ PHPSessionHandler::class, 'install' ],
35  [ $oldManager, $oldStore, $oldLogger ]
36  );
37  }
38 
39  return $reset;
40  }
41 
42  public function testEnableFlags() {
44  $this->getMockBuilder( PHPSessionHandler::class )
45  ->setMethods( null )
46  ->disableOriginalConstructor()
47  ->getMock()
48  );
49 
50  $rProp = new \ReflectionProperty( PHPSessionHandler::class, 'instance' );
51  $rProp->setAccessible( true );
52  $reset = new \Wikimedia\ScopedCallback( [ $rProp, 'setValue' ], [ $rProp->getValue() ] );
53  $rProp->setValue( $handler );
54 
55  $handler->setEnableFlags( 'enable' );
56  $this->assertTrue( $handler->enable );
57  $this->assertFalse( $handler->warn );
58  $this->assertTrue( PHPSessionHandler::isEnabled() );
59 
60  $handler->setEnableFlags( 'warn' );
61  $this->assertTrue( $handler->enable );
62  $this->assertTrue( $handler->warn );
63  $this->assertTrue( PHPSessionHandler::isEnabled() );
64 
65  $handler->setEnableFlags( 'disable' );
66  $this->assertFalse( $handler->enable );
67  $this->assertFalse( PHPSessionHandler::isEnabled() );
68 
69  $rProp->setValue( null );
70  $this->assertFalse( PHPSessionHandler::isEnabled() );
71  }
72 
73  public function testInstall() {
74  $reset = $this->getResetter( $rProp );
75  $rProp->setValue( null );
76 
77  session_write_close();
78  ini_set( 'session.use_cookies', 1 );
79  ini_set( 'session.use_trans_sid', 1 );
80 
81  $store = new TestBagOStuff();
82  $logger = new \TestLogger();
83  $manager = new SessionManager( [
84  'store' => $store,
85  'logger' => $logger,
86  ] );
87 
88  $this->assertFalse( PHPSessionHandler::isInstalled() );
89  PHPSessionHandler::install( $manager );
90  $this->assertTrue( PHPSessionHandler::isInstalled() );
91 
92  $this->assertFalse( wfIniGetBool( 'session.use_cookies' ) );
93  $this->assertFalse( wfIniGetBool( 'session.use_trans_sid' ) );
94 
95  $this->assertNotNull( $rProp->getValue() );
96  $priv = \TestingAccessWrapper::newFromObject( $rProp->getValue() );
97  $this->assertSame( $manager, $priv->manager );
98  $this->assertSame( $store, $priv->store );
99  $this->assertSame( $logger, $priv->logger );
100  }
101 
106  public function testSessionHandling( $handler ) {
107  $this->hideDeprecated( '$_SESSION' );
108  $reset[] = $this->getResetter( $rProp );
109 
110  $this->setMwGlobals( [
111  'wgSessionProviders' => [ [ 'class' => 'DummySessionProvider' ] ],
112  'wgObjectCacheSessionExpiry' => 2,
113  ] );
114 
115  $store = new TestBagOStuff();
116  $logger = new \TestLogger( true, function ( $m ) {
117  // Discard all log events starting with expected prefix
118  return preg_match( '/^SessionBackend "\{session\}" /', $m ) ? null : $m;
119  } );
120  $manager = new SessionManager( [
121  'store' => $store,
122  'logger' => $logger,
123  ] );
124  PHPSessionHandler::install( $manager );
125  $wrap = \TestingAccessWrapper::newFromObject( $rProp->getValue() );
126  $reset[] = new \Wikimedia\ScopedCallback(
127  [ $wrap, 'setEnableFlags' ],
128  [ $wrap->enable ? $wrap->warn ? 'warn' : 'enable' : 'disable' ]
129  );
130  $wrap->setEnableFlags( 'warn' );
131 
132  \MediaWiki\suppressWarnings();
133  ini_set( 'session.serialize_handler', $handler );
134  \MediaWiki\restoreWarnings();
135  if ( ini_get( 'session.serialize_handler' ) !== $handler ) {
136  $this->markTestSkipped( "Cannot set session.serialize_handler to \"$handler\"" );
137  }
138 
139  // Session IDs for testing
140  $sessionA = str_repeat( 'a', 32 );
141  $sessionB = str_repeat( 'b', 32 );
142  $sessionC = str_repeat( 'c', 32 );
143 
144  // Set up garbage data in the session
145  $_SESSION['AuthenticationSessionTest'] = 'bogus';
146 
147  session_id( $sessionA );
148  session_start();
149  $this->assertSame( [], $_SESSION );
150  $this->assertSame( $sessionA, session_id() );
151 
152  // Set some data in the session so we can see if it works.
153  $rand = mt_rand();
154  $_SESSION['AuthenticationSessionTest'] = $rand;
155  $expect = [ 'AuthenticationSessionTest' => $rand ];
156  session_write_close();
157  $this->assertSame( [
158  [ LogLevel::WARNING, 'Something wrote to $_SESSION!' ],
159  ], $logger->getBuffer() );
160 
161  // Screw up $_SESSION so we can tell the difference between "this
162  // worked" and "this did nothing"
163  $_SESSION['AuthenticationSessionTest'] = 'bogus';
164 
165  // Re-open the session and see that data was actually reloaded
166  session_start();
167  $this->assertSame( $expect, $_SESSION );
168 
169  // Make sure session_reset() works too.
170  if ( function_exists( 'session_reset' ) ) {
171  $_SESSION['AuthenticationSessionTest'] = 'bogus';
172  session_reset();
173  $this->assertSame( $expect, $_SESSION );
174  }
175 
176  // Re-fill the session, then test that session_destroy() works.
177  $_SESSION['AuthenticationSessionTest'] = $rand;
178  session_write_close();
179  session_start();
180  $this->assertSame( $expect, $_SESSION );
181  session_destroy();
182  session_id( $sessionA );
183  session_start();
184  $this->assertSame( [], $_SESSION );
185  session_write_close();
186 
187  // Test that our session handler won't clone someone else's session
188  session_id( $sessionB );
189  session_start();
190  $this->assertSame( $sessionB, session_id() );
191  $_SESSION['id'] = 'B';
192  session_write_close();
193 
194  session_id( $sessionC );
195  session_start();
196  $this->assertSame( [], $_SESSION );
197  $_SESSION['id'] = 'C';
198  session_write_close();
199 
200  session_id( $sessionB );
201  session_start();
202  $this->assertSame( [ 'id' => 'B' ], $_SESSION );
203  session_write_close();
204 
205  session_id( $sessionC );
206  session_start();
207  $this->assertSame( [ 'id' => 'C' ], $_SESSION );
208  session_destroy();
209 
210  session_id( $sessionB );
211  session_start();
212  $this->assertSame( [ 'id' => 'B' ], $_SESSION );
213 
214  // Test merging between Session and $_SESSION
215  session_write_close();
216 
217  $session = $manager->getEmptySession();
218  $session->set( 'Unchanged', 'setup' );
219  $session->set( 'Unchanged, null', null );
220  $session->set( 'Changed in $_SESSION', 'setup' );
221  $session->set( 'Changed in Session', 'setup' );
222  $session->set( 'Changed in both', 'setup' );
223  $session->set( 'Deleted in Session', 'setup' );
224  $session->set( 'Deleted in $_SESSION', 'setup' );
225  $session->set( 'Deleted in both', 'setup' );
226  $session->set( 'Deleted in Session, changed in $_SESSION', 'setup' );
227  $session->set( 'Deleted in $_SESSION, changed in Session', 'setup' );
228  $session->persist();
229  $session->save();
230 
231  session_id( $session->getId() );
232  session_start();
233  $session->set( 'Added in Session', 'Session' );
234  $session->set( 'Added in both', 'Session' );
235  $session->set( 'Changed in Session', 'Session' );
236  $session->set( 'Changed in both', 'Session' );
237  $session->set( 'Deleted in $_SESSION, changed in Session', 'Session' );
238  $session->remove( 'Deleted in Session' );
239  $session->remove( 'Deleted in both' );
240  $session->remove( 'Deleted in Session, changed in $_SESSION' );
241  $session->save();
242  $_SESSION['Added in $_SESSION'] = '$_SESSION';
243  $_SESSION['Added in both'] = '$_SESSION';
244  $_SESSION['Changed in $_SESSION'] = '$_SESSION';
245  $_SESSION['Changed in both'] = '$_SESSION';
246  $_SESSION['Deleted in Session, changed in $_SESSION'] = '$_SESSION';
247  unset( $_SESSION['Deleted in $_SESSION'] );
248  unset( $_SESSION['Deleted in both'] );
249  unset( $_SESSION['Deleted in $_SESSION, changed in Session'] );
250  session_write_close();
251 
252  $this->assertEquals( [
253  'Added in Session' => 'Session',
254  'Added in $_SESSION' => '$_SESSION',
255  'Added in both' => 'Session',
256  'Unchanged' => 'setup',
257  'Unchanged, null' => null,
258  'Changed in Session' => 'Session',
259  'Changed in $_SESSION' => '$_SESSION',
260  'Changed in both' => 'Session',
261  'Deleted in Session, changed in $_SESSION' => '$_SESSION',
262  'Deleted in $_SESSION, changed in Session' => 'Session',
263  ], iterator_to_array( $session ) );
264 
265  $session->clear();
266  $session->set( 42, 'forty-two' );
267  $session->set( 'forty-two', 42 );
268  $session->set( 'wrong', 43 );
269  $session->persist();
270  $session->save();
271 
272  session_start();
273  $this->assertArrayHasKey( 'forty-two', $_SESSION );
274  $this->assertSame( 42, $_SESSION['forty-two'] );
275  $this->assertArrayHasKey( 'wrong', $_SESSION );
276  unset( $_SESSION['wrong'] );
277  session_write_close();
278 
279  $this->assertEquals( [
280  42 => 'forty-two',
281  'forty-two' => 42,
282  ], iterator_to_array( $session ) );
283 
284  // Test that write doesn't break if the session is invalid
285  $session = $manager->getEmptySession();
286  $session->persist();
287  $id = $session->getId();
288  unset( $session );
289  session_id( $id );
290  session_start();
291  $this->mergeMwGlobalArrayValue( 'wgHooks', [
292  'SessionCheckInfo' => [ function ( &$reason ) {
293  $reason = 'Testing';
294  return false;
295  } ],
296  ] );
297  $this->assertNull( $manager->getSessionById( $id, true ), 'sanity check' );
298  session_write_close();
299 
300  $this->mergeMwGlobalArrayValue( 'wgHooks', [
301  'SessionCheckInfo' => [],
302  ] );
303  $this->assertNotNull( $manager->getSessionById( $id, true ), 'sanity check' );
304  }
305 
306  public static function provideHandlers() {
307  return [
308  [ 'php' ],
309  [ 'php_binary' ],
310  [ 'php_serialize' ],
311  ];
312  }
313 
319  public function testDisabled( $method, $args ) {
320  $rProp = new \ReflectionProperty( PHPSessionHandler::class, 'instance' );
321  $rProp->setAccessible( true );
322  $handler = $this->getMockBuilder( PHPSessionHandler::class )
323  ->setMethods( null )
324  ->disableOriginalConstructor()
325  ->getMock();
326  \TestingAccessWrapper::newFromObject( $handler )->setEnableFlags( 'disable' );
327  $oldValue = $rProp->getValue();
328  $rProp->setValue( $handler );
329  $reset = new \Wikimedia\ScopedCallback( [ $rProp, 'setValue' ], [ $oldValue ] );
330 
331  call_user_func_array( [ $handler, $method ], $args );
332  }
333 
334  public static function provideDisabled() {
335  return [
336  [ 'open', [ '', '' ] ],
337  [ 'read', [ '' ] ],
338  [ 'write', [ '', '' ] ],
339  [ 'destroy', [ '' ] ],
340  ];
341  }
342 
348  public function testWrongInstance( $method, $args ) {
349  $handler = $this->getMockBuilder( PHPSessionHandler::class )
350  ->setMethods( null )
351  ->disableOriginalConstructor()
352  ->getMock();
353  \TestingAccessWrapper::newFromObject( $handler )->setEnableFlags( 'enable' );
354 
355  call_user_func_array( [ $handler, $method ], $args );
356  }
357 
358  public static function provideWrongInstance() {
359  return [
360  [ 'open', [ '', '' ] ],
361  [ 'close', [] ],
362  [ 'read', [ '' ] ],
363  [ 'write', [ '', '' ] ],
364  [ 'destroy', [ '' ] ],
365  [ 'gc', [ 0 ] ],
366  ];
367  }
368 
369 }
mergeMwGlobalArrayValue($name, $values)
Merges the given values into a MW global array variable.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Session MediaWiki\Session\PHPSessionHandler.
testWrongInstance($method, $args)
provideWrongInstance UnexpectedValueException /: Wrong instance called!$/
if($line===false) $args
Definition: cdb.php:64
testDisabled($method, $args)
provideDisabled BadMethodCallException Attempt to use PHP session management
BagOStuff with utility functions for MediaWiki\\Session\\* testing.
static install(SessionManager $manager)
Install a session handler for the current web request.
wfIniGetBool($setting)
Safety wrapper around ini_get() for boolean settings.
static isInstalled()
Test whether the handler is installed.
hideDeprecated($function)
Don't throw a warning if $function is deprecated and called later.
static isEnabled()
Test whether the handler is installed and enabled.
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
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
This serves as the entry point to the MediaWiki session handling system.
static newFromObject($object)
Return the same object, without access restrictions.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:802
setMwGlobals($pairs, $value=null)