Merge "Http::getProxy() method to get proxy configuration"
[lhc/web/wiklou.git] / includes / user / BotPassword.php
1 <?php
2 /**
3 * Utility class for bot passwords
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 */
20
21 /**
22 * Utility class for bot passwords
23 * @since 1.27
24 */
25 class BotPassword implements IDBAccessObject {
26
27 const APPID_MAXLENGTH = 32;
28
29 /** @var bool */
30 private $isSaved;
31
32 /** @var int */
33 private $centralId;
34
35 /** @var string */
36 private $appId;
37
38 /** @var string */
39 private $token;
40
41 /** @var MWRestrictions */
42 private $restrictions;
43
44 /** @var string[] */
45 private $grants;
46
47 /** @var int */
48 private $flags = self::READ_NORMAL;
49
50 /**
51 * @param object $row bot_passwords database row
52 * @param bool $isSaved Whether the bot password was read from the database
53 * @param int $flags IDBAccessObject read flags
54 */
55 protected function __construct( $row, $isSaved, $flags = self::READ_NORMAL ) {
56 $this->isSaved = $isSaved;
57 $this->flags = $flags;
58
59 $this->centralId = (int)$row->bp_user;
60 $this->appId = $row->bp_app_id;
61 $this->token = $row->bp_token;
62 $this->restrictions = MWRestrictions::newFromJson( $row->bp_restrictions );
63 $this->grants = FormatJson::decode( $row->bp_grants );
64 }
65
66 /**
67 * Get a database connection for the bot passwords database
68 * @param int $db Index of the connection to get, e.g. DB_MASTER or DB_SLAVE.
69 * @return DatabaseBase
70 */
71 public static function getDB( $db ) {
72 global $wgBotPasswordsCluster, $wgBotPasswordsDatabase;
73
74 $lb = $wgBotPasswordsCluster
75 ? wfGetLBFactory()->getExternalLB( $wgBotPasswordsCluster )
76 : wfGetLB( $wgBotPasswordsDatabase );
77 return $lb->getConnectionRef( $db, [], $wgBotPasswordsDatabase );
78 }
79
80 /**
81 * Load a BotPassword from the database
82 * @param User $user
83 * @param string $appId
84 * @param int $flags IDBAccessObject read flags
85 * @return BotPassword|null
86 */
87 public static function newFromUser( User $user, $appId, $flags = self::READ_NORMAL ) {
88 $centralId = CentralIdLookup::factory()->centralIdFromLocalUser(
89 $user, CentralIdLookup::AUDIENCE_RAW, $flags
90 );
91 return $centralId ? self::newFromCentralId( $centralId, $appId, $flags ) : null;
92 }
93
94 /**
95 * Load a BotPassword from the database
96 * @param int $centralId from CentralIdLookup
97 * @param string $appId
98 * @param int $flags IDBAccessObject read flags
99 * @return BotPassword|null
100 */
101 public static function newFromCentralId( $centralId, $appId, $flags = self::READ_NORMAL ) {
102 global $wgEnableBotPasswords;
103
104 if ( !$wgEnableBotPasswords ) {
105 return null;
106 }
107
108 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
109 $db = self::getDB( $index );
110 $row = $db->selectRow(
111 'bot_passwords',
112 [ 'bp_user', 'bp_app_id', 'bp_token', 'bp_restrictions', 'bp_grants' ],
113 [ 'bp_user' => $centralId, 'bp_app_id' => $appId ],
114 __METHOD__,
115 $options
116 );
117 return $row ? new self( $row, true, $flags ) : null;
118 }
119
120 /**
121 * Create an unsaved BotPassword
122 * @param array $data Data to use to create the bot password. Keys are:
123 * - user: (User) User object 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) 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 = self::READ_NORMAL ) {
133 $row = (object)[
134 'bp_user' => 0,
135 'bp_app_id' => isset( $data['appId'] ) ? trim( $data['appId'] ) : '',
136 'bp_token' => '**unsaved**',
137 'bp_restrictions' => isset( $data['restrictions'] )
138 ? $data['restrictions']
139 : MWRestrictions::newDefault(),
140 'bp_grants' => isset( $data['grants'] ) ? $data['grants'] : [],
141 ];
142
143 if (
144 $row->bp_app_id === '' || strlen( $row->bp_app_id ) > self::APPID_MAXLENGTH ||
145 !$row->bp_restrictions instanceof MWRestrictions ||
146 !is_array( $row->bp_grants )
147 ) {
148 return null;
149 }
150
151 $row->bp_restrictions = $row->bp_restrictions->toJson();
152 $row->bp_grants = FormatJson::encode( $row->bp_grants );
153
154 if ( isset( $data['user'] ) ) {
155 if ( !$data['user'] instanceof User ) {
156 return null;
157 }
158 $row->bp_user = CentralIdLookup::factory()->centralIdFromLocalUser(
159 $data['user'], CentralIdLookup::AUDIENCE_RAW, $flags
160 );
161 } elseif ( isset( $data['username'] ) ) {
162 $row->bp_user = CentralIdLookup::factory()->centralIdFromName(
163 $data['username'], CentralIdLookup::AUDIENCE_RAW, $flags
164 );
165 } elseif ( isset( $data['centralId'] ) ) {
166 $row->bp_user = $data['centralId'];
167 }
168 if ( !$row->bp_user ) {
169 return null;
170 }
171
172 return new self( $row, false, $flags );
173 }
174
175 /**
176 * Indicate whether this is known to be saved
177 * @return bool
178 */
179 public function isSaved() {
180 return $this->isSaved;
181 }
182
183 /**
184 * Get the central user ID
185 * @return int
186 */
187 public function getUserCentralId() {
188 return $this->centralId;
189 }
190
191 /**
192 * Get the app ID
193 * @return string
194 */
195 public function getAppId() {
196 return $this->appId;
197 }
198
199 /**
200 * Get the token
201 * @return string
202 */
203 public function getToken() {
204 return $this->token;
205 }
206
207 /**
208 * Get the restrictions
209 * @return MWRestrictions
210 */
211 public function getRestrictions() {
212 return $this->restrictions;
213 }
214
215 /**
216 * Get the grants
217 * @return string[]
218 */
219 public function getGrants() {
220 return $this->grants;
221 }
222
223 /**
224 * Get the separator for combined user name + app ID
225 * @return string
226 */
227 public static function getSeparator() {
228 global $wgUserrightsInterwikiDelimiter;
229 return $wgUserrightsInterwikiDelimiter;
230 }
231
232 /**
233 * Get the password
234 * @return Password
235 */
236 protected function getPassword() {
237 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $this->flags );
238 $db = self::getDB( $index );
239 $password = $db->selectField(
240 'bot_passwords',
241 'bp_password',
242 [ 'bp_user' => $this->centralId, 'bp_app_id' => $this->appId ],
243 __METHOD__,
244 $options
245 );
246 if ( $password === false ) {
247 return PasswordFactory::newInvalidPassword();
248 }
249
250 $passwordFactory = new \PasswordFactory();
251 $passwordFactory->init( \RequestContext::getMain()->getConfig() );
252 try {
253 return $passwordFactory->newFromCiphertext( $password );
254 } catch ( PasswordError $ex ) {
255 return PasswordFactory::newInvalidPassword();
256 }
257 }
258
259 /**
260 * Save the BotPassword to the database
261 * @param string $operation 'update' or 'insert'
262 * @param Password|null $password Password to set.
263 * @return bool Success
264 */
265 public function save( $operation, Password $password = null ) {
266 $conds = [
267 'bp_user' => $this->centralId,
268 'bp_app_id' => $this->appId,
269 ];
270 $fields = [
271 'bp_token' => MWCryptRand::generateHex( User::TOKEN_LENGTH ),
272 'bp_restrictions' => $this->restrictions->toJson(),
273 'bp_grants' => FormatJson::encode( $this->grants ),
274 ];
275
276 if ( $password !== null ) {
277 $fields['bp_password'] = $password->toString();
278 } elseif ( $operation === 'insert' ) {
279 $fields['bp_password'] = PasswordFactory::newInvalidPassword()->toString();
280 }
281
282 $dbw = self::getDB( DB_MASTER );
283 switch ( $operation ) {
284 case 'insert':
285 $dbw->insert( 'bot_passwords', $fields + $conds, __METHOD__, [ 'IGNORE' ] );
286 break;
287
288 case 'update':
289 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__ );
290 break;
291
292 default:
293 return false;
294 }
295 $ok = (bool)$dbw->affectedRows();
296 if ( $ok ) {
297 $this->token = $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__ );
298 $this->isSaved = true;
299 }
300 return $ok;
301 }
302
303 /**
304 * Delete the BotPassword from the database
305 * @return bool Success
306 */
307 public function delete() {
308 $conds = [
309 'bp_user' => $this->centralId,
310 'bp_app_id' => $this->appId,
311 ];
312 $dbw = self::getDB( DB_MASTER );
313 $dbw->delete( 'bot_passwords', $conds, __METHOD__ );
314 $ok = (bool)$dbw->affectedRows();
315 if ( $ok ) {
316 $this->token = '**unsaved**';
317 $this->isSaved = false;
318 }
319 return $ok;
320 }
321
322 /**
323 * Invalidate all passwords for a user, by name
324 * @param string $username User name
325 * @return bool Whether any passwords were invalidated
326 */
327 public static function invalidateAllPasswordsForUser( $username ) {
328 $centralId = CentralIdLookup::factory()->centralIdFromName(
329 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
330 );
331 return $centralId && self::invalidateAllPasswordsForCentralId( $centralId );
332 }
333
334 /**
335 * Invalidate all passwords for a user, by central ID
336 * @param int $centralId
337 * @return bool Whether any passwords were invalidated
338 */
339 public static function invalidateAllPasswordsForCentralId( $centralId ) {
340 global $wgEnableBotPasswords;
341
342 if ( !$wgEnableBotPasswords ) {
343 return false;
344 }
345
346 $dbw = self::getDB( DB_MASTER );
347 $dbw->update(
348 'bot_passwords',
349 [ 'bp_password' => PasswordFactory::newInvalidPassword()->toString() ],
350 [ 'bp_user' => $centralId ],
351 __METHOD__
352 );
353 return (bool)$dbw->affectedRows();
354 }
355
356 /**
357 * Remove all passwords for a user, by name
358 * @param string $username User name
359 * @return bool Whether any passwords were removed
360 */
361 public static function removeAllPasswordsForUser( $username ) {
362 $centralId = CentralIdLookup::factory()->centralIdFromName(
363 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
364 );
365 return $centralId && self::removeAllPasswordsForCentralId( $centralId );
366 }
367
368 /**
369 * Remove all passwords for a user, by central ID
370 * @param int $centralId
371 * @return bool Whether any passwords were removed
372 */
373 public static function removeAllPasswordsForCentralId( $centralId ) {
374 global $wgEnableBotPasswords;
375
376 if ( !$wgEnableBotPasswords ) {
377 return false;
378 }
379
380 $dbw = self::getDB( DB_MASTER );
381 $dbw->delete(
382 'bot_passwords',
383 [ 'bp_user' => $centralId ],
384 __METHOD__
385 );
386 return (bool)$dbw->affectedRows();
387 }
388
389 /**
390 * Try to log the user in
391 * @param string $username Combined user name and app ID
392 * @param string $password Supplied password
393 * @param WebRequest $request
394 * @return Status On success, the good status's value is the new Session object
395 */
396 public static function login( $username, $password, WebRequest $request ) {
397 global $wgEnableBotPasswords;
398
399 if ( !$wgEnableBotPasswords ) {
400 return Status::newFatal( 'botpasswords-disabled' );
401 }
402
403 $manager = MediaWiki\Session\SessionManager::singleton();
404 $provider = $manager->getProvider(
405 'MediaWiki\\Session\\BotPasswordSessionProvider'
406 );
407 if ( !$provider ) {
408 return Status::newFatal( 'botpasswords-no-provider' );
409 }
410
411 // Split name into name+appId
412 $sep = self::getSeparator();
413 if ( strpos( $username, $sep ) === false ) {
414 return Status::newFatal( 'botpasswords-invalid-name', $sep );
415 }
416 list( $name, $appId ) = explode( $sep, $username, 2 );
417
418 // Find the named user
419 $user = User::newFromName( $name );
420 if ( !$user || $user->isAnon() ) {
421 return Status::newFatal( 'nosuchuser', $name );
422 }
423
424 // Get the bot password
425 $bp = self::newFromUser( $user, $appId );
426 if ( !$bp ) {
427 return Status::newFatal( 'botpasswords-not-exist', $name, $appId );
428 }
429
430 // Check restrictions
431 $status = $bp->getRestrictions()->check( $request );
432 if ( !$status->isOK() ) {
433 return Status::newFatal( 'botpasswords-restriction-failed' );
434 }
435
436 // Check the password
437 if ( !$bp->getPassword()->equals( $password ) ) {
438 return Status::newFatal( 'wrongpassword' );
439 }
440
441 // Ok! Create the session.
442 return Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );
443 }
444 }