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