MediaWiki REL1_28
SessionTest.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki\Session;
4
5use Psr\Log\LogLevel;
8
14
15 public function testConstructor() {
17 \TestingAccessWrapper::newFromObject( $backend )->requests = [ -1 => 'dummy' ];
18 \TestingAccessWrapper::newFromObject( $backend )->id = new SessionId( 'abc' );
19
20 $session = new Session( $backend, 42, new \TestLogger );
21 $priv = \TestingAccessWrapper::newFromObject( $session );
22 $this->assertSame( $backend, $priv->backend );
23 $this->assertSame( 42, $priv->index );
24
25 $request = new \FauxRequest();
26 $priv2 = \TestingAccessWrapper::newFromObject( $session->sessionWithRequest( $request ) );
27 $this->assertSame( $backend, $priv2->backend );
28 $this->assertNotSame( $priv->index, $priv2->index );
29 $this->assertSame( $request, $priv2->getRequest() );
30 }
31
39 public function testMethods( $m, $args, $index, $ret ) {
40 $mock = $this->getMock( DummySessionBackend::class,
41 [ $m, 'deregisterSession' ] );
42 $mock->expects( $this->once() )->method( 'deregisterSession' )
43 ->with( $this->identicalTo( 42 ) );
44
45 $tmp = $mock->expects( $this->once() )->method( $m );
46 $expectArgs = [];
47 if ( $index ) {
48 $expectArgs[] = $this->identicalTo( 42 );
49 }
50 foreach ( $args as $arg ) {
51 $expectArgs[] = $this->identicalTo( $arg );
52 }
53 $tmp = call_user_func_array( [ $tmp, 'with' ], $expectArgs );
54
55 $retval = new \stdClass;
56 $tmp->will( $this->returnValue( $retval ) );
57
58 $session = TestUtils::getDummySession( $mock, 42 );
59
60 if ( $ret ) {
61 $this->assertSame( $retval, call_user_func_array( [ $session, $m ], $args ) );
62 } else {
63 $this->assertNull( call_user_func_array( [ $session, $m ], $args ) );
64 }
65
66 // Trigger Session destructor
67 $session = null;
68 }
69
70 public static function provideMethods() {
71 return [
72 [ 'getId', [], false, true ],
73 [ 'getSessionId', [], false, true ],
74 [ 'resetId', [], false, true ],
75 [ 'getProvider', [], false, true ],
76 [ 'isPersistent', [], false, true ],
77 [ 'persist', [], false, false ],
78 [ 'unpersist', [], false, false ],
79 [ 'shouldRememberUser', [], false, true ],
80 [ 'setRememberUser', [ true ], false, false ],
81 [ 'getRequest', [], true, true ],
82 [ 'getUser', [], false, true ],
83 [ 'getAllowedUserRights', [], false, true ],
84 [ 'canSetUser', [], false, true ],
85 [ 'setUser', [ new \stdClass ], false, false ],
86 [ 'suggestLoginUsername', [], true, true ],
87 [ 'shouldForceHTTPS', [], false, true ],
88 [ 'setForceHTTPS', [ true ], false, false ],
89 [ 'getLoggedOutTimestamp', [], false, true ],
90 [ 'setLoggedOutTimestamp', [ 123 ], false, false ],
91 [ 'getProviderMetadata', [], false, true ],
92 [ 'save', [], false, false ],
93 [ 'delaySave', [], false, true ],
94 [ 'renew', [], false, false ],
95 ];
96 }
97
98 public function testDataAccess() {
99 $session = TestUtils::getDummySession();
100 $backend = \TestingAccessWrapper::newFromObject( $session )->backend;
101
102 $this->assertEquals( 1, $session->get( 'foo' ) );
103 $this->assertEquals( 'zero', $session->get( 0 ) );
104 $this->assertFalse( $backend->dirty );
105
106 $this->assertEquals( null, $session->get( 'null' ) );
107 $this->assertEquals( 'default', $session->get( 'null', 'default' ) );
108 $this->assertFalse( $backend->dirty );
109
110 $session->set( 'foo', 55 );
111 $this->assertEquals( 55, $backend->data['foo'] );
112 $this->assertTrue( $backend->dirty );
113 $backend->dirty = false;
114
115 $session->set( 1, 'one' );
116 $this->assertEquals( 'one', $backend->data[1] );
117 $this->assertTrue( $backend->dirty );
118 $backend->dirty = false;
119
120 $session->set( 1, 'one' );
121 $this->assertFalse( $backend->dirty );
122
123 $this->assertTrue( $session->exists( 'foo' ) );
124 $this->assertTrue( $session->exists( 1 ) );
125 $this->assertFalse( $session->exists( 'null' ) );
126 $this->assertFalse( $session->exists( 100 ) );
127 $this->assertFalse( $backend->dirty );
128
129 $session->remove( 'foo' );
130 $this->assertArrayNotHasKey( 'foo', $backend->data );
131 $this->assertTrue( $backend->dirty );
132 $backend->dirty = false;
133 $session->remove( 1 );
134 $this->assertArrayNotHasKey( 1, $backend->data );
135 $this->assertTrue( $backend->dirty );
136 $backend->dirty = false;
137
138 $session->remove( 101 );
139 $this->assertFalse( $backend->dirty );
140
141 $backend->data = [ 'a', 'b', '?' => 'c' ];
142 $this->assertSame( 3, $session->count() );
143 $this->assertSame( 3, count( $session ) );
144 $this->assertFalse( $backend->dirty );
145
146 $data = [];
147 foreach ( $session as $key => $value ) {
148 $data[$key] = $value;
149 }
150 $this->assertEquals( $backend->data, $data );
151 $this->assertFalse( $backend->dirty );
152
153 $this->assertEquals( $backend->data, iterator_to_array( $session ) );
154 $this->assertFalse( $backend->dirty );
155 }
156
157 public function testArrayAccess() {
158 $logger = new \TestLogger;
159 $session = TestUtils::getDummySession( null, -1, $logger );
160 $backend = \TestingAccessWrapper::newFromObject( $session )->backend;
161
162 $this->assertEquals( 1, $session['foo'] );
163 $this->assertEquals( 'zero', $session[0] );
164 $this->assertFalse( $backend->dirty );
165
166 $logger->setCollect( true );
167 $this->assertEquals( null, $session['null'] );
168 $logger->setCollect( false );
169 $this->assertFalse( $backend->dirty );
170 $this->assertSame( [
171 [ LogLevel::DEBUG, 'Undefined index (auto-adds to session with a null value): null' ]
172 ], $logger->getBuffer() );
173 $logger->clearBuffer();
174
175 $session['foo'] = 55;
176 $this->assertEquals( 55, $backend->data['foo'] );
177 $this->assertTrue( $backend->dirty );
178 $backend->dirty = false;
179
180 $session[1] = 'one';
181 $this->assertEquals( 'one', $backend->data[1] );
182 $this->assertTrue( $backend->dirty );
183 $backend->dirty = false;
184
185 $session[1] = 'one';
186 $this->assertFalse( $backend->dirty );
187
188 $session['bar'] = [ 'baz' => [] ];
189 $session['bar']['baz']['quux'] = 2;
190 $this->assertEquals( [ 'baz' => [ 'quux' => 2 ] ], $backend->data['bar'] );
191
192 $logger->setCollect( true );
193 $session['bar2']['baz']['quux'] = 3;
194 $logger->setCollect( false );
195 $this->assertEquals( [ 'baz' => [ 'quux' => 3 ] ], $backend->data['bar2'] );
196 $this->assertSame( [
197 [ LogLevel::DEBUG, 'Undefined index (auto-adds to session with a null value): bar2' ]
198 ], $logger->getBuffer() );
199 $logger->clearBuffer();
200
201 $backend->dirty = false;
202 $this->assertTrue( isset( $session['foo'] ) );
203 $this->assertTrue( isset( $session[1] ) );
204 $this->assertFalse( isset( $session['null'] ) );
205 $this->assertFalse( isset( $session['missing'] ) );
206 $this->assertFalse( isset( $session[100] ) );
207 $this->assertFalse( $backend->dirty );
208
209 unset( $session['foo'] );
210 $this->assertArrayNotHasKey( 'foo', $backend->data );
211 $this->assertTrue( $backend->dirty );
212 $backend->dirty = false;
213 unset( $session[1] );
214 $this->assertArrayNotHasKey( 1, $backend->data );
215 $this->assertTrue( $backend->dirty );
216 $backend->dirty = false;
217
218 unset( $session[101] );
219 $this->assertFalse( $backend->dirty );
220 }
221
222 public function testClear() {
223 $session = TestUtils::getDummySession();
224 $priv = \TestingAccessWrapper::newFromObject( $session );
225
226 $backend = $this->getMock(
227 DummySessionBackend::class, [ 'canSetUser', 'setUser', 'save' ]
228 );
229 $backend->expects( $this->once() )->method( 'canSetUser' )
230 ->will( $this->returnValue( true ) );
231 $backend->expects( $this->once() )->method( 'setUser' )
232 ->with( $this->callback( function ( $user ) {
233 return $user instanceof User && $user->isAnon();
234 } ) );
235 $backend->expects( $this->once() )->method( 'save' );
236 $priv->backend = $backend;
237 $session->clear();
238 $this->assertSame( [], $backend->data );
239 $this->assertTrue( $backend->dirty );
240
241 $backend = $this->getMock(
242 DummySessionBackend::class, [ 'canSetUser', 'setUser', 'save' ]
243 );
244 $backend->data = [];
245 $backend->expects( $this->once() )->method( 'canSetUser' )
246 ->will( $this->returnValue( true ) );
247 $backend->expects( $this->once() )->method( 'setUser' )
248 ->with( $this->callback( function ( $user ) {
249 return $user instanceof User && $user->isAnon();
250 } ) );
251 $backend->expects( $this->once() )->method( 'save' );
252 $priv->backend = $backend;
253 $session->clear();
254 $this->assertFalse( $backend->dirty );
255
256 $backend = $this->getMock(
257 DummySessionBackend::class, [ 'canSetUser', 'setUser', 'save' ]
258 );
259 $backend->expects( $this->once() )->method( 'canSetUser' )
260 ->will( $this->returnValue( false ) );
261 $backend->expects( $this->never() )->method( 'setUser' );
262 $backend->expects( $this->once() )->method( 'save' );
263 $priv->backend = $backend;
264 $session->clear();
265 $this->assertSame( [], $backend->data );
266 $this->assertTrue( $backend->dirty );
267 }
268
269 public function testTokens() {
270 $session = TestUtils::getDummySession();
271 $priv = \TestingAccessWrapper::newFromObject( $session );
272 $backend = $priv->backend;
273
274 $token = \TestingAccessWrapper::newFromObject( $session->getToken() );
275 $this->assertArrayHasKey( 'wsTokenSecrets', $backend->data );
276 $this->assertArrayHasKey( 'default', $backend->data['wsTokenSecrets'] );
277 $secret = $backend->data['wsTokenSecrets']['default'];
278 $this->assertSame( $secret, $token->secret );
279 $this->assertSame( '', $token->salt );
280 $this->assertTrue( $token->wasNew() );
281
282 $token = \TestingAccessWrapper::newFromObject( $session->getToken( 'foo' ) );
283 $this->assertSame( $secret, $token->secret );
284 $this->assertSame( 'foo', $token->salt );
285 $this->assertFalse( $token->wasNew() );
286
287 $backend->data['wsTokenSecrets']['secret'] = 'sekret';
288 $token = \TestingAccessWrapper::newFromObject(
289 $session->getToken( [ 'bar', 'baz' ], 'secret' )
290 );
291 $this->assertSame( 'sekret', $token->secret );
292 $this->assertSame( 'bar|baz', $token->salt );
293 $this->assertFalse( $token->wasNew() );
294
295 $session->resetToken( 'secret' );
296 $this->assertArrayHasKey( 'wsTokenSecrets', $backend->data );
297 $this->assertArrayHasKey( 'default', $backend->data['wsTokenSecrets'] );
298 $this->assertArrayNotHasKey( 'secret', $backend->data['wsTokenSecrets'] );
299
300 $session->resetAllTokens();
301 $this->assertArrayNotHasKey( 'wsTokenSecrets', $backend->data );
302
303 }
304
309 public function testSecretsRoundTripping( $data ) {
310 $session = TestUtils::getDummySession();
311
312 // Simple round-trip
313 $session->setSecret( 'secret', $data );
314 $this->assertNotEquals( $data, $session->get( 'secret' ) );
315 $this->assertEquals( $data, $session->getSecret( 'secret', 'defaulted' ) );
316 }
317
318 public static function provideSecretsRoundTripping() {
319 return [
320 [ 'Foobar' ],
321 [ 42 ],
322 [ [ 'foo', 'bar' => 'baz', 'subarray' => [ 1, 2, 3 ] ] ],
323 [ (object)[ 'foo', 'bar' => 'baz', 'subarray' => [ 1, 2, 3 ] ] ],
324 [ true ],
325 [ false ],
326 [ null ],
327 ];
328 }
329
330 public function testSecrets() {
331 $logger = new \TestLogger;
332 $session = TestUtils::getDummySession( null, -1, $logger );
333
334 // Simple defaulting
335 $this->assertEquals( 'defaulted', $session->getSecret( 'test', 'defaulted' ) );
336
337 // Bad encrypted data
338 $session->set( 'test', 'foobar' );
339 $logger->setCollect( true );
340 $this->assertEquals( 'defaulted', $session->getSecret( 'test', 'defaulted' ) );
341 $logger->setCollect( false );
342 $this->assertSame( [
343 [ LogLevel::WARNING, 'Invalid sealed-secret format' ]
344 ], $logger->getBuffer() );
345 $logger->clearBuffer();
346
347 // Tampered data
348 $session->setSecret( 'test', 'foobar' );
349 $encrypted = $session->get( 'test' );
350 $session->set( 'test', $encrypted . 'x' );
351 $logger->setCollect( true );
352 $this->assertEquals( 'defaulted', $session->getSecret( 'test', 'defaulted' ) );
353 $logger->setCollect( false );
354 $this->assertSame( [
355 [ LogLevel::WARNING, 'Sealed secret has been tampered with, aborting.' ]
356 ], $logger->getBuffer() );
357 $logger->clearBuffer();
358
359 // Unserializable data
360 $iv = \MWCryptRand::generate( 16, true );
361 list( $encKey, $hmacKey ) = \TestingAccessWrapper::newFromObject( $session )->getSecretKeys();
362 $ciphertext = openssl_encrypt( 'foobar', 'aes-256-ctr', $encKey, OPENSSL_RAW_DATA, $iv );
363 $sealed = base64_encode( $iv ) . '.' . base64_encode( $ciphertext );
364 $hmac = hash_hmac( 'sha256', $sealed, $hmacKey, true );
365 $encrypted = base64_encode( $hmac ) . '.' . $sealed;
366 $session->set( 'test', $encrypted );
367 \MediaWiki\suppressWarnings();
368 $this->assertEquals( 'defaulted', $session->getSecret( 'test', 'defaulted' ) );
369 \MediaWiki\restoreWarnings();
370 }
371
372}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if( $line===false) $args
Definition cdb.php:64
getRequest()
Get the WebRequest object.
Value object holding the session ID in a manner that can be globally updated.
Definition SessionId.php:38
Session MediaWiki\Session\Session.
testMethods( $m, $args, $index, $ret)
provideMethods
testSecretsRoundTripping( $data)
provideSecretsRoundTripping
Manages data for an an authenticated session.
Definition Session.php:48
static getDummySessionBackend()
If you need a SessionBackend for testing but don't want to create a real one, use this.
Definition TestUtils.php:64
static getDummySession( $backend=null, $index=-1, $logger=null)
If you need a Session for testing but don't want to create a backend to construct one,...
Definition TestUtils.php:85
A logger that may be configured to either buffer logs or to print them to the output where PHPUnit wi...
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:48
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
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
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition globals.txt:64
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:249
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 incomplete not yet checked for validity & $retval
Definition hooks.txt:268
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:1950
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2685
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 & $ret
Definition hooks.txt:1949
processing should stop and the error should be shown to the user * false
Definition hooks.txt:189
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:37