Debian Codegraph @

tests/phpunit/includes/user/BotPasswordTest.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Config\HashConfig;
4 use MediaWiki\Config\MultiConfig;
5 use MediaWiki\MainConfigNames;
6 use MediaWiki\Password\InvalidPassword;
7 use MediaWiki\Password\Password;
8 use MediaWiki\Request\FauxRequest;
9 use MediaWiki\Session\SessionManager;
10 use MediaWiki\Status\Status;
11 use MediaWiki\Tests\Session\TestUtils;
12 use MediaWiki\User\BotPassword;
13 use MediaWiki\User\CentralId\CentralIdLookup;
14 use Wikimedia\ObjectCache\EmptyBagOStuff;
15 use Wikimedia\Rdbms\IDBAccessObject;
16 use Wikimedia\ScopedCallback;
17 use Wikimedia\TestingAccessWrapper;
18
19 /**
20 * @covers \MediaWiki\User\BotPassword
21 * @group Database
22 */
23 class BotPasswordTest extends MediaWikiIntegrationTestCase {
24
25 /** @var TestUser */
26 private $testUser;
27
28 /** @var string */
29 private $testUserName;
30
31 protected function setUp(): void {
32 parent::setUp();
33
34 $this->overrideConfigValues( [
35 MainConfigNames::EnableBotPasswords => true,
36 MainConfigNames::CentralIdLookupProvider => 'BotPasswordTest OkMock',
37 MainConfigNames::GrantPermissions => [
38 'test' => [ 'read' => true ],
39 ],
40 MainConfigNames::UserrightsInterwikiDelimiter => '@',
41 ] );
42
43 $this->testUser = $this->getMutableTestUser();
44 $this->testUserName = $this->testUser->getUser()->getName();
45
46 $mock1 = $this->getMockForAbstractClass( CentralIdLookup::class );
47 $mock1->method( 'isAttached' )
48 ->willReturn( true );
49 $mock1->method( 'lookupUserNames' )
50 ->willReturn( [ $this->testUserName => 42, 'UTDummy' => 43, 'UTInvalid' => 0 ] );
51 $mock1->expects( $this->never() )->method( 'lookupCentralIds' );
52
53 $mock2 = $this->getMockForAbstractClass( CentralIdLookup::class );
54 $mock2->method( 'isAttached' )
55 ->willReturn( false );
56 $mock2->method( 'lookupUserNames' )
57 ->willReturnArgument( 0 );
58 $mock2->expects( $this->never() )->method( 'lookupCentralIds' );
59
60 $this->mergeMwGlobalArrayValue( 'wgCentralIdLookupProviders', [
61 'BotPasswordTest OkMock' => [ 'factory' => static function () use ( $mock1 ) {
62 return $mock1;
63 } ],
64 'BotPasswordTest FailMock' => [ 'factory' => static function () use ( $mock2 ) {
65 return $mock2;
66 } ],
67 ] );
68 }
69
70 public function addDBData() {
71 $passwordFactory = $this->getServiceContainer()->getPasswordFactory();
72 $passwordHash = $passwordFactory->newFromPlaintext( 'foobaz' );
73
74 $dbw = $this->getDb();
75 $dbw->newDeleteQueryBuilder()
76 ->deleteFrom( 'bot_passwords' )
77 ->where( [ 'bp_user' => [ 42, 43 ], 'bp_app_id' => 'BotPassword' ] )
78 ->caller( __METHOD__ )->execute();
79 $dbw->newInsertQueryBuilder()
80 ->insertInto( 'bot_passwords' )
81 ->row( [
82 'bp_user' => 42,
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 ->row( [
90 'bp_user' => 43,
91 'bp_app_id' => 'BotPassword',
92 'bp_password' => $passwordHash->toString(),
93 'bp_token' => 'token!',
94 'bp_restrictions' => '{"IPAddresses":["127.0.0.0/8"]}',
95 'bp_grants' => '["test"]',
96 ] )
97 ->caller( __METHOD__ )
98 ->execute();
99 }
100
101 public function testBasics() {
102 $user = $this->testUser->getUser();
103 $bp = BotPassword::newFromUser( $user, 'BotPassword' );
104 $this->assertInstanceOf( BotPassword::class, $bp );
105 $this->assertTrue( $bp->isSaved() );
106 $this->assertSame( 42, $bp->getUserCentralId() );
107 $this->assertSame( 'BotPassword', $bp->getAppId() );
108 $this->assertSame( 'token!', trim( $bp->getToken(), " \0" ) );
109 $this->assertEquals( '{"IPAddresses":["127.0.0.0/8"]}', $bp->getRestrictions()->toJson() );
110 $this->assertSame( [ 'test' ], $bp->getGrants() );
111
112 $this->assertNull( BotPassword::newFromUser( $user, 'DoesNotExist' ) );
113
114 $this->overrideConfigValue( MainConfigNames::CentralIdLookupProvider, 'BotPasswordTest FailMock' );
115 $this->assertNull( BotPassword::newFromUser( $user, 'BotPassword' ) );
116
117 $this->assertSame( '@', BotPassword::getSeparator() );
118 $this->overrideConfigValue( MainConfigNames::UserrightsInterwikiDelimiter, '#' );
119 $this->assertSame( '#', BotPassword::getSeparator() );
120 }
121
122 public function testUnsaved() {
123 $user = $this->testUser->getUser();
124 $bp = BotPassword::newUnsaved( [
125 'user' => $user,
126 'appId' => 'DoesNotExist'
127 ] );
128 $this->assertInstanceOf( BotPassword::class, $bp );
129 $this->assertFalse( $bp->isSaved() );
130 $this->assertSame( 42, $bp->getUserCentralId() );
131 $this->assertSame( 'DoesNotExist', $bp->getAppId() );
132 $this->assertEquals( MWRestrictions::newDefault(), $bp->getRestrictions() );
133 $this->assertSame( [], $bp->getGrants() );
134
135 $bp = BotPassword::newUnsaved( [
136 'username' => 'UTDummy',
137 'appId' => 'DoesNotExist2',
138 'restrictions' => MWRestrictions::newFromJson( '{"IPAddresses":["127.0.0.0/8"]}' ),
139 'grants' => [ 'test' ],
140 ] );
141 $this->assertInstanceOf( BotPassword::class, $bp );
142 $this->assertFalse( $bp->isSaved() );
143 $this->assertSame( 43, $bp->getUserCentralId() );
144 $this->assertSame( 'DoesNotExist2', $bp->getAppId() );
145 $this->assertEquals( '{"IPAddresses":["127.0.0.0/8"]}', $bp->getRestrictions()->toJson() );
146 $this->assertSame( [ 'test' ], $bp->getGrants() );
147
148 $bp = BotPassword::newUnsaved( [
149 'centralId' => 45,
150 'appId' => 'DoesNotExist'
151 ] );
152 $this->assertInstanceOf( BotPassword::class, $bp );
153 $this->assertFalse( $bp->isSaved() );
154 $this->assertSame( 45, $bp->getUserCentralId() );
155 $this->assertSame( 'DoesNotExist', $bp->getAppId() );
156
157 $user = $this->testUser->getUser();
158 $bp = BotPassword::newUnsaved( [
159 'user' => $user,
160 'appId' => 'BotPassword'
161 ] );
162 $this->assertInstanceOf( BotPassword::class, $bp );
163 $this->assertFalse( $bp->isSaved() );
164
165 $this->assertNull( BotPassword::newUnsaved( [
166 'user' => $user,
167 'appId' => '',
168 ] ) );
169 $this->assertNull( BotPassword::newUnsaved( [
170 'user' => $user,
171 'appId' => str_repeat( 'X', BotPassword::APPID_MAXLENGTH + 1 ),
172 ] ) );
173 $this->assertNull( BotPassword::newUnsaved( [
174 'user' => $this->testUserName,
175 'appId' => 'Ok',
176 ] ) );
177 $this->assertNull( BotPassword::newUnsaved( [
178 'username' => 'UTInvalid',
179 'appId' => 'Ok',
180 ] ) );
181 $this->assertNull( BotPassword::newUnsaved( [
182 'appId' => 'Ok',
183 ] ) );
184 }
185
186 public function testGetPassword() {
187 /** @var BotPassword $bp */
188 $bp = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
189
190 $password = $bp->getPassword();
191 $this->assertInstanceOf( Password::class, $password );
192 $this->assertTrue( $password->verify( 'foobaz' ) );
193
194 $bp->centralId = 44;
195 $password = $bp->getPassword();
196 $this->assertInstanceOf( InvalidPassword::class, $password );
197
198 $bp = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
199 $dbw = $this->getDb();
200 $dbw->newUpdateQueryBuilder()
201 ->update( 'bot_passwords' )
202 ->set( [ 'bp_password' => 'garbage' ] )
203 ->where( [ 'bp_user' => 42, 'bp_app_id' => 'BotPassword' ] )
204 ->caller( __METHOD__ )->execute();
205 $password = $bp->getPassword();
206 $this->assertInstanceOf( InvalidPassword::class, $password );
207 }
208
209 public function testInvalidateAllPasswordsForUser() {
210 $bp1 = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
211 $bp2 = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 43, 'BotPassword' ) );
212
213 $this->assertNotInstanceOf( InvalidPassword::class, $bp1->getPassword() );
214 $this->assertNotInstanceOf( InvalidPassword::class, $bp2->getPassword() );
215 BotPassword::invalidateAllPasswordsForUser( $this->testUserName );
216 $this->assertInstanceOf( InvalidPassword::class, $bp1->getPassword() );
217 $this->assertNotInstanceOf( InvalidPassword::class, $bp2->getPassword() );
218
219 $bp = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
220 $this->assertInstanceOf( InvalidPassword::class, $bp->getPassword() );
221 }
222
223 public function testRemoveAllPasswordsForUser() {
224 $this->assertNotNull( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
225 $this->assertNotNull( BotPassword::newFromCentralId( 43, 'BotPassword' ) );
226
227 BotPassword::removeAllPasswordsForUser( $this->testUserName );
228
229 $this->assertNull( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
230 $this->assertNotNull( BotPassword::newFromCentralId( 43, 'BotPassword' ) );
231 }
232
233 /**
234 * @dataProvider provideCanonicalizeLoginData
235 */
236 public function testCanonicalizeLoginData( $username, $password, $expectedResult ) {
237 $result = BotPassword::canonicalizeLoginData( $username, $password );
238 if ( is_array( $expectedResult ) ) {
239 $this->assertArrayEquals( $expectedResult, $result, true, true );
240 } else {
241 $this->assertSame( $expectedResult, $result );
242 }
243 }
244
245 public static function provideCanonicalizeLoginData() {
246 return [
247 // T388255
248 [ '', '', false ],
249 [ 'user', '', false ],
250 [ '', '12345678901234567890123456789012', false ],
251 [ 'user', 'pass', false ],
252 [ 'user', 'abc@def', false ],
253 [ 'legacy@user', 'pass', false ],
254 [ 'user@bot', '12345678901234567890123456789012',
255 [ 'user@bot', '12345678901234567890123456789012' ] ],
256 [ 'user', 'bot@12345678901234567890123456789012',
257 [ 'user@bot', '12345678901234567890123456789012' ] ],
258 [ 'user', 'bot@12345678901234567890123456789012345',
259 [ 'user@bot', '12345678901234567890123456789012345' ] ],
260 [ 'user', 'bot@x@12345678901234567890123456789012',
261 [ 'user@bot@x', '12345678901234567890123456789012' ] ],
262 ];
263 }
264
265 public function testLogin() {
266 // Test failure when bot passwords aren't enabled
267 $this->overrideConfigValue( MainConfigNames::EnableBotPasswords, false );
268 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', new FauxRequest );
269 $this->assertEquals( Status::newFatal( 'botpasswords-disabled' ), $status );
270 $this->overrideConfigValue( MainConfigNames::EnableBotPasswords, true );
271
272 // Test failure when BotPasswordSessionProvider isn't configured
273 $manager = new SessionManager( [
274 'logger' => new Psr\Log\NullLogger,
275 'store' => new EmptyBagOStuff,
276 ] );
277 $reset = TestUtils::setSessionManagerSingleton( $manager );
278 $this->assertNull(
279 $manager->getProvider( MediaWiki\Session\BotPasswordSessionProvider::class )
280 );
281 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', new FauxRequest );
282 $this->assertEquals( Status::newFatal( 'botpasswords-no-provider' ), $status );
283 ScopedCallback::consume( $reset );
284
285 // Now configure BotPasswordSessionProvider for further tests...
286 $mainConfig = $this->getServiceContainer()->getMainConfig();
287 $config = new HashConfig( [
288 MainConfigNames::SessionProviders => $mainConfig->get( MainConfigNames::SessionProviders ) + [
289 MediaWiki\Session\BotPasswordSessionProvider::class => [
290 'class' => MediaWiki\Session\BotPasswordSessionProvider::class,
291 'args' => [ [ 'priority' => 40 ] ],
292 'services' => [ 'GrantsInfo' ],
293 ]
294 ],
295 ] );
296 $manager = new SessionManager( [
297 'config' => new MultiConfig( [ $config, $mainConfig ] ),
298 'logger' => new Psr\Log\NullLogger,
299 'store' => new EmptyBagOStuff,
300 ] );
301 $reset = TestUtils::setSessionManagerSingleton( $manager );
302
303 // No "@"-thing in the username
304 $status = BotPassword::login( $this->testUserName, 'foobaz', new FauxRequest );
305 $this->assertStatusError( 'botpasswords-invalid-name', $status );
306
307 // No base user
308 $status = BotPassword::login( 'UTDummy@BotPassword', 'foobaz', new FauxRequest );
309 $this->assertStatusError( 'nosuchuser', $status );
310
311 // No bot password
312 $status = BotPassword::login( "{$this->testUserName}@DoesNotExist", 'foobaz', new FauxRequest );
313 $this->assertStatusError( 'botpasswords-not-exist', $status );
314
315 // Failed restriction
316 $request = $this->getMockBuilder( FauxRequest::class )
317 ->onlyMethods( [ 'getIP' ] )
318 ->getMock();
319 $request->method( 'getIP' )
320 ->willReturn( '10.0.0.1' );
321 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', $request );
322 $this->assertStatusError( 'botpasswords-restriction-failed', $status );
323
324 // Wrong password
325 $status = BotPassword::login(
326 "{$this->testUserName}@BotPassword", $this->testUser->getPassword(), new FauxRequest );
327 $this->assertStatusError( 'wrongpassword', $status );
328
329 // Success!
330 $request = new FauxRequest;
331 $this->assertNotInstanceOf(
332 MediaWiki\Session\BotPasswordSessionProvider::class,
333 $request->getSession()->getProvider()
334 );
335 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', $request );
336 $this->assertInstanceOf( Status::class, $status );
337 $this->assertStatusGood( $status );
338 $session = $status->getValue();
339 $this->assertInstanceOf( MediaWiki\Session\Session::class, $session );
340 $this->assertInstanceOf(
341 MediaWiki\Session\BotPasswordSessionProvider::class, $session->getProvider()
342 );
343 $this->assertSame( $session->getId(), $request->getSession()->getId() );
344
345 ScopedCallback::consume( $reset );
346 }
347
348 /**
349 * @dataProvider provideSave
350 * @param string|null $password
351 */
352 public function testSave( $password ) {
353 $passwordFactory = $this->getServiceContainer()->getPasswordFactory();
354
355 $bp = BotPassword::newUnsaved( [
356 'centralId' => 42,
357 'appId' => 'TestSave',
358 'restrictions' => MWRestrictions::newFromJson( '{"IPAddresses":["127.0.0.0/8"]}' ),
359 'grants' => [ 'test' ],
360 ] );
361 $this->assertFalse( $bp->isSaved() );
362 $this->assertNull(
363 BotPassword::newFromCentralId( 42, 'TestSave', IDBAccessObject::READ_LATEST )
364 );
365
366 $passwordHash = $password ? $passwordFactory->newFromPlaintext( $password ) : null;
367 $this->assertStatusNotOk( $bp->save( 'update', $passwordHash ) );
368 $this->assertStatusGood( $bp->save( 'insert', $passwordHash ) );
369
370 $bp2 = BotPassword::newFromCentralId( 42, 'TestSave', IDBAccessObject::READ_LATEST );
371 $this->assertInstanceOf( BotPassword::class, $bp2 );
372 $this->assertEquals( $bp->getUserCentralId(), $bp2->getUserCentralId() );
373 $this->assertEquals( $bp->getAppId(), $bp2->getAppId() );
374 $this->assertEquals( $bp->getToken(), $bp2->getToken() );
375 $this->assertEquals( $bp->getRestrictions(), $bp2->getRestrictions() );
376 $this->assertEquals( $bp->getGrants(), $bp2->getGrants() );
377
378 /** @var Password $pw */
379 $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
380 if ( $password === null ) {
381 $this->assertInstanceOf( InvalidPassword::class, $pw );
382 } else {
383 $this->assertTrue( $pw->verify( $password ) );
384 }
385
386 $token = $bp->getToken();
387 $this->assertEquals( 42, $bp->getUserCentralId() );
388 $this->assertEquals( 'TestSave', $bp->getAppId() );
389 $this->assertStatusNotOk( $bp->save( 'insert' ) );
390 $this->assertStatusGood( $bp->save( 'update' ) );
391 $this->assertNotEquals( $token, $bp->getToken() );
392
393 $bp2 = BotPassword::newFromCentralId( 42, 'TestSave', IDBAccessObject::READ_LATEST );
394 $this->assertInstanceOf( BotPassword::class, $bp2 );
395 $this->assertEquals( $bp->getToken(), $bp2->getToken() );
396 /** @var Password $pw */
397 $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
398 if ( $password === null ) {
399 $this->assertInstanceOf( InvalidPassword::class, $pw );
400 } else {
401 $this->assertTrue( $pw->verify( $password ) );
402 }
403
404 $passwordHash = $passwordFactory->newFromPlaintext( 'XXX' );
405 $token = $bp->getToken();
406 $this->assertStatusGood( $bp->save( 'update', $passwordHash ) );
407 $this->assertNotEquals( $token, $bp->getToken() );
408
409 /** @var Password $pw */
410 $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
411 $this->assertTrue( $pw->verify( 'XXX' ) );
412
413 $this->assertTrue( $bp->delete() );
414 $this->assertFalse( $bp->isSaved() );
415 $this->assertNull( BotPassword::newFromCentralId( 42, 'TestSave', IDBAccessObject::READ_LATEST ) );
416
417 $this->expectException( UnexpectedValueException::class );
418 $bp->save( 'foobar' )->isGood();
419 }
420
421 public static function provideSave() {
422 return [
423 [ null ],
424 [ 'foobar' ],
425 ];
426 }
427
428 /**
429 * Tests for error handling when bp_restrictions and bp_grants are too long
430 */
431 public function testSaveValidation() {
432 $lotsOfIPs = [
433 'IPAddresses' => array_fill(
434 0,
435 5000,
436 "127.0.0.0/8"
437 )
438 ];
439
440 $bp = BotPassword::newUnsaved( [
441 'centralId' => 42,
442 'appId' => 'TestSave',
443 // When this becomes JSON, it'll be 70,017 characters, which is
444 // greater than BotPassword::GRANTS_MAXLENGTH, so it will cause an error.
445 'restrictions' => MWRestrictions::newFromArray( $lotsOfIPs ),
446 'grants' => [
447 // Maximum length of the JSON is BotPassword::RESTRICTIONS_MAXLENGTH characters.
448 // So one long grant name should be good. Turning it into JSON will add
449 // a couple of extra characters, taking it over BotPassword::RESTRICTIONS_MAXLENGTH
450 // characters long, so it will cause an error.
451 str_repeat( '*', BotPassword::RESTRICTIONS_MAXLENGTH )
452 ],
453 ] );
454
455 $status = $bp->save( 'insert' );
456
457 $this->assertStatusError( 'botpasswords-toolong-restrictions', $status );
458 $this->assertStatusError( 'botpasswords-toolong-grants', $status );
459 }
460 }