Merge "Make LBFactory::waitForReplication() mask wait latency with callbacks"
[lhc/web/wiklou.git] / tests / phpunit / includes / user / BotPasswordTest.php
1 <?php
2
3 use MediaWiki\Session\SessionManager;
4
5 /**
6 * @covers BotPassword
7 * @group Database
8 */
9 class BotPasswordTest extends MediaWikiTestCase {
10
11 /** @var TestUser */
12 private $testUser;
13
14 /** @var string */
15 private $testUserName;
16
17 protected function setUp() {
18 parent::setUp();
19
20 $this->setMwGlobals( [
21 'wgEnableBotPasswords' => true,
22 'wgBotPasswordsDatabase' => false,
23 'wgCentralIdLookupProvider' => 'BotPasswordTest OkMock',
24 'wgGrantPermissions' => [
25 'test' => [ 'read' => true ],
26 ],
27 'wgUserrightsInterwikiDelimiter' => '@',
28 ] );
29
30 $this->testUser = $this->getMutableTestUser();
31 $this->testUserName = $this->testUser->getUser()->getName();
32
33 $mock1 = $this->getMockForAbstractClass( 'CentralIdLookup' );
34 $mock1->expects( $this->any() )->method( 'isAttached' )
35 ->will( $this->returnValue( true ) );
36 $mock1->expects( $this->any() )->method( 'lookupUserNames' )
37 ->will( $this->returnValue( [ $this->testUserName => 42, 'UTDummy' => 43, 'UTInvalid' => 0 ] ) );
38 $mock1->expects( $this->never() )->method( 'lookupCentralIds' );
39
40 $mock2 = $this->getMockForAbstractClass( 'CentralIdLookup' );
41 $mock2->expects( $this->any() )->method( 'isAttached' )
42 ->will( $this->returnValue( false ) );
43 $mock2->expects( $this->any() )->method( 'lookupUserNames' )
44 ->will( $this->returnArgument( 0 ) );
45 $mock2->expects( $this->never() )->method( 'lookupCentralIds' );
46
47 $this->mergeMwGlobalArrayValue( 'wgCentralIdLookupProviders', [
48 'BotPasswordTest OkMock' => [ 'factory' => function () use ( $mock1 ) {
49 return $mock1;
50 } ],
51 'BotPasswordTest FailMock' => [ 'factory' => function () use ( $mock2 ) {
52 return $mock2;
53 } ],
54 ] );
55
56 CentralIdLookup::resetCache();
57 }
58
59 public function addDBData() {
60 $passwordFactory = new \PasswordFactory();
61 $passwordFactory->init( \RequestContext::getMain()->getConfig() );
62 $passwordHash = $passwordFactory->newFromPlaintext( 'foobaz' );
63
64 $dbw = wfGetDB( DB_MASTER );
65 $dbw->delete(
66 'bot_passwords',
67 [ 'bp_user' => [ 42, 43 ], 'bp_app_id' => 'BotPassword' ],
68 __METHOD__
69 );
70 $dbw->insert(
71 'bot_passwords',
72 [
73 [
74 'bp_user' => 42,
75 'bp_app_id' => 'BotPassword',
76 'bp_password' => $passwordHash->toString(),
77 'bp_token' => 'token!',
78 'bp_restrictions' => '{"IPAddresses":["127.0.0.0/8"]}',
79 'bp_grants' => '["test"]',
80 ],
81 [
82 'bp_user' => 43,
83 'bp_app_id' => 'BotPassword',
84 'bp_password' => $passwordHash->toString(),
85 'bp_token' => 'token!',
86 'bp_restrictions' => '{"IPAddresses":["127.0.0.0/8"]}',
87 'bp_grants' => '["test"]',
88 ],
89 ],
90 __METHOD__
91 );
92 }
93
94 public function testBasics() {
95 $user = $this->testUser->getUser();
96 $bp = BotPassword::newFromUser( $user, 'BotPassword' );
97 $this->assertInstanceOf( 'BotPassword', $bp );
98 $this->assertTrue( $bp->isSaved() );
99 $this->assertSame( 42, $bp->getUserCentralId() );
100 $this->assertSame( 'BotPassword', $bp->getAppId() );
101 $this->assertSame( 'token!', trim( $bp->getToken(), " \0" ) );
102 $this->assertEquals( '{"IPAddresses":["127.0.0.0/8"]}', $bp->getRestrictions()->toJson() );
103 $this->assertSame( [ 'test' ], $bp->getGrants() );
104
105 $this->assertNull( BotPassword::newFromUser( $user, 'DoesNotExist' ) );
106
107 $this->setMwGlobals( [
108 'wgCentralIdLookupProvider' => 'BotPasswordTest FailMock'
109 ] );
110 $this->assertNull( BotPassword::newFromUser( $user, 'BotPassword' ) );
111
112 $this->assertSame( '@', BotPassword::getSeparator() );
113 $this->setMwGlobals( [
114 'wgUserrightsInterwikiDelimiter' => '#',
115 ] );
116 $this->assertSame( '#', BotPassword::getSeparator() );
117 }
118
119 public function testUnsaved() {
120 $user = $this->testUser->getUser();
121 $bp = BotPassword::newUnsaved( [
122 'user' => $user,
123 'appId' => 'DoesNotExist'
124 ] );
125 $this->assertInstanceOf( 'BotPassword', $bp );
126 $this->assertFalse( $bp->isSaved() );
127 $this->assertSame( 42, $bp->getUserCentralId() );
128 $this->assertSame( 'DoesNotExist', $bp->getAppId() );
129 $this->assertEquals( MWRestrictions::newDefault(), $bp->getRestrictions() );
130 $this->assertSame( [], $bp->getGrants() );
131
132 $bp = BotPassword::newUnsaved( [
133 'username' => 'UTDummy',
134 'appId' => 'DoesNotExist2',
135 'restrictions' => MWRestrictions::newFromJson( '{"IPAddresses":["127.0.0.0/8"]}' ),
136 'grants' => [ 'test' ],
137 ] );
138 $this->assertInstanceOf( 'BotPassword', $bp );
139 $this->assertFalse( $bp->isSaved() );
140 $this->assertSame( 43, $bp->getUserCentralId() );
141 $this->assertSame( 'DoesNotExist2', $bp->getAppId() );
142 $this->assertEquals( '{"IPAddresses":["127.0.0.0/8"]}', $bp->getRestrictions()->toJson() );
143 $this->assertSame( [ 'test' ], $bp->getGrants() );
144
145 $user = $this->testUser->getUser();
146 $bp = BotPassword::newUnsaved( [
147 'centralId' => 45,
148 'appId' => 'DoesNotExist'
149 ] );
150 $this->assertInstanceOf( 'BotPassword', $bp );
151 $this->assertFalse( $bp->isSaved() );
152 $this->assertSame( 45, $bp->getUserCentralId() );
153 $this->assertSame( 'DoesNotExist', $bp->getAppId() );
154
155 $user = $this->testUser->getUser();
156 $bp = BotPassword::newUnsaved( [
157 'user' => $user,
158 'appId' => 'BotPassword'
159 ] );
160 $this->assertInstanceOf( 'BotPassword', $bp );
161 $this->assertFalse( $bp->isSaved() );
162
163 $this->assertNull( BotPassword::newUnsaved( [
164 'user' => $user,
165 'appId' => '',
166 ] ) );
167 $this->assertNull( BotPassword::newUnsaved( [
168 'user' => $user,
169 'appId' => str_repeat( 'X', BotPassword::APPID_MAXLENGTH + 1 ),
170 ] ) );
171 $this->assertNull( BotPassword::newUnsaved( [
172 'user' => $this->testUserName,
173 'appId' => 'Ok',
174 ] ) );
175 $this->assertNull( BotPassword::newUnsaved( [
176 'username' => 'UTInvalid',
177 'appId' => 'Ok',
178 ] ) );
179 $this->assertNull( BotPassword::newUnsaved( [
180 'appId' => 'Ok',
181 ] ) );
182 }
183
184 public function testGetPassword() {
185 $bp = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
186
187 $password = $bp->getPassword();
188 $this->assertInstanceOf( 'Password', $password );
189 $this->assertTrue( $password->equals( 'foobaz' ) );
190
191 $bp->centralId = 44;
192 $password = $bp->getPassword();
193 $this->assertInstanceOf( 'InvalidPassword', $password );
194
195 $bp = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
196 $dbw = wfGetDB( DB_MASTER );
197 $dbw->update(
198 'bot_passwords',
199 [ 'bp_password' => 'garbage' ],
200 [ 'bp_user' => 42, 'bp_app_id' => 'BotPassword' ],
201 __METHOD__
202 );
203 $password = $bp->getPassword();
204 $this->assertInstanceOf( 'InvalidPassword', $password );
205 }
206
207 public function testInvalidateAllPasswordsForUser() {
208 $bp1 = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
209 $bp2 = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 43, 'BotPassword' ) );
210
211 $this->assertNotInstanceOf( 'InvalidPassword', $bp1->getPassword(), 'sanity check' );
212 $this->assertNotInstanceOf( 'InvalidPassword', $bp2->getPassword(), 'sanity check' );
213 BotPassword::invalidateAllPasswordsForUser( $this->testUserName );
214 $this->assertInstanceOf( 'InvalidPassword', $bp1->getPassword() );
215 $this->assertNotInstanceOf( 'InvalidPassword', $bp2->getPassword() );
216
217 $bp = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
218 $this->assertInstanceOf( 'InvalidPassword', $bp->getPassword() );
219 }
220
221 public function testRemoveAllPasswordsForUser() {
222 $this->assertNotNull( BotPassword::newFromCentralId( 42, 'BotPassword' ), 'sanity check' );
223 $this->assertNotNull( BotPassword::newFromCentralId( 43, 'BotPassword' ), 'sanity check' );
224
225 BotPassword::removeAllPasswordsForUser( $this->testUserName );
226
227 $this->assertNull( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
228 $this->assertNotNull( BotPassword::newFromCentralId( 43, 'BotPassword' ) );
229 }
230
231 /**
232 * @dataProvider provideCanonicalizeLoginData
233 */
234 public function testCanonicalizeLoginData( $username, $password, $expectedResult ) {
235 $result = BotPassword::canonicalizeLoginData( $username, $password );
236 if ( is_array( $expectedResult ) ) {
237 $this->assertArrayEquals( $expectedResult, $result, true, true );
238 } else {
239 $this->assertSame( $expectedResult, $result );
240 }
241 }
242
243 public function provideCanonicalizeLoginData() {
244 return [
245 [ 'user', 'pass', false ],
246 [ 'user', 'abc@def', false ],
247 [ 'user@bot', '12345678901234567890123456789012',
248 [ 'user@bot', '12345678901234567890123456789012', false ] ],
249 [ 'user', 'bot@12345678901234567890123456789012',
250 [ 'user@bot', '12345678901234567890123456789012', true ] ],
251 [ 'user', 'bot@12345678901234567890123456789012345',
252 [ 'user@bot', '12345678901234567890123456789012345', true ] ],
253 [ 'user', 'bot@x@12345678901234567890123456789012',
254 [ 'user@bot@x', '12345678901234567890123456789012', true ] ],
255 ];
256 }
257
258 public function testLogin() {
259 // Test failure when bot passwords aren't enabled
260 $this->setMwGlobals( 'wgEnableBotPasswords', false );
261 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', new FauxRequest );
262 $this->assertEquals( Status::newFatal( 'botpasswords-disabled' ), $status );
263 $this->setMwGlobals( 'wgEnableBotPasswords', true );
264
265 // Test failure when BotPasswordSessionProvider isn't configured
266 $manager = new SessionManager( [
267 'logger' => new Psr\Log\NullLogger,
268 'store' => new EmptyBagOStuff,
269 ] );
270 $reset = MediaWiki\Session\TestUtils::setSessionManagerSingleton( $manager );
271 $this->assertNull(
272 $manager->getProvider( MediaWiki\Session\BotPasswordSessionProvider::class ),
273 'sanity check'
274 );
275 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', new FauxRequest );
276 $this->assertEquals( Status::newFatal( 'botpasswords-no-provider' ), $status );
277 ScopedCallback::consume( $reset );
278
279 // Now configure BotPasswordSessionProvider for further tests...
280 $mainConfig = RequestContext::getMain()->getConfig();
281 $config = new HashConfig( [
282 'SessionProviders' => $mainConfig->get( 'SessionProviders' ) + [
283 MediaWiki\Session\BotPasswordSessionProvider::class => [
284 'class' => MediaWiki\Session\BotPasswordSessionProvider::class,
285 'args' => [ [ 'priority' => 40 ] ],
286 ]
287 ],
288 ] );
289 $manager = new SessionManager( [
290 'config' => new MultiConfig( [ $config, RequestContext::getMain()->getConfig() ] ),
291 'logger' => new Psr\Log\NullLogger,
292 'store' => new EmptyBagOStuff,
293 ] );
294 $reset = MediaWiki\Session\TestUtils::setSessionManagerSingleton( $manager );
295
296 // No "@"-thing in the username
297 $status = BotPassword::login( $this->testUserName, 'foobaz', new FauxRequest );
298 $this->assertEquals( Status::newFatal( 'botpasswords-invalid-name', '@' ), $status );
299
300 // No base user
301 $status = BotPassword::login( 'UTDummy@BotPassword', 'foobaz', new FauxRequest );
302 $this->assertEquals( Status::newFatal( 'nosuchuser', 'UTDummy' ), $status );
303
304 // No bot password
305 $status = BotPassword::login( "{$this->testUserName}@DoesNotExist", 'foobaz', new FauxRequest );
306 $this->assertEquals(
307 Status::newFatal( 'botpasswords-not-exist', $this->testUserName, 'DoesNotExist' ),
308 $status
309 );
310
311 // Failed restriction
312 $request = $this->getMock( 'FauxRequest', [ 'getIP' ] );
313 $request->expects( $this->any() )->method( 'getIP' )
314 ->will( $this->returnValue( '10.0.0.1' ) );
315 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', $request );
316 $this->assertEquals( Status::newFatal( 'botpasswords-restriction-failed' ), $status );
317
318 // Wrong password
319 $status = BotPassword::login(
320 "{$this->testUserName}@BotPassword", $this->testUser->getPassword(), new FauxRequest );
321 $this->assertEquals( Status::newFatal( 'wrongpassword' ), $status );
322
323 // Success!
324 $request = new FauxRequest;
325 $this->assertNotInstanceOf(
326 MediaWiki\Session\BotPasswordSessionProvider::class,
327 $request->getSession()->getProvider(),
328 'sanity check'
329 );
330 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', $request );
331 $this->assertInstanceOf( 'Status', $status );
332 $this->assertTrue( $status->isGood() );
333 $session = $status->getValue();
334 $this->assertInstanceOf( MediaWiki\Session\Session::class, $session );
335 $this->assertInstanceOf(
336 MediaWiki\Session\BotPasswordSessionProvider::class, $session->getProvider()
337 );
338 $this->assertSame( $session->getId(), $request->getSession()->getId() );
339
340 ScopedCallback::consume( $reset );
341 }
342
343 /**
344 * @dataProvider provideSave
345 * @param string|null $password
346 */
347 public function testSave( $password ) {
348 $passwordFactory = new \PasswordFactory();
349 $passwordFactory->init( \RequestContext::getMain()->getConfig() );
350
351 $bp = BotPassword::newUnsaved( [
352 'centralId' => 42,
353 'appId' => 'TestSave',
354 'restrictions' => MWRestrictions::newFromJson( '{"IPAddresses":["127.0.0.0/8"]}' ),
355 'grants' => [ 'test' ],
356 ] );
357 $this->assertFalse( $bp->isSaved(), 'sanity check' );
358 $this->assertNull(
359 BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST ), 'sanity check'
360 );
361
362 $passwordHash = $password ? $passwordFactory->newFromPlaintext( $password ) : null;
363 $this->assertFalse( $bp->save( 'update', $passwordHash ) );
364 $this->assertTrue( $bp->save( 'insert', $passwordHash ) );
365 $bp2 = BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST );
366 $this->assertInstanceOf( 'BotPassword', $bp2 );
367 $this->assertEquals( $bp->getUserCentralId(), $bp2->getUserCentralId() );
368 $this->assertEquals( $bp->getAppId(), $bp2->getAppId() );
369 $this->assertEquals( $bp->getToken(), $bp2->getToken() );
370 $this->assertEquals( $bp->getRestrictions(), $bp2->getRestrictions() );
371 $this->assertEquals( $bp->getGrants(), $bp2->getGrants() );
372 $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
373 if ( $password === null ) {
374 $this->assertInstanceOf( 'InvalidPassword', $pw );
375 } else {
376 $this->assertTrue( $pw->equals( $password ) );
377 }
378
379 $token = $bp->getToken();
380 $this->assertFalse( $bp->save( 'insert' ) );
381 $this->assertTrue( $bp->save( 'update' ) );
382 $this->assertNotEquals( $token, $bp->getToken() );
383 $bp2 = BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST );
384 $this->assertInstanceOf( 'BotPassword', $bp2 );
385 $this->assertEquals( $bp->getToken(), $bp2->getToken() );
386 $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
387 if ( $password === null ) {
388 $this->assertInstanceOf( 'InvalidPassword', $pw );
389 } else {
390 $this->assertTrue( $pw->equals( $password ) );
391 }
392
393 $passwordHash = $passwordFactory->newFromPlaintext( 'XXX' );
394 $token = $bp->getToken();
395 $this->assertTrue( $bp->save( 'update', $passwordHash ) );
396 $this->assertNotEquals( $token, $bp->getToken() );
397 $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
398 $this->assertTrue( $pw->equals( 'XXX' ) );
399
400 $this->assertTrue( $bp->delete() );
401 $this->assertFalse( $bp->isSaved() );
402 $this->assertNull( BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST ) );
403
404 $this->assertFalse( $bp->save( 'foobar' ) );
405 }
406
407 public static function provideSave() {
408 return [
409 [ null ],
410 [ 'foobar' ],
411 ];
412 }
413 }