Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.55% covered (success)
92.55%
149 / 161
78.26% covered (warning)
78.26%
18 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
BotPassword
93.12% covered (success)
93.12%
149 / 160
78.26% covered (warning)
78.26%
18 / 23
54.95
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 getReplicaDatabase
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getPrimaryDatabase
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 newFromUser
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 newFromCentralId
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 newUnsaved
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 isSaved
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getUserCentralId
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getAppId
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getToken
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRestrictions
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getGrants
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getSeparator
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getPassword
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
4.00
 isInvalid
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 save
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 delete
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 invalidateAllPasswordsForUser
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 removeAllPasswordsForUser
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 generatePassword
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 canonicalizeLoginData
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
7
 login
92.06% covered (success)
92.06%
58 / 63
0.00% covered (danger)
0.00%
0 / 1
15.11
 loginHook
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\User;
8
9use MediaWiki\Auth\AuthenticationResponse;
10use MediaWiki\Auth\AuthManager;
11use MediaWiki\Auth\Throttler;
12use MediaWiki\HookContainer\HookRunner;
13use MediaWiki\Json\FormatJson;
14use MediaWiki\MainConfigNames;
15use MediaWiki\MediaWikiServices;
16use MediaWiki\Password\InvalidPassword;
17use MediaWiki\Password\Password;
18use MediaWiki\Password\PasswordError;
19use MediaWiki\Password\PasswordFactory;
20use MediaWiki\Request\WebRequest;
21use MediaWiki\Session\BotPasswordSessionProvider;
22use MediaWiki\Status\Status;
23use MediaWiki\Utils\MWRestrictions;
24use stdClass;
25use UnexpectedValueException;
26use Wikimedia\Rdbms\IDatabase;
27use Wikimedia\Rdbms\IDBAccessObject;
28use Wikimedia\Rdbms\IReadableDatabase;
29
30/**
31 * Utility class for bot passwords
32 * @since 1.27
33 */
34class BotPassword {
35
36    public const APPID_MAXLENGTH = 32;
37
38    /**
39     * Minimum length for a bot password
40     */
41    public const PASSWORD_MINLENGTH = 32;
42
43    /**
44     * Maximum length of the json representation of restrictions
45     * @since 1.36
46     */
47    public const RESTRICTIONS_MAXLENGTH = 65535;
48
49    /**
50     * Maximum length of the json representation of grants
51     * @since 1.36
52     */
53    public const GRANTS_MAXLENGTH = 65535;
54
55    private int $centralId;
56    private readonly string $appId;
57    private string $token;
58    private readonly MWRestrictions $restrictions;
59
60    /** @var string[] */
61    private readonly array $grants;
62
63    /**
64     * @internal only public for construction in BotPasswordStore
65     *
66     * @param stdClass $row bot_passwords database row
67     * @param bool $isSaved Whether the bot password was read from the database
68     * @param int $flags IDBAccessObject read flags
69     */
70    public function __construct(
71        stdClass $row,
72        private bool $isSaved,
73        private readonly int $flags = IDBAccessObject::READ_NORMAL,
74    ) {
75        $this->centralId = (int)$row->bp_user;
76        $this->appId = $row->bp_app_id;
77        $this->token = $row->bp_token;
78        $this->restrictions = MWRestrictions::newFromJson( $row->bp_restrictions );
79        $this->grants = FormatJson::decode( $row->bp_grants );
80    }
81
82    public static function getReplicaDatabase(): IReadableDatabase {
83        return MediaWikiServices::getInstance()
84            ->getBotPasswordStore()
85            ->getReplicaDatabase();
86    }
87
88    public static function getPrimaryDatabase(): IDatabase {
89        return MediaWikiServices::getInstance()
90            ->getBotPasswordStore()
91            ->getPrimaryDatabase();
92    }
93
94    /**
95     * Load a BotPassword from the database
96     * @param UserIdentity $userIdentity
97     * @param string $appId
98     * @param int $flags IDBAccessObject read flags
99     * @return BotPassword|null
100     */
101    public static function newFromUser( UserIdentity $userIdentity, $appId, $flags = IDBAccessObject::READ_NORMAL ) {
102        return MediaWikiServices::getInstance()
103            ->getBotPasswordStore()
104            ->getByUser( $userIdentity, (string)$appId, (int)$flags );
105    }
106
107    /**
108     * Load a BotPassword from the database
109     * @param int $centralId from CentralIdLookup
110     * @param string $appId
111     * @param int $flags IDBAccessObject read flags
112     * @return BotPassword|null
113     */
114    public static function newFromCentralId( $centralId, $appId, $flags = IDBAccessObject::READ_NORMAL ) {
115        return MediaWikiServices::getInstance()
116            ->getBotPasswordStore()
117            ->getByCentralId( (int)$centralId, (string)$appId, (int)$flags );
118    }
119
120    /**
121     * Create an unsaved BotPassword
122     * @param array $data Data to use to create the bot password. Keys are:
123     *  - user: (UserIdentity) UserIdentity to create the password for. Overrides username and centralId.
124     *  - username: (string) Username to create the password for. Overrides centralId.
125     *  - centralId: (int) User central ID to create the password for.
126     *  - appId: (string, required) App ID for the password.
127     *  - restrictions: (MWRestrictions, optional) Restrictions.
128     *  - grants: (string[], optional) Grants.
129     * @param int $flags IDBAccessObject read flags
130     * @return BotPassword|null
131     */
132    public static function newUnsaved( array $data, $flags = IDBAccessObject::READ_NORMAL ) {
133        return MediaWikiServices::getInstance()
134            ->getBotPasswordStore()
135            ->newUnsavedBotPassword( $data, (int)$flags );
136    }
137
138    /**
139     * Indicate whether this is known to be saved
140     */
141    public function isSaved(): bool {
142        return $this->isSaved;
143    }
144
145    /**
146     * Get the central user ID
147     */
148    public function getUserCentralId(): int {
149        return $this->centralId;
150    }
151
152    public function getAppId(): string {
153        return $this->appId;
154    }
155
156    public function getToken(): string {
157        return $this->token;
158    }
159
160    public function getRestrictions(): MWRestrictions {
161        return $this->restrictions;
162    }
163
164    /**
165     * @return string[]
166     */
167    public function getGrants() {
168        return $this->grants;
169    }
170
171    /**
172     * Get the separator for combined username + app ID
173     */
174    public static function getSeparator(): string {
175        return MediaWikiServices::getInstance()
176            ->getMainConfig()->get( MainConfigNames::UserrightsInterwikiDelimiter );
177    }
178
179    private function getPassword(): Password {
180        if ( ( $this->flags & IDBAccessObject::READ_LATEST ) === IDBAccessObject::READ_LATEST ) {
181            $db = self::getPrimaryDatabase();
182        } else {
183            $db = self::getReplicaDatabase();
184        }
185
186        $password = $db->newSelectQueryBuilder()
187            ->select( 'bp_password' )
188            ->from( 'bot_passwords' )
189            ->where( [ 'bp_user' => $this->centralId, 'bp_app_id' => $this->appId ] )
190            ->recency( $this->flags )
191            ->caller( __METHOD__ )->fetchField();
192        if ( $password === false ) {
193            return PasswordFactory::newInvalidPassword();
194        }
195
196        $passwordFactory = MediaWikiServices::getInstance()->getPasswordFactory();
197        try {
198            return $passwordFactory->newFromCiphertext( $password );
199        } catch ( PasswordError ) {
200            return PasswordFactory::newInvalidPassword();
201        }
202    }
203
204    /**
205     * Whether the password is currently invalid
206     * @since 1.32
207     */
208    public function isInvalid(): bool {
209        return $this->getPassword() instanceof InvalidPassword;
210    }
211
212    /**
213     * Save the BotPassword to the database
214     * @param string $operation 'update' or 'insert'
215     * @param Password|null $password Password to set.
216     * @return Status
217     * @throws UnexpectedValueException
218     */
219    public function save( $operation, ?Password $password = null ) {
220        // Ensure operation is valid
221        if ( $operation !== 'insert' && $operation !== 'update' ) {
222            throw new UnexpectedValueException(
223                "Expected 'insert' or 'update'; got '{$operation}'."
224            );
225        }
226
227        $store = MediaWikiServices::getInstance()->getBotPasswordStore();
228        if ( $operation === 'insert' ) {
229            $statusValue = $store->insertBotPassword( $this, $password );
230        } else {
231            // Must be update, already checked above
232            $statusValue = $store->updateBotPassword( $this, $password );
233        }
234
235        if ( $statusValue->isGood() ) {
236            $this->token = $statusValue->getValue();
237            $this->isSaved = true;
238            return Status::newGood();
239        }
240
241        // Action failed, status will have code botpasswords-insert-failed or
242        // botpasswords-update-failed depending on which action we tried
243        return Status::wrap( $statusValue );
244    }
245
246    /**
247     * Delete the BotPassword from the database
248     * @return bool Success
249     */
250    public function delete() {
251        $ok = MediaWikiServices::getInstance()
252            ->getBotPasswordStore()
253            ->deleteBotPassword( $this );
254        if ( $ok ) {
255            $this->token = '**unsaved**';
256            $this->isSaved = false;
257        }
258        return $ok;
259    }
260
261    /**
262     * Invalidate all passwords for a user, by name
263     * @param string $username
264     * @return bool Whether any passwords were invalidated
265     */
266    public static function invalidateAllPasswordsForUser( string $username ): bool {
267        return MediaWikiServices::getInstance()
268            ->getBotPasswordStore()
269            ->invalidateUserPasswords( $username );
270    }
271
272    /**
273     * Remove all passwords for a user, by name
274     * @param string $username
275     * @return bool Whether any passwords were removed
276     */
277    public static function removeAllPasswordsForUser( string $username ): bool {
278        return MediaWikiServices::getInstance()
279            ->getBotPasswordStore()
280            ->removeUserPasswords( $username );
281    }
282
283    /**
284     * Returns a (raw, unhashed) random password string.
285     */
286    public static function generatePassword(): string {
287        return PasswordFactory::generateRandomPasswordString( self::PASSWORD_MINLENGTH );
288    }
289
290    /**
291     * There are two ways to login with a bot password: "username@appId", "password" and
292     * "username", "appId@password". Transform it so it is always in the first form.
293     * Returns [bot username, bot password].
294     * If this cannot be a bot password login just return false.
295     * @param string $username
296     * @param string $password
297     * @return string[]|false
298     */
299    public static function canonicalizeLoginData( string $username, string $password ) {
300        $sep = self::getSeparator();
301        // the strlen check helps minimize the password information obtainable from timing
302        if ( strlen( $password ) >= self::PASSWORD_MINLENGTH && str_contains( $username, $sep ) ) {
303            // the separator is not valid in new usernames but might appear in legacy ones
304            if ( preg_match( '/^[0-9a-w]{' . self::PASSWORD_MINLENGTH . ',}$/', $password ) ) {
305                return [ $username, $password ];
306            }
307        } elseif ( strlen( $password ) > self::PASSWORD_MINLENGTH && str_contains( $password, $sep ) ) {
308            $segments = explode( $sep, $password );
309            $password = array_pop( $segments );
310            $appId = implode( $sep, $segments );
311            if ( preg_match( '/^[0-9a-w]{' . self::PASSWORD_MINLENGTH . ',}$/', $password ) ) {
312                return [ $username . $sep . $appId, $password ];
313            }
314        }
315        return false;
316    }
317
318    /**
319     * Try to log the user in
320     * @param string $username Combined username and app ID
321     * @param string $password Supplied password
322     * @param WebRequest $request
323     * @return Status On success, the good status's value is the new Session object
324     */
325    public static function login( string $username, string $password, WebRequest $request ) {
326        $services = MediaWikiServices::getInstance();
327        $config = $services->getMainConfig();
328        $enableBotPasswords = $config->get( MainConfigNames::EnableBotPasswords );
329        if ( !$enableBotPasswords ) {
330            return Status::newFatal( 'botpasswords-disabled' );
331        }
332
333        $sessionManager = $services->getSessionManager();
334
335        // @phan-suppress-next-line PhanUndeclaredMethod
336        $provider = $sessionManager->getProvider( BotPasswordSessionProvider::class );
337
338        if ( !$provider ) {
339            return Status::newFatal( 'botpasswords-no-provider' );
340        }
341
342        $performer = $request->getSession()->getUser();
343        // Split name into name+appId
344        $sep = self::getSeparator();
345        if ( !str_contains( $username, $sep ) ) {
346            return self::loginHook(
347                $username, null, $performer, Status::newFatal( 'botpasswords-invalid-name', $sep )
348            );
349        }
350        [ $name, $appId ] = explode( $sep, $username, 2 );
351
352        // Find the named user
353        $user = User::newFromName( $name );
354        if ( !$user ) {
355            return self::loginHook( $name, null, $performer, Status::newFatal( 'noname' ) );
356        }
357
358        $centralIdLookup = $services->getCentralIdLookup();
359        // Since bot passwords may be shared within a wiki farm, only allow them for globally owned accounts
360        [ $user->getName() => $centralId ] = $centralIdLookup->lookupOwnedUserNames(
361            [ $user->getName() => 0 ], $centralIdLookup::AUDIENCE_RAW );
362        if ( !$centralId ) {
363            return self::loginHook( $user, null, $performer, Status::newFatal( 'nosuchuser', $name ) );
364        }
365        if ( $user->isLocked() ) {
366            return Status::newFatal( 'botpasswords-locked' );
367        }
368
369        $throttle = null;
370        $passwordAttemptThrottle = $config->get( MainConfigNames::PasswordAttemptThrottle );
371        if ( $passwordAttemptThrottle ) {
372            $throttle = new Throttler( $passwordAttemptThrottle, [
373                'type' => 'botpassword',
374                'cache' => $services->getObjectCacheFactory()->getLocalClusterInstance(),
375            ] );
376            $result = $throttle->increase( $user->getName(), $request->getIP(), __METHOD__ );
377            if ( $result ) {
378                $msg = wfMessage( 'login-throttled' )->durationParams( $result['wait'] );
379                return self::loginHook( $user, null, $performer, Status::newFatal( $msg ) );
380            }
381        }
382
383        // Get the bot password
384        $bp = self::newFromCentralId( $centralId, $appId );
385        if ( !$bp ) {
386            return self::loginHook( $user, $bp, $performer,
387                Status::newFatal( 'botpasswords-not-exist', $name, $appId ) );
388        }
389
390        // Check restrictions
391        $status = $bp->getRestrictions()->check( $request );
392        if ( !$status->isOK() ) {
393            return self::loginHook( $user, $bp, $performer,
394                Status::newFatal( 'botpasswords-restriction-failed' ) );
395        }
396
397        // Check the password
398        $passwordObj = $bp->getPassword();
399        if ( $passwordObj instanceof InvalidPassword ) {
400            return self::loginHook( $user, $bp, $performer,
401                Status::newFatal( 'botpasswords-needs-reset', $name, $appId ) );
402        }
403        if ( !$passwordObj->verify( $password ) ) {
404            return self::loginHook( $user, $bp, $performer, Status::newFatal( 'wrongpassword' ) );
405        }
406
407        // Ok! Create the session.
408        $throttle?->clear( $user->getName(), $request->getIP() );
409
410        if ( !$user->isRegistered() ) {
411            // Clone $user before passing it to ::autoCreateUser, as that will
412            // modify the provided User object to an IP for some failures (but
413            // we want the login hook to get the username used and not an IP)
414            $userForFailure = clone $user;
415            $status = $services->getAuthManager()->autoCreateUser(
416                $user,
417                AuthManager::AUTOCREATE_SOURCE_SESSION,
418                false
419            );
420            if ( !$status->isOK() ) {
421                return self::loginHook( $userForFailure, $bp, $performer, $status );
422            }
423        }
424
425        return self::loginHook( $user, $bp, $performer,
426            Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) ) );
427    }
428
429    /**
430     * Call AuthManagerLoginAuthenticateAudit
431     *
432     * To facilitate logging all authentications, even ones not via
433     * AuthManager, call the AuthManagerLoginAuthenticateAudit hook.
434     *
435     * @param User|string $user User being logged in
436     * @param BotPassword|null $bp Bot sub-account, if it can be identified
437     * @param User $performer User performing the request
438     * @param Status $status Login status
439     * @return Status The passed-in status
440     */
441    private static function loginHook( $user, $bp, User $performer, Status $status ) {
442        $extraData = [
443            'performer' => $performer
444        ];
445        if ( $user instanceof User ) {
446            $name = $user->getName();
447            if ( $bp ) {
448                $extraData['appId'] = $name . self::getSeparator() . $bp->getAppId();
449            }
450        } else {
451            $name = $user;
452            $user = null;
453        }
454
455        if ( $status->isGood() ) {
456            $response = AuthenticationResponse::newPass( $name );
457        } else {
458            $response = AuthenticationResponse::newFail( $status->getMessage() );
459        }
460        ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
461            ->onAuthManagerLoginAuthenticateAudit( $response, $user, $name, $extraData );
462
463        return $status;
464    }
465}
466
467/** @deprecated class alias since 1.41 */
468class_alias( BotPassword::class, 'BotPassword' );