MediaWiki  1.27.2
BotPasswordTest.php
Go to the documentation of this file.
1 <?php
2 
4 
10  protected function setUp() {
11  parent::setUp();
12 
13  $this->setMwGlobals( [
14  'wgEnableBotPasswords' => true,
15  'wgBotPasswordsDatabase' => false,
16  'wgCentralIdLookupProvider' => 'BotPasswordTest OkMock',
17  'wgGrantPermissions' => [
18  'test' => [ 'read' => true ],
19  ],
20  'wgUserrightsInterwikiDelimiter' => '@',
21  ] );
22 
23  $mock1 = $this->getMockForAbstractClass( 'CentralIdLookup' );
24  $mock1->expects( $this->any() )->method( 'isAttached' )
25  ->will( $this->returnValue( true ) );
26  $mock1->expects( $this->any() )->method( 'lookupUserNames' )
27  ->will( $this->returnValue( [ 'UTSysop' => 42, 'UTDummy' => 43, 'UTInvalid' => 0 ] ) );
28  $mock1->expects( $this->never() )->method( 'lookupCentralIds' );
29 
30  $mock2 = $this->getMockForAbstractClass( 'CentralIdLookup' );
31  $mock2->expects( $this->any() )->method( 'isAttached' )
32  ->will( $this->returnValue( false ) );
33  $mock2->expects( $this->any() )->method( 'lookupUserNames' )
34  ->will( $this->returnArgument( 0 ) );
35  $mock2->expects( $this->never() )->method( 'lookupCentralIds' );
36 
37  $this->mergeMwGlobalArrayValue( 'wgCentralIdLookupProviders', [
38  'BotPasswordTest OkMock' => [ 'factory' => function () use ( $mock1 ) {
39  return $mock1;
40  } ],
41  'BotPasswordTest FailMock' => [ 'factory' => function () use ( $mock2 ) {
42  return $mock2;
43  } ],
44  ] );
45 
47  }
48 
49  public function addDBData() {
50  $passwordFactory = new \PasswordFactory();
51  $passwordFactory->init( \RequestContext::getMain()->getConfig() );
52  // A is unsalted MD5 (thus fast) ... we don't care about security here, this is test only
53  $passwordFactory->setDefaultType( 'A' );
54  $pwhash = $passwordFactory->newFromPlaintext( 'foobaz' );
55 
56  $dbw = wfGetDB( DB_MASTER );
57  $dbw->delete(
58  'bot_passwords',
59  [ 'bp_user' => [ 42, 43 ], 'bp_app_id' => 'BotPassword' ],
60  __METHOD__
61  );
62  $dbw->insert(
63  'bot_passwords',
64  [
65  [
66  'bp_user' => 42,
67  'bp_app_id' => 'BotPassword',
68  'bp_password' => $pwhash->toString(),
69  'bp_token' => 'token!',
70  'bp_restrictions' => '{"IPAddresses":["127.0.0.0/8"]}',
71  'bp_grants' => '["test"]',
72  ],
73  [
74  'bp_user' => 43,
75  'bp_app_id' => 'BotPassword',
76  'bp_password' => $pwhash->toString(),
77  'bp_token' => 'token!',
78  'bp_restrictions' => '{"IPAddresses":["127.0.0.0/8"]}',
79  'bp_grants' => '["test"]',
80  ],
81  ],
82  __METHOD__
83  );
84  }
85 
86  public function testBasics() {
87  $user = User::newFromName( 'UTSysop' );
88  $bp = BotPassword::newFromUser( $user, 'BotPassword' );
89  $this->assertInstanceOf( 'BotPassword', $bp );
90  $this->assertTrue( $bp->isSaved() );
91  $this->assertSame( 42, $bp->getUserCentralId() );
92  $this->assertSame( 'BotPassword', $bp->getAppId() );
93  $this->assertSame( 'token!', trim( $bp->getToken(), " \0" ) );
94  $this->assertEquals( '{"IPAddresses":["127.0.0.0/8"]}', $bp->getRestrictions()->toJson() );
95  $this->assertSame( [ 'test' ], $bp->getGrants() );
96 
97  $this->assertNull( BotPassword::newFromUser( $user, 'DoesNotExist' ) );
98 
99  $this->setMwGlobals( [
100  'wgCentralIdLookupProvider' => 'BotPasswordTest FailMock'
101  ] );
102  $this->assertNull( BotPassword::newFromUser( $user, 'BotPassword' ) );
103 
104  $this->assertSame( '@', BotPassword::getSeparator() );
105  $this->setMwGlobals( [
106  'wgUserrightsInterwikiDelimiter' => '#',
107  ] );
108  $this->assertSame( '#', BotPassword::getSeparator() );
109  }
110 
111  public function testUnsaved() {
112  $user = User::newFromName( 'UTSysop' );
113  $bp = BotPassword::newUnsaved( [
114  'user' => $user,
115  'appId' => 'DoesNotExist'
116  ] );
117  $this->assertInstanceOf( 'BotPassword', $bp );
118  $this->assertFalse( $bp->isSaved() );
119  $this->assertSame( 42, $bp->getUserCentralId() );
120  $this->assertSame( 'DoesNotExist', $bp->getAppId() );
121  $this->assertEquals( MWRestrictions::newDefault(), $bp->getRestrictions() );
122  $this->assertSame( [], $bp->getGrants() );
123 
124  $bp = BotPassword::newUnsaved( [
125  'username' => 'UTDummy',
126  'appId' => 'DoesNotExist2',
127  'restrictions' => MWRestrictions::newFromJson( '{"IPAddresses":["127.0.0.0/8"]}' ),
128  'grants' => [ 'test' ],
129  ] );
130  $this->assertInstanceOf( 'BotPassword', $bp );
131  $this->assertFalse( $bp->isSaved() );
132  $this->assertSame( 43, $bp->getUserCentralId() );
133  $this->assertSame( 'DoesNotExist2', $bp->getAppId() );
134  $this->assertEquals( '{"IPAddresses":["127.0.0.0/8"]}', $bp->getRestrictions()->toJson() );
135  $this->assertSame( [ 'test' ], $bp->getGrants() );
136 
137  $user = User::newFromName( 'UTSysop' );
138  $bp = BotPassword::newUnsaved( [
139  'centralId' => 45,
140  'appId' => 'DoesNotExist'
141  ] );
142  $this->assertInstanceOf( 'BotPassword', $bp );
143  $this->assertFalse( $bp->isSaved() );
144  $this->assertSame( 45, $bp->getUserCentralId() );
145  $this->assertSame( 'DoesNotExist', $bp->getAppId() );
146 
147  $user = User::newFromName( 'UTSysop' );
148  $bp = BotPassword::newUnsaved( [
149  'user' => $user,
150  'appId' => 'BotPassword'
151  ] );
152  $this->assertInstanceOf( 'BotPassword', $bp );
153  $this->assertFalse( $bp->isSaved() );
154 
155  $this->assertNull( BotPassword::newUnsaved( [
156  'user' => $user,
157  'appId' => '',
158  ] ) );
159  $this->assertNull( BotPassword::newUnsaved( [
160  'user' => $user,
161  'appId' => str_repeat( 'X', BotPassword::APPID_MAXLENGTH + 1 ),
162  ] ) );
163  $this->assertNull( BotPassword::newUnsaved( [
164  'user' => 'UTSysop',
165  'appId' => 'Ok',
166  ] ) );
167  $this->assertNull( BotPassword::newUnsaved( [
168  'username' => 'UTInvalid',
169  'appId' => 'Ok',
170  ] ) );
171  $this->assertNull( BotPassword::newUnsaved( [
172  'appId' => 'Ok',
173  ] ) );
174  }
175 
176  public function testGetPassword() {
178 
179  $password = $bp->getPassword();
180  $this->assertInstanceOf( 'Password', $password );
181  $this->assertTrue( $password->equals( 'foobaz' ) );
182 
183  $bp->centralId = 44;
184  $password = $bp->getPassword();
185  $this->assertInstanceOf( 'InvalidPassword', $password );
186 
188  $dbw = wfGetDB( DB_MASTER );
189  $dbw->update(
190  'bot_passwords',
191  [ 'bp_password' => 'garbage' ],
192  [ 'bp_user' => 42, 'bp_app_id' => 'BotPassword' ],
193  __METHOD__
194  );
195  $password = $bp->getPassword();
196  $this->assertInstanceOf( 'InvalidPassword', $password );
197  }
198 
202 
203  $this->assertNotInstanceOf( 'InvalidPassword', $bp1->getPassword(), 'sanity check' );
204  $this->assertNotInstanceOf( 'InvalidPassword', $bp2->getPassword(), 'sanity check' );
206  $this->assertInstanceOf( 'InvalidPassword', $bp1->getPassword() );
207  $this->assertNotInstanceOf( 'InvalidPassword', $bp2->getPassword() );
208 
210  $this->assertInstanceOf( 'InvalidPassword', $bp->getPassword() );
211  }
212 
213  public function testRemoveAllPasswordsForUser() {
214  $this->assertNotNull( BotPassword::newFromCentralId( 42, 'BotPassword' ), 'sanity check' );
215  $this->assertNotNull( BotPassword::newFromCentralId( 43, 'BotPassword' ), 'sanity check' );
216 
218 
219  $this->assertNull( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
220  $this->assertNotNull( BotPassword::newFromCentralId( 43, 'BotPassword' ) );
221  }
222 
223  public function testLogin() {
224  // Test failure when bot passwords aren't enabled
225  $this->setMwGlobals( 'wgEnableBotPasswords', false );
226  $status = BotPassword::login( 'UTSysop@BotPassword', 'foobaz', new FauxRequest );
227  $this->assertEquals( Status::newFatal( 'botpasswords-disabled' ), $status );
228  $this->setMwGlobals( 'wgEnableBotPasswords', true );
229 
230  // Test failure when BotPasswordSessionProvider isn't configured
231  $manager = new SessionManager( [
232  'logger' => new Psr\Log\NullLogger,
233  'store' => new EmptyBagOStuff,
234  ] );
236  $this->assertNull(
237  $manager->getProvider( MediaWiki\Session\BotPasswordSessionProvider::class ),
238  'sanity check'
239  );
240  $status = BotPassword::login( 'UTSysop@BotPassword', 'foobaz', new FauxRequest );
241  $this->assertEquals( Status::newFatal( 'botpasswords-no-provider' ), $status );
242  ScopedCallback::consume( $reset );
243 
244  // Now configure BotPasswordSessionProvider for further tests...
245  $mainConfig = RequestContext::getMain()->getConfig();
246  $config = new HashConfig( [
247  'SessionProviders' => $mainConfig->get( 'SessionProviders' ) + [
250  'args' => [ [ 'priority' => 40 ] ],
251  ]
252  ],
253  ] );
254  $manager = new SessionManager( [
255  'config' => new MultiConfig( [ $config, RequestContext::getMain()->getConfig() ] ),
256  'logger' => new Psr\Log\NullLogger,
257  'store' => new EmptyBagOStuff,
258  ] );
260 
261  // No "@"-thing in the username
262  $status = BotPassword::login( 'UTSysop', 'foobaz', new FauxRequest );
263  $this->assertEquals( Status::newFatal( 'botpasswords-invalid-name', '@' ), $status );
264 
265  // No base user
266  $status = BotPassword::login( 'UTDummy@BotPassword', 'foobaz', new FauxRequest );
267  $this->assertEquals( Status::newFatal( 'nosuchuser', 'UTDummy' ), $status );
268 
269  // No bot password
270  $status = BotPassword::login( 'UTSysop@DoesNotExist', 'foobaz', new FauxRequest );
271  $this->assertEquals(
272  Status::newFatal( 'botpasswords-not-exist', 'UTSysop', 'DoesNotExist' ),
273  $status
274  );
275 
276  // Failed restriction
277  $request = $this->getMock( 'FauxRequest', [ 'getIP' ] );
278  $request->expects( $this->any() )->method( 'getIP' )
279  ->will( $this->returnValue( '10.0.0.1' ) );
280  $status = BotPassword::login( 'UTSysop@BotPassword', 'foobaz', $request );
281  $this->assertEquals( Status::newFatal( 'botpasswords-restriction-failed' ), $status );
282 
283  // Wrong password
284  $status = BotPassword::login( 'UTSysop@BotPassword', 'UTSysopPassword', new FauxRequest );
285  $this->assertEquals( Status::newFatal( 'wrongpassword' ), $status );
286 
287  // Success!
288  $request = new FauxRequest;
289  $this->assertNotInstanceOf(
290  MediaWiki\Session\BotPasswordSessionProvider::class,
291  $request->getSession()->getProvider(),
292  'sanity check'
293  );
294  $status = BotPassword::login( 'UTSysop@BotPassword', 'foobaz', $request );
295  $this->assertInstanceOf( 'Status', $status );
296  $this->assertTrue( $status->isGood() );
297  $session = $status->getValue();
298  $this->assertInstanceOf( MediaWiki\Session\Session::class, $session );
299  $this->assertInstanceOf(
300  MediaWiki\Session\BotPasswordSessionProvider::class, $session->getProvider()
301  );
302  $this->assertSame( $session->getId(), $request->getSession()->getId() );
303 
304  ScopedCallback::consume( $reset );
305  }
306 
311  public function testSave( $password ) {
312  $passwordFactory = new \PasswordFactory();
313  $passwordFactory->init( \RequestContext::getMain()->getConfig() );
314  // A is unsalted MD5 (thus fast) ... we don't care about security here, this is test only
315  $passwordFactory->setDefaultType( 'A' );
316 
317  $bp = BotPassword::newUnsaved( [
318  'centralId' => 42,
319  'appId' => 'TestSave',
320  'restrictions' => MWRestrictions::newFromJson( '{"IPAddresses":["127.0.0.0/8"]}' ),
321  'grants' => [ 'test' ],
322  ] );
323  $this->assertFalse( $bp->isSaved(), 'sanity check' );
324  $this->assertNull(
325  BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST ), 'sanity check'
326  );
327 
328  $pwhash = $password ? $passwordFactory->newFromPlaintext( $password ) : null;
329  $this->assertFalse( $bp->save( 'update', $pwhash ) );
330  $this->assertTrue( $bp->save( 'insert', $pwhash ) );
332  $this->assertInstanceOf( 'BotPassword', $bp2 );
333  $this->assertEquals( $bp->getUserCentralId(), $bp2->getUserCentralId() );
334  $this->assertEquals( $bp->getAppId(), $bp2->getAppId() );
335  $this->assertEquals( $bp->getToken(), $bp2->getToken() );
336  $this->assertEquals( $bp->getRestrictions(), $bp2->getRestrictions() );
337  $this->assertEquals( $bp->getGrants(), $bp2->getGrants() );
338  $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
339  if ( $password === null ) {
340  $this->assertInstanceOf( 'InvalidPassword', $pw );
341  } else {
342  $this->assertTrue( $pw->equals( $password ) );
343  }
344 
345  $token = $bp->getToken();
346  $this->assertFalse( $bp->save( 'insert' ) );
347  $this->assertTrue( $bp->save( 'update' ) );
348  $this->assertNotEquals( $token, $bp->getToken() );
350  $this->assertInstanceOf( 'BotPassword', $bp2 );
351  $this->assertEquals( $bp->getToken(), $bp2->getToken() );
352  $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
353  if ( $password === null ) {
354  $this->assertInstanceOf( 'InvalidPassword', $pw );
355  } else {
356  $this->assertTrue( $pw->equals( $password ) );
357  }
358 
359  $pwhash = $passwordFactory->newFromPlaintext( 'XXX' );
360  $token = $bp->getToken();
361  $this->assertTrue( $bp->save( 'update', $pwhash ) );
362  $this->assertNotEquals( $token, $bp->getToken() );
363  $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
364  $this->assertTrue( $pw->equals( 'XXX' ) );
365 
366  $this->assertTrue( $bp->delete() );
367  $this->assertFalse( $bp->isSaved() );
368  $this->assertNull( BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST ) );
369 
370  $this->assertFalse( $bp->save( 'foobar' ) );
371  }
372 
373  public static function provideSave() {
374  return [
375  [ null ],
376  [ 'foobar' ],
377  ];
378  }
379 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:568
mergeMwGlobalArrayValue($name, $values)
Merges the given values into a MW global array variable.
static getSeparator()
Get the separator for combined user name + app ID.
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
const APPID_MAXLENGTH
Definition: BotPassword.php:29
static setSessionManagerSingleton(SessionManager $manager=null)
Override the singleton for unit testing.
Definition: TestUtils.php:17
A helper class for throttling authentication attempts.
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
static newUnsaved(array $data, $flags=self::READ_NORMAL)
Create an unsaved BotPassword.
static newFromCentralId($centralId, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
static removeAllPasswordsForUser($username)
Remove all passwords for a user, by name.
static getMain()
Static methods.
static invalidateAllPasswordsForUser($username)
Invalidate all passwords for a user, by name.
A BagOStuff object with no objects in it.
static newFromJson($json)
Provides a fallback sequence for Config objects.
Definition: MultiConfig.php:28
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:242
static newFromUser(User $user, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
Definition: BotPassword.php:89
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:35
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2418
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:52
static resetCache()
Reset internal cache for unit testing.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1004
static consume(ScopedCallback &$sc=null)
Trigger a scoped callback and destroy it.
static newDefault()
const DB_MASTER
Definition: Defines.php:47
This serves as the entry point to the MediaWiki session handling system.
static newFromObject($object)
Return the same object, without access restrictions.
static login($username, $password, WebRequest $request)
Try to log the user in.
setMwGlobals($pairs, $value=null)
A Config instance which stores all settings as a member variable.
Definition: HashConfig.php:28
BotPassword Database.
testSave($password)
provideSave