File: ImmutableSessionProviderWithCookieTest.php

package info (click to toggle)
mediawiki 1%3A1.43.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 417,464 kB
  • sloc: php: 1,062,949; javascript: 664,290; sql: 9,714; python: 5,458; xml: 3,489; sh: 1,131; makefile: 64
file content (320 lines) | stat: -rw-r--r-- 10,451 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
<?php

namespace MediaWiki\Tests\Session;

use ArrayUtils;
use BadMethodCallException;
use InvalidArgumentException;
use MediaWiki\Config\HashConfig;
use MediaWiki\MainConfigNames;
use MediaWiki\Message\Message;
use MediaWiki\Request\FauxRequest;
use MediaWiki\Request\FauxResponse;
use MediaWiki\Session\ImmutableSessionProviderWithCookie;
use MediaWiki\Session\SessionBackend;
use MediaWiki\Session\SessionId;
use MediaWiki\Session\SessionInfo;
use MediaWiki\Session\SessionManager;
use MediaWiki\Session\UserInfo;
use MediaWikiIntegrationTestCase;
use Psr\Log\NullLogger;
use TestLogger;
use Wikimedia\TestingAccessWrapper;

/**
 * @group Session
 * @group Database
 * @covers \MediaWiki\Session\ImmutableSessionProviderWithCookie
 */
class ImmutableSessionProviderWithCookieTest extends MediaWikiIntegrationTestCase {
	use SessionProviderTestTrait;

	private function getProvider( $name, $prefix = null, $forceHTTPS = false, $logger = null ) {
		$config = new HashConfig();
		$config->set( MainConfigNames::CookiePrefix, 'wgCookiePrefix' );
		$config->set( MainConfigNames::ForceHTTPS, $forceHTTPS );

		$params = [
			'sessionCookieName' => $name,
			'sessionCookieOptions' => [],
		];
		if ( $prefix !== null ) {
			$params['sessionCookieOptions']['prefix'] = $prefix;
		}

		$provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
			->setConstructorArgs( [ $params ] )
			->getMockForAbstractClass();
		$this->initProvider( $provider, $logger ?? new TestLogger(), $config, new SessionManager() );

		return $provider;
	}

	public function testConstructor() {
		$provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
			->getMockForAbstractClass();
		$priv = TestingAccessWrapper::newFromObject( $provider );
		$this->assertNull( $priv->sessionCookieName );
		$this->assertSame( [], $priv->sessionCookieOptions );

		$provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
			->setConstructorArgs( [ [
				'sessionCookieName' => 'Foo',
				'sessionCookieOptions' => [ 'Bar' ],
			] ] )
			->getMockForAbstractClass();
		$priv = TestingAccessWrapper::newFromObject( $provider );
		$this->assertSame( 'Foo', $priv->sessionCookieName );
		$this->assertSame( [ 'Bar' ], $priv->sessionCookieOptions );

		try {
			$provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
				->setConstructorArgs( [ [
					'sessionCookieName' => false,
				] ] )
				->getMockForAbstractClass();
			$this->fail( 'Expected exception not thrown' );
		} catch ( InvalidArgumentException $ex ) {
			$this->assertSame(
				'sessionCookieName must be a string',
				$ex->getMessage()
			);
		}

		try {
			$provider = $this->getMockBuilder( ImmutableSessionProviderWithCookie::class )
				->setConstructorArgs( [ [
					'sessionCookieOptions' => 'x',
				] ] )
				->getMockForAbstractClass();
			$this->fail( 'Expected exception not thrown' );
		} catch ( InvalidArgumentException $ex ) {
			$this->assertSame(
				'sessionCookieOptions must be an array',
				$ex->getMessage()
			);
		}
	}

