MediaWiki  REL1_31
ImmutableSessionProviderWithCookieTest.php
Go to the documentation of this file.
1 <?php
2 
3 namespace MediaWiki\Session;
4 
6 use User;
7 use Wikimedia\TestingAccessWrapper;
8 
15 
16  private function getProvider( $name, $prefix = null, $forceHTTPS = false ) {
17  $config = new \HashConfig();
18  $config->set( 'CookiePrefix', 'wgCookiePrefix' );
19  $config->set( 'ForceHTTPS', $forceHTTPS );
20 
21  $params = [
22  'sessionCookieName' => $name,
23  'sessionCookieOptions' => [],
24  ];
25  if ( $prefix !== null ) {
26  $params['sessionCookieOptions']['prefix'] = $prefix;
27  }
28 
29  $provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
30  ->setConstructorArgs( [ $params ] )
31  ->getMockForAbstractClass();
32  $provider->setLogger( new \TestLogger() );
33  $provider->setConfig( $config );
34  $provider->setManager( new SessionManager() );
35 
36  return $provider;
37  }
38 
39  public function testConstructor() {
40  $provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
41  ->getMockForAbstractClass();
42  $priv = TestingAccessWrapper::newFromObject( $provider );
43  $this->assertNull( $priv->sessionCookieName );
44  $this->assertSame( [], $priv->sessionCookieOptions );
45 
46  $provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
47  ->setConstructorArgs( [ [
48  'sessionCookieName' => 'Foo',
49  'sessionCookieOptions' => [ 'Bar' ],
50  ] ] )
51  ->getMockForAbstractClass();
52  $priv = TestingAccessWrapper::newFromObject( $provider );
53  $this->assertSame( 'Foo', $priv->sessionCookieName );
54  $this->assertSame( [ 'Bar' ], $priv->sessionCookieOptions );
55 
56  try {
57  $provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
58  ->setConstructorArgs( [ [
59  'sessionCookieName' => false,
60  ] ] )
61  ->getMockForAbstractClass();
62  $this->fail( 'Expected exception not thrown' );
63  } catch ( \InvalidArgumentException $ex ) {
64  $this->assertSame(
65  'sessionCookieName must be a string',
66  $ex->getMessage()
67  );
68  }
69 
70  try {
71  $provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
72  ->setConstructorArgs( [ [
73  'sessionCookieOptions' => 'x',
74  ] ] )
75  ->getMockForAbstractClass();
76  $this->fail( 'Expected exception not thrown' );
77  } catch ( \InvalidArgumentException $ex ) {
78  $this->assertSame(
79  'sessionCookieOptions must be an array',
80  $ex->getMessage()
81  );
82  }
83  }
84 
85  public function testBasics() {
86  $provider = $this->getProvider( null );
87  $this->assertFalse( $provider->persistsSessionID() );
88  $this->assertFalse( $provider->canChangeUser() );
89 
90  $provider = $this->getProvider( 'Foo' );
91  $this->assertTrue( $provider->persistsSessionID() );
92  $this->assertFalse( $provider->canChangeUser() );
93 
94  $msg = $provider->whyNoSession();
95  $this->assertInstanceOf( \Message::class, $msg );
96  $this->assertSame( 'sessionprovider-nocookies', $msg->getKey() );
97  }
98 
99  public function testGetVaryCookies() {
100  $provider = $this->getProvider( null );
101  $this->assertSame( [], $provider->getVaryCookies() );
102 
103  $provider = $this->getProvider( 'Foo' );
104  $this->assertSame( [ 'wgCookiePrefixFoo' ], $provider->getVaryCookies() );
105 
106  $provider = $this->getProvider( 'Foo', 'Bar' );
107  $this->assertSame( [ 'BarFoo' ], $provider->getVaryCookies() );
108 
109  $provider = $this->getProvider( 'Foo', '' );
110  $this->assertSame( [ 'Foo' ], $provider->getVaryCookies() );
111  }
112 
113  public function testGetSessionIdFromCookie() {
114  $this->setMwGlobals( 'wgCookiePrefix', 'wgCookiePrefix' );
115  $request = new \FauxRequest();
116  $request->setCookies( [
117  '' => 'empty---------------------------',
118  'Foo' => 'foo-----------------------------',
119  'wgCookiePrefixFoo' => 'wgfoo---------------------------',
120  'BarFoo' => 'foobar--------------------------',
121  'bad' => 'bad',
122  ], '' );
123 
124  $provider = TestingAccessWrapper::newFromObject( $this->getProvider( null ) );
125  try {
126  $provider->getSessionIdFromCookie( $request );
127  $this->fail( 'Expected exception not thrown' );
128  } catch ( \BadMethodCallException $ex ) {
129  $this->assertSame(
130  'MediaWiki\\Session\\ImmutableSessionProviderWithCookie::getSessionIdFromCookie ' .
131  'may not be called when $this->sessionCookieName === null',
132  $ex->getMessage()
133  );
134  }
135 
136  $provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'Foo' ) );
137  $this->assertSame(
138  'wgfoo---------------------------',
139  $provider->getSessionIdFromCookie( $request )
140  );
141 
142  $provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'Foo', 'Bar' ) );
143  $this->assertSame(
144  'foobar--------------------------',
145  $provider->getSessionIdFromCookie( $request )
146  );
147 
148  $provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'Foo', '' ) );
149  $this->assertSame(
150  'foo-----------------------------',
151  $provider->getSessionIdFromCookie( $request )
152  );
153 
154  $provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'bad', '' ) );
155  $this->assertSame( null, $provider->getSessionIdFromCookie( $request ) );
156 
157  $provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'none', '' ) );
158  $this->assertSame( null, $provider->getSessionIdFromCookie( $request ) );
159  }
160 
161  protected function getSentRequest() {
162  $sentResponse = $this->getMockBuilder( \FauxResponse::class )
163  ->setMethods( [ 'headersSent', 'setCookie', 'header' ] )
164  ->getMock();
165  $sentResponse->expects( $this->any() )->method( 'headersSent' )
166  ->will( $this->returnValue( true ) );
167  $sentResponse->expects( $this->never() )->method( 'setCookie' );
168  $sentResponse->expects( $this->never() )->method( 'header' );
169 
170  $sentRequest = $this->getMockBuilder( \FauxRequest::class )
171  ->setMethods( [ 'response' ] )->getMock();
172  $sentRequest->expects( $this->any() )->method( 'response' )
173  ->will( $this->returnValue( $sentResponse ) );
174  return $sentRequest;
175  }
176 
183  public function testPersistSession( $secure, $remember, $forceHTTPS ) {
184  $this->setMwGlobals( [
185  'wgCookieExpiration' => 100,
186  'wgSecureLogin' => false,
187  'wgForceHTTPS' => $forceHTTPS,
188  ] );
189 
190  $provider = $this->getProvider( 'session', null, $forceHTTPS );
191  $provider->setLogger( new \Psr\Log\NullLogger() );
192  $priv = TestingAccessWrapper::newFromObject( $provider );
193  $priv->sessionCookieOptions = [
194  'prefix' => 'x',
195  'path' => 'CookiePath',
196  'domain' => 'CookieDomain',
197  'secure' => false,
198  'httpOnly' => true,
199  ];
200 
201  $sessionId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
202  $user = User::newFromName( 'UTSysop' );
203  $this->assertSame( $forceHTTPS, $user->requiresHTTPS(), 'sanity check' );
204 
205  $backend = new SessionBackend(
206  new SessionId( $sessionId ),
208  'provider' => $provider,
209  'id' => $sessionId,
210  'persisted' => true,
211  'userInfo' => UserInfo::newFromUser( $user, true ),
212  'idIsSafe' => true,
213  ] ),
214  new TestBagOStuff(),
215  new \Psr\Log\NullLogger(),
216  10
217  );
218  TestingAccessWrapper::newFromObject( $backend )->usePhpSessionHandling = false;
219  $backend->setRememberUser( $remember );
220  $backend->setForceHTTPS( $secure );
221 
222  // No cookie
223  $priv->sessionCookieName = null;
224  $request = new \FauxRequest();
225  $provider->persistSession( $backend, $request );
226  $this->assertSame( [], $request->response()->getCookies() );
227 
228  // Cookie
229  $priv->sessionCookieName = 'session';
230  $request = new \FauxRequest();
231  $time = time();
232  $provider->persistSession( $backend, $request );
233 
234  $cookie = $request->response()->getCookieData( 'xsession' );
235  $this->assertInternalType( 'array', $cookie );
236  if ( isset( $cookie['expire'] ) && $cookie['expire'] > 0 ) {
237  // Round expiry so we don't randomly fail if the seconds ticked during the test.
238  $cookie['expire'] = round( $cookie['expire'] - $time, -2 );
239  }
240  $this->assertEquals( [
241  'value' => $sessionId,
242  'expire' => null,
243  'path' => 'CookiePath',
244  'domain' => 'CookieDomain',
245  'secure' => $secure || $forceHTTPS,
246  'httpOnly' => true,
247  'raw' => false,
248  ], $cookie );
249 
250  $cookie = $request->response()->getCookieData( 'forceHTTPS' );
251  if ( $secure && !$forceHTTPS ) {
252  $this->assertInternalType( 'array', $cookie );
253  if ( isset( $cookie['expire'] ) && $cookie['expire'] > 0 ) {
254  // Round expiry so we don't randomly fail if the seconds ticked during the test.
255  $cookie['expire'] = round( $cookie['expire'] - $time, -2 );
256  }
257  $this->assertEquals( [
258  'value' => 'true',
259  'expire' => null,
260  'path' => 'CookiePath',
261  'domain' => 'CookieDomain',
262  'secure' => false,
263  'httpOnly' => true,
264  'raw' => false,
265  ], $cookie );
266  } else {
267  $this->assertNull( $cookie );
268  }
269 
270  // Headers sent
271  $request = $this->getSentRequest();
272  $provider->persistSession( $backend, $request );
273  $this->assertSame( [], $request->response()->getCookies() );
274  }
275 
276  public static function providePersistSession() {
277  return \ArrayUtils::cartesianProduct(
278  [ false, true ], // $secure
279  [ false, true ], // $remember
280  [ false, true ] // $forceHTTPS
281  );
282  }
283 
284  public function testUnpersistSession() {
285  $provider = $this->getProvider( 'session', '' );
286  $provider->setLogger( new \Psr\Log\NullLogger() );
287  $priv = TestingAccessWrapper::newFromObject( $provider );
288 
289  // No cookie
290  $priv->sessionCookieName = null;
291  $request = new \FauxRequest();
292  $provider->unpersistSession( $request );
293  $this->assertSame( null, $request->response()->getCookie( 'session', '' ) );
294 
295  // Cookie
296  $priv->sessionCookieName = 'session';
297  $request = new \FauxRequest();
298  $provider->unpersistSession( $request );
299  $this->assertSame( '', $request->response()->getCookie( 'session', '' ) );
300 
301  // Headers sent
302  $request = $this->getSentRequest();
303  $provider->unpersistSession( $request );
304  $this->assertSame( null, $request->response()->getCookie( 'session', '' ) );
305  }
306 
307 }
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1795
$user
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 account $user
Definition: hooks.txt:247
MediaWiki\Session\ImmutableSessionProviderWithCookieTest\testBasics
testBasics()
Definition: ImmutableSessionProviderWithCookieTest.php:85
MediaWiki\Session\ImmutableSessionProviderWithCookieTest\getProvider
getProvider( $name, $prefix=null, $forceHTTPS=false)
Definition: ImmutableSessionProviderWithCookieTest.php:16
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
TestLogger
A logger that may be configured to either buffer logs or to print them to the output where PHPUnit wi...
Definition: TestLogger.php:33
$params
$params
Definition: styleTest.css.php:40
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:591
User
User
Definition: All_system_messages.txt:425
MediaWiki\Session\UserInfo\newFromUser
static newFromUser(User $user, $verified=false)
Create an instance from an existing User object.
Definition: UserInfo.php:116
php
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
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
Definition: MediaWikiTestCase.php:678
MediaWiki\Session\ImmutableSessionProviderWithCookieTest\providePersistSession
static providePersistSession()
Definition: ImmutableSessionProviderWithCookieTest.php:276
MediaWikiTestCase
Definition: MediaWikiTestCase.php:17
MediaWiki\Session\ImmutableSessionProviderWithCookieTest
Session Database MediaWiki\Session\ImmutableSessionProviderWithCookie.
Definition: ImmutableSessionProviderWithCookieTest.php:14
MediaWiki\Session
Definition: BotPasswordSessionProvider.php:24
MediaWiki\Session\ImmutableSessionProviderWithCookieTest\getSentRequest
getSentRequest()
Definition: ImmutableSessionProviderWithCookieTest.php:161
MediaWiki\Session\ImmutableSessionProviderWithCookieTest\testGetVaryCookies
testGetVaryCookies()
Definition: ImmutableSessionProviderWithCookieTest.php:99
MediaWiki\Session\ImmutableSessionProviderWithCookieTest\testUnpersistSession
testUnpersistSession()
Definition: ImmutableSessionProviderWithCookieTest.php:284
MediaWiki\Session\TestBagOStuff
BagOStuff with utility functions for MediaWiki\\Session\\* testing.
Definition: TestBagOStuff.php:8
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:50
MediaWiki\Session\ImmutableSessionProviderWithCookieTest\testPersistSession
testPersistSession( $secure, $remember, $forceHTTPS)
providePersistSession
Definition: ImmutableSessionProviderWithCookieTest.php:183
MediaWiki\Session\ImmutableSessionProviderWithCookieTest\testGetSessionIdFromCookie
testGetSessionIdFromCookie()
Definition: ImmutableSessionProviderWithCookieTest.php:113
MediaWiki\Session\ImmutableSessionProviderWithCookieTest\testConstructor
testConstructor()
Definition: ImmutableSessionProviderWithCookieTest.php:39
MediaWiki\Session\SessionInfo
Value object returned by SessionProvider.
Definition: SessionInfo.php:34
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
MediaWiki\Session\SessionId
Value object holding the session ID in a manner that can be globally updated.
Definition: SessionId.php:38
MediaWiki\$config
Config $config
Definition: MediaWiki.php:43
class
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:56
$request
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2806
MediaWiki\Session\SessionInfo\MIN_PRIORITY
const MIN_PRIORITY
Minimum allowed priority.
Definition: SessionInfo.php:36
MediaWiki\Session\SessionBackend
This is the actual workhorse for Session.
Definition: SessionBackend.php:49