SessionManager: Use existing backend for the ID if one is loaded
[lhc/web/wiklou.git] / tests / phpunit / includes / session / PHPSessionHandlerTest.php
1 <?php
2
3 namespace MediaWiki\Session;
4
5 use Psr\Log\LogLevel;
6 use MediaWikiTestCase;
7
8 /**
9 * @group Session
10 * @covers MediaWiki\Session\PHPSessionHandler
11 */
12 class PHPSessionHandlerTest extends MediaWikiTestCase {
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 \ScopedCallback( 'restore_error_handler' );
25
26 $rProp = new \ReflectionProperty( 'MediaWiki\\Session\\PHPSessionHandler', '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 \ScopedCallback(
34 [ 'MediaWiki\\Session\\PHPSessionHandler', 'install' ],
35 [ $oldManager, $oldStore, $oldLogger ]
36 );
37 }
38
39 return $reset;
40 }
41
42 public function testEnableFlags() {
43 $handler = \TestingAccessWrapper::newFromObject(
44 $this->getMockBuilder( 'MediaWiki\\Session\\PHPSessionHandler' )
45 ->setMethods( null )
46 ->disableOriginalConstructor()
47 ->getMock()
48 );
49
50 $rProp = new \ReflectionProperty( 'MediaWiki\\Session\\PHPSessionHandler', 'instance' );
51 $rProp->setAccessible( true );
52 $reset = new \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
102 /**
103 * @dataProvider provideHandlers
104 * @param string $handler php serialize_handler to use
105 */
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 \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 // Test expiry
177 session_write_close();
178 ini_set( 'session.gc_divisor', 1 );
179 ini_set( 'session.gc_probability', 1 );
180 sleep( 3 );
181 session_start();
182 $this->assertSame( [], $_SESSION );
183
184 // Re-fill the session, then test that session_destroy() works.
185 $_SESSION['AuthenticationSessionTest'] = $rand;
186 session_write_close();
187 session_start();
188 $this->assertSame( $expect, $_SESSION );
189 session_destroy();
190 session_id( $sessionA );
191 session_start();
192 $this->assertSame( [], $_SESSION );
193 session_write_close();
194
195 // Test that our session handler won't clone someone else's session
196 session_id( $sessionB );
197 session_start();
198 $this->assertSame( $sessionB, session_id() );
199 $_SESSION['id'] = 'B';
200 session_write_close();
201
202 session_id( $sessionC );
203 session_start();
204 $this->assertSame( [], $_SESSION );
205 $_SESSION['id'] = 'C';
206 session_write_close();
207
208 session_id( $sessionB );
209 session_start();
210 $this->assertSame( [ 'id' => 'B' ], $_SESSION );
211 session_write_close();
212
213 session_id( $sessionC );
214 session_start();
215 $this->assertSame( [ 'id' => 'C' ], $_SESSION );
216 session_destroy();
217
218 session_id( $sessionB );
219 session_start();
220 $this->assertSame( [ 'id' => 'B' ], $_SESSION );
221
222 // Test merging between Session and $_SESSION
223 session_write_close();
224
225 $session = $manager->getEmptySession();
226 $session->set( 'Unchanged', 'setup' );
227 $session->set( 'Unchanged, null', null );
228 $session->set( 'Changed in $_SESSION', 'setup' );
229 $session->set( 'Changed in Session', 'setup' );
230 $session->set( 'Changed in both', 'setup' );
231 $session->set( 'Deleted in Session', 'setup' );
232 $session->set( 'Deleted in $_SESSION', 'setup' );
233 $session->set( 'Deleted in both', 'setup' );
234 $session->set( 'Deleted in Session, changed in $_SESSION', 'setup' );
235 $session->set( 'Deleted in $_SESSION, changed in Session', 'setup' );
236 $session->persist();
237 $session->save();
238
239 session_id( $session->getId() );
240 session_start();
241 $session->set( 'Added in Session', 'Session' );
242 $session->set( 'Added in both', 'Session' );
243 $session->set( 'Changed in Session', 'Session' );
244 $session->set( 'Changed in both', 'Session' );
245 $session->set( 'Deleted in $_SESSION, changed in Session', 'Session' );
246 $session->remove( 'Deleted in Session' );
247 $session->remove( 'Deleted in both' );
248 $session->remove( 'Deleted in Session, changed in $_SESSION' );
249 $session->save();
250 $_SESSION['Added in $_SESSION'] = '$_SESSION';
251 $_SESSION['Added in both'] = '$_SESSION';
252 $_SESSION['Changed in $_SESSION'] = '$_SESSION';
253 $_SESSION['Changed in both'] = '$_SESSION';
254 $_SESSION['Deleted in Session, changed in $_SESSION'] = '$_SESSION';
255 unset( $_SESSION['Deleted in $_SESSION'] );
256 unset( $_SESSION['Deleted in both'] );
257 unset( $_SESSION['Deleted in $_SESSION, changed in Session'] );
258 session_write_close();
259
260 $this->assertEquals( [
261 'Added in Session' => 'Session',
262 'Added in $_SESSION' => '$_SESSION',
263 'Added in both' => 'Session',
264 'Unchanged' => 'setup',
265 'Unchanged, null' => null,
266 'Changed in Session' => 'Session',
267 'Changed in $_SESSION' => '$_SESSION',
268 'Changed in both' => 'Session',
269 'Deleted in Session, changed in $_SESSION' => '$_SESSION',
270 'Deleted in $_SESSION, changed in Session' => 'Session',
271 ], iterator_to_array( $session ) );
272
273 $session->clear();
274 $session->set( 42, 'forty-two' );
275 $session->set( 'forty-two', 42 );
276 $session->set( 'wrong', 43 );
277 $session->persist();
278 $session->save();
279
280 session_start();
281 $this->assertArrayHasKey( 'forty-two', $_SESSION );
282 $this->assertSame( 42, $_SESSION['forty-two'] );
283 $this->assertArrayHasKey( 'wrong', $_SESSION );
284 unset( $_SESSION['wrong'] );
285 session_write_close();
286
287 $this->assertEquals( [
288 42 => 'forty-two',
289 'forty-two' => 42,
290 ], iterator_to_array( $session ) );
291
292 // Test that write doesn't break if the session is invalid
293 $session = $manager->getEmptySession();
294 $session->persist();
295 $id = $session->getId();
296 unset( $session );
297 session_id( $id );
298 session_start();
299 $this->mergeMwGlobalArrayValue( 'wgHooks', [
300 'SessionCheckInfo' => [ function ( &$reason ) {
301 $reason = 'Testing';
302 return false;
303 } ],
304 ] );
305 $this->assertNull( $manager->getSessionById( $id, true ), 'sanity check' );
306 session_write_close();
307
308 $this->mergeMwGlobalArrayValue( 'wgHooks', [
309 'SessionCheckInfo' => [],
310 ] );
311 $this->assertNotNull( $manager->getSessionById( $id, true ), 'sanity check' );
312 }
313
314 public static function provideHandlers() {
315 return [
316 [ 'php' ],
317 [ 'php_binary' ],
318 [ 'php_serialize' ],
319 ];
320 }
321
322 /**
323 * @dataProvider provideDisabled
324 * @expectedException BadMethodCallException
325 * @expectedExceptionMessage Attempt to use PHP session management
326 */
327 public function testDisabled( $method, $args ) {
328 $rProp = new \ReflectionProperty( 'MediaWiki\\Session\\PHPSessionHandler', 'instance' );
329 $rProp->setAccessible( true );
330 $handler = $this->getMockBuilder( 'MediaWiki\\Session\\PHPSessionHandler' )
331 ->setMethods( null )
332 ->disableOriginalConstructor()
333 ->getMock();
334 \TestingAccessWrapper::newFromObject( $handler )->setEnableFlags( 'disable' );
335 $oldValue = $rProp->getValue();
336 $rProp->setValue( $handler );
337 $reset = new \ScopedCallback( [ $rProp, 'setValue' ], [ $oldValue ] );
338
339 call_user_func_array( [ $handler, $method ], $args );
340 }
341
342 public static function provideDisabled() {
343 return [
344 [ 'open', [ '', '' ] ],
345 [ 'read', [ '' ] ],
346 [ 'write', [ '', '' ] ],
347 [ 'destroy', [ '' ] ],
348 ];
349 }
350
351 /**
352 * @dataProvider provideWrongInstance
353 * @expectedException UnexpectedValueException
354 * @expectedExceptionMessageRegExp /: Wrong instance called!$/
355 */
356 public function testWrongInstance( $method, $args ) {
357 $handler = $this->getMockBuilder( 'MediaWiki\\Session\\PHPSessionHandler' )
358 ->setMethods( null )
359 ->disableOriginalConstructor()
360 ->getMock();
361 \TestingAccessWrapper::newFromObject( $handler )->setEnableFlags( 'enable' );
362
363 call_user_func_array( [ $handler, $method ], $args );
364 }
365
366 public static function provideWrongInstance() {
367 return [
368 [ 'open', [ '', '' ] ],
369 [ 'close', [] ],
370 [ 'read', [ '' ] ],
371 [ 'write', [ '', '' ] ],
372 [ 'destroy', [ '' ] ],
373 [ 'gc', [ 0 ] ],
374 ];
375 }
376
377 }