	public function testBasics() {
		$provider = $this->getProvider( null );
		$this->assertFalse( $provider->persistsSessionId() );
		$this->assertFalse( $provider->canChangeUser() );

		$provider = $this->getProvider( 'Foo' );
		$this->assertTrue( $provider->persistsSessionId() );
		$this->assertFalse( $provider->canChangeUser() );

		$msg = $provider->whyNoSession();
		$this->assertInstanceOf( Message::class, $msg );
		$this->assertSame( 'sessionprovider-nocookies', $msg->getKey() );
	}

	public function testGetVaryCookies() {
		$provider = $this->getProvider( null );
		$this->assertSame( [], $provider->getVaryCookies() );

		$provider = $this->getProvider( 'Foo' );
		$this->assertSame( [ 'wgCookiePrefixFoo' ], $provider->getVaryCookies() );

		$provider = $this->getProvider( 'Foo', 'Bar' );
		$this->assertSame( [ 'BarFoo' ], $provider->getVaryCookies() );

		$provider = $this->getProvider( 'Foo', '' );
		$this->assertSame( [ 'Foo' ], $provider->getVaryCookies() );
	}

	public function testGetSessionIdFromCookie() {
		$this->overrideConfigValue( MainConfigNames::CookiePrefix, 'wgCookiePrefix' );
		$request = new FauxRequest();
		$request->setCookies( [
			'' => 'empty---------------------------',
			'Foo' => 'foo-----------------------------',
			'wgCookiePrefixFoo' => 'wgfoo---------------------------',
			'BarFoo' => 'foobar--------------------------',
			'bad' => 'bad',
		], '' );

		$provider = TestingAccessWrapper::newFromObject( $this->getProvider( null ) );
		try {
			$provider->getSessionIdFromCookie( $request );
			$this->fail( 'Expected exception not thrown' );
		} catch ( BadMethodCallException $ex ) {
			$this->assertSame(
				'MediaWiki\\Session\\ImmutableSessionProviderWithCookie::getSessionIdFromCookie ' .
					'may not be called when $this->sessionCookieName === null',
				$ex->getMessage()
			);
		}

		$provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'Foo' ) );
		$this->assertSame(
			'wgfoo---------------------------',
			$provider->getSessionIdFromCookie( $request )
		);

		$provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'Foo', 'Bar' ) );
		$this->assertSame(
			'foobar--------------------------',
			$provider->getSessionIdFromCookie( $request )
		);

		$provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'Foo', '' ) );
		$this->assertSame(
			'foo-----------------------------',
			$provider->getSessionIdFromCookie( $request )
		);

		$provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'bad', '' ) );
		$this->assertSame( null, $provider->getSessionIdFromCookie( $request ) );

		$provider = TestingAccessWrapper::newFromObject( $this->getProvider( 'none', '' ) );
		$this->assertSame( null, $provider->getSessionIdFromCookie( $request ) );
	}

	protected function getSentRequest() {
		$sentResponse = $this->getMockBuilder( FauxResponse::class )
			->onlyMethods( [ 'headersSent', 'setCookie', 'header' ] )
			->getMock();
		$sentResponse->method( 'headersSent' )
			->willReturn( true );
		$sentResponse->expects( $this->never() )->method( 'setCookie' );
		$sentResponse->expects( $this->never() )->method( 'header' );

		$sentRequest = $this->getMockBuilder( FauxRequest::class )
			->onlyMethods( [ 'response' ] )->getMock();
		$sentRequest->method( 'response' )
			->willReturn( $sentResponse );
		return $sentRequest;
	}

	/**
	 * @dataProvider providePersistSession
	 * @param bool $secure
	 * @param bool $remember
	 * @param bool $forceHTTPS
	 */
	public function testPersistSession( $secure, $remember, $forceHTTPS ) {
		$this->overrideConfigValues( [
			MainConfigNames::CookieExpiration => 100,
			MainConfigNames::SecureLogin => false,
			MainConfigNames::ForceHTTPS => $forceHTTPS,
		] );

		$provider = $this->getProvider( 'session', null, $forceHTTPS, new NullLogger() );
		$priv = TestingAccessWrapper::newFromObject( $provider );
		$priv->sessionCookieOptions = [
			'prefix' => 'x',
			'path' => 'CookiePath',
			'domain' => 'CookieDomain',
			'secure' => false,
			'httpOnly' => true,
		];

		$sessionId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
		$user = $this->getTestSysop()->getUser();
		$this->assertSame( $forceHTTPS, $user->requiresHTTPS() );

		$backend = new SessionBackend(
			new SessionId( $sessionId ),
			new SessionInfo( SessionInfo::MIN_PRIORITY, [
				'provider' => $provider,
				'id' => $sessionId,
				'persisted' => true,
				'userInfo' => UserInfo::newFromUser( $user, true ),
				'idIsSafe' => true,
			] ),
			new TestBagOStuff(),
			new NullLogger(),
			$this->createHookContainer(),
			10
		);
		TestingAccessWrapper::newFromObject( $backend )->usePhpSessionHandling = false;
		$backend->setRememberUser( $remember );
		$backend->setForceHTTPS( $secure );

		// No cookie
		$priv->sessionCookieName = null;
		$request = new FauxRequest();
		$provider->persistSession( $backend, $request );
		$this->assertSame( [], $request->response()->getCookies() );

		// Cookie
		$priv->sessionCookieName = 'session';
		$request = new FauxRequest();
		$time = time();
		$provider->persistSession( $backend, $request );

		$cookie = $request->response()->getCookieData( 'xsession' );
		$this->assertIsArray( $cookie );
		if ( isset( $cookie['expire'] ) && $cookie['expire'] > 0 ) {
			// Round expiry so we don't randomly fail if the seconds ticked during the test.
			$cookie['expire'] = round( $cookie['expire'] - $time, -2 );
		}
		$this->assertEquals( [
			'value' => $sessionId,
			'expire' => null,
			'path' => 'CookiePath',
			'domain' => 'CookieDomain',
			'secure' => $secure || $forceHTTPS,
			'httpOnly' => true,
			'raw' => false,
		], $cookie );

		$cookie = $request->response()->getCookieData( 'forceHTTPS' );
		if ( $secure && !$forceHTTPS ) {
			$this->assertIsArray( $cookie );
			if ( isset( $cookie['expire'] ) && $cookie['expire'] > 0 ) {
				// Round expiry so we don't randomly fail if the seconds ticked during the test.
				$cookie['expire'] = round( $cookie['expire'] - $time, -2 );
			}
			$this->assertEquals( [
				'value' => 'true',
				'expire' => null,
				'path' => 'CookiePath',
				'domain' => 'CookieDomain',
				'secure' => false,
				'httpOnly' => true,
				'raw' => false,
			], $cookie );
		} else {
			$this->assertNull( $cookie );
		}

		// Headers sent
		$request = $this->getSentRequest();
		$provider->persistSession( $backend, $request );
		$this->assertSame( [], $request->response()->getCookies() );
	}

	public static function providePersistSession() {
		return ArrayUtils::cartesianProduct(
			[ false, true ], // $secure
			[ false, true ], // $remember
			[ false, true ] // $forceHTTPS
		);
	}

	public function testUnpersistSession() {
		$provider = $this->getProvider( 'session', '', false, new NullLogger() );
		$priv = TestingAccessWrapper::newFromObject( $provider );

		// No cookie
		$priv->sessionCookieName = null;
		$request = new FauxRequest();
		$provider->unpersistSession( $request );
		$this->assertSame( null, $request->response()->getCookie( 'session', '' ) );

		// Cookie
		$priv->sessionCookieName = 'session';
		$request = new FauxRequest();
		$provider->unpersistSession( $request );
		$this->assertSame( '', $request->response()->getCookie( 'session', '' ) );

		// Headers sent
		$request = $this->getSentRequest();
		$provider->unpersistSession( $request );
		$this->assertSame( null, $request->response()->getCookie( 'session', '' ) );
	}

}