Better logging for botpasswords
[lhc/web/wiklou.git] / includes / specials / SpecialBotPasswords.php
1 <?php
2 /**
3 * Implements Special:BotPasswords
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 * @file
21 * @ingroup SpecialPage
22 */
23
24 use MediaWiki\Logger\LoggerFactory;
25
26 /**
27 * Let users manage bot passwords
28 *
29 * @ingroup SpecialPage
30 */
31 class SpecialBotPasswords extends FormSpecialPage {
32
33 /** @var int Central user ID */
34 private $userId = 0;
35
36 /** @var BotPassword|null Bot password being edited, if any */
37 private $botPassword = null;
38
39 /** @var string Operation being performed: create, update, delete */
40 private $operation = null;
41
42 /** @var string New password set, for communication between onSubmit() and onSuccess() */
43 private $password = null;
44
45 /** @var Psr\Log\LoggerInterface */
46 private $logger = null;
47
48 public function __construct() {
49 parent::__construct( 'BotPasswords', 'editmyprivateinfo' );
50 $this->logger = LoggerFactory::getInstance( 'authentication' );
51 }
52
53 /**
54 * @return bool
55 */
56 public function isListed() {
57 return $this->getConfig()->get( 'EnableBotPasswords' );
58 }
59
60 /**
61 * Main execution point
62 * @param string|null $par
63 */
64 function execute( $par ) {
65 $this->getOutput()->disallowUserJs();
66 $this->requireLogin();
67
68 $par = trim( $par );
69 if ( strlen( $par ) === 0 ) {
70 $par = null;
71 } elseif ( strlen( $par ) > BotPassword::APPID_MAXLENGTH ) {
72 throw new ErrorPageError( 'botpasswords', 'botpasswords-bad-appid',
73 [ htmlspecialchars( $par ) ] );
74 }
75
76 parent::execute( $par );
77 }
78
79 protected function checkExecutePermissions( User $user ) {
80 parent::checkExecutePermissions( $user );
81
82 if ( !$this->getConfig()->get( 'EnableBotPasswords' ) ) {
83 throw new ErrorPageError( 'botpasswords', 'botpasswords-disabled' );
84 }
85
86 $this->userId = CentralIdLookup::factory()->centralIdFromLocalUser( $this->getUser() );
87 if ( !$this->userId ) {
88 throw new ErrorPageError( 'botpasswords', 'botpasswords-no-central-id' );
89 }
90 }
91
92 protected function getFormFields() {
93 $fields = [];
94
95 if ( $this->par !== null ) {
96 $this->botPassword = BotPassword::newFromCentralId( $this->userId, $this->par );
97 if ( !$this->botPassword ) {
98 $this->botPassword = BotPassword::newUnsaved( [
99 'centralId' => $this->userId,
100 'appId' => $this->par,
101 ] );
102 }
103
104 $sep = BotPassword::getSeparator();
105 $fields[] = [
106 'type' => 'info',
107 'label-message' => 'username',
108 'default' => $this->getUser()->getName() . $sep . $this->par
109 ];
110
111 if ( $this->botPassword->isSaved() ) {
112 $fields['resetPassword'] = [
113 'type' => 'check',
114 'label-message' => 'botpasswords-label-resetpassword',
115 ];
116 }
117
118 $lang = $this->getLanguage();
119 $showGrants = MWGrants::getValidGrants();
120 $fields['grants'] = [
121 'type' => 'checkmatrix',
122 'label-message' => 'botpasswords-label-grants',
123 'help-message' => 'botpasswords-help-grants',
124 'columns' => [
125 $this->msg( 'botpasswords-label-grants-column' )->escaped() => 'grant'
126 ],
127 'rows' => array_combine(
128 array_map( 'MWGrants::getGrantsLink', $showGrants ),
129 $showGrants
130 ),
131 'default' => array_map(
132 function ( $g ) {
133 return "grant-$g";
134 },
135 $this->botPassword->getGrants()
136 ),
137 'tooltips' => array_combine(
138 array_map( 'MWGrants::getGrantsLink', $showGrants ),
139 array_map(
140 function ( $rights ) use ( $lang ) {
141 return $lang->semicolonList( array_map( 'User::getRightDescription', $rights ) );
142 },
143 array_intersect_key( MWGrants::getRightsByGrant(), array_flip( $showGrants ) )
144 )
145 ),
146 'force-options-on' => array_map(
147 function ( $g ) {
148 return "grant-$g";
149 },
150 MWGrants::getHiddenGrants()
151 ),
152 ];
153
154 $fields['restrictions'] = [
155 'class' => HTMLRestrictionsField::class,
156 'required' => true,
157 'default' => $this->botPassword->getRestrictions(),
158 ];
159
160 } else {
161 $linkRenderer = $this->getLinkRenderer();
162 $dbr = BotPassword::getDB( DB_REPLICA );
163 $res = $dbr->select(
164 'bot_passwords',
165 [ 'bp_app_id' ],
166 [ 'bp_user' => $this->userId ],
167 __METHOD__
168 );
169 foreach ( $res as $row ) {
170 $fields[] = [
171 'section' => 'existing',
172 'type' => 'info',
173 'raw' => true,
174 'default' => $linkRenderer->makeKnownLink(
175 $this->getPageTitle( $row->bp_app_id ),
176 $row->bp_app_id
177 ),
178 ];
179 }
180
181 $fields['appId'] = [
182 'section' => 'createnew',
183 'type' => 'textwithbutton',
184 'label-message' => 'botpasswords-label-appid',
185 'buttondefault' => $this->msg( 'botpasswords-label-create' )->text(),
186 'buttonflags' => [ 'progressive', 'primary' ],
187 'required' => true,
188 'size' => BotPassword::APPID_MAXLENGTH,
189 'maxlength' => BotPassword::APPID_MAXLENGTH,
190 'validation-callback' => function ( $v ) {
191 $v = trim( $v );
192 return $v !== '' && strlen( $v ) <= BotPassword::APPID_MAXLENGTH;
193 },
194 ];
195
196 $fields[] = [
197 'type' => 'hidden',
198 'default' => 'new',
199 'name' => 'op',
200 ];
201 }
202
203 return $fields;
204 }
205
206 protected function alterForm( HTMLForm $form ) {
207 $form->setId( 'mw-botpasswords-form' );
208 $form->setTableId( 'mw-botpasswords-table' );
209 $form->addPreText( $this->msg( 'botpasswords-summary' )->parseAsBlock() );
210 $form->suppressDefaultSubmit();
211
212 if ( $this->par !== null ) {
213 if ( $this->botPassword->isSaved() ) {
214 $form->setWrapperLegendMsg( 'botpasswords-editexisting' );
215 $form->addButton( [
216 'name' => 'op',
217 'value' => 'update',
218 'label-message' => 'botpasswords-label-update',
219 'flags' => [ 'primary', 'progressive' ],
220 ] );
221 $form->addButton( [
222 'name' => 'op',
223 'value' => 'delete',
224 'label-message' => 'botpasswords-label-delete',
225 'flags' => [ 'destructive' ],
226 ] );
227 } else {
228 $form->setWrapperLegendMsg( 'botpasswords-createnew' );
229 $form->addButton( [
230 'name' => 'op',
231 'value' => 'create',
232 'label-message' => 'botpasswords-label-create',
233 'flags' => [ 'primary', 'progressive' ],
234 ] );
235 }
236
237 $form->addButton( [
238 'name' => 'op',
239 'value' => 'cancel',
240 'label-message' => 'botpasswords-label-cancel'
241 ] );
242 }
243 }
244
245 public function onSubmit( array $data ) {
246 $op = $this->getRequest()->getVal( 'op', '' );
247
248 switch ( $op ) {
249 case 'new':
250 $this->getOutput()->redirect( $this->getPageTitle( $data['appId'] )->getFullURL() );
251 return false;
252
253 case 'create':
254 $this->operation = 'insert';
255 return $this->save( $data );
256
257 case 'update':
258 $this->operation = 'update';
259 return $this->save( $data );
260
261 case 'delete':
262 $this->operation = 'delete';
263 $bp = BotPassword::newFromCentralId( $this->userId, $this->par );
264 if ( $bp ) {
265 $bp->delete();
266 $this->logger->info(
267 "Bot password {op} for {user}@{app_id}",
268 [
269 'app_id' => $this->par,
270 'user' => $this->getUser()->getName(),
271 'centralId' => $this->userId,
272 'op' => 'delete',
273 'client_ip' => $this->getRequest()->getIP()
274 ]
275 );
276 }
277 return Status::newGood();
278
279 case 'cancel':
280 $this->getOutput()->redirect( $this->getPageTitle()->getFullURL() );
281 return false;
282 }
283
284 return false;
285 }
286
287 private function save( array $data ) {
288 $bp = BotPassword::newUnsaved( [
289 'centralId' => $this->userId,
290 'appId' => $this->par,
291 'restrictions' => $data['restrictions'],
292 'grants' => array_merge(
293 MWGrants::getHiddenGrants(),
294 preg_replace( '/^grant-/', '', $data['grants'] )
295 )
296 ] );
297
298 if ( $this->operation === 'insert' || !empty( $data['resetPassword'] ) ) {
299 $this->password = BotPassword::generatePassword( $this->getConfig() );
300 $passwordFactory = new PasswordFactory();
301 $passwordFactory->init( RequestContext::getMain()->getConfig() );
302 $password = $passwordFactory->newFromPlaintext( $this->password );
303 } else {
304 $password = null;
305 }
306
307 if ( $bp->save( $this->operation, $password ) ) {
308 $this->logger->info(
309 "Bot password {op} for {user}@{app_id}",
310 [
311 'op' => $this->operation,
312 'user' => $this->getUser()->getName(),
313 'app_id' => $this->par,
314 'centralId' => $this->userId,
315 'restrictions' => $data['restrictions'],
316 'grants' => $bp->getGrants(),
317 'client_ip' => $this->getRequest()->getIP()
318 ]
319 );
320 return Status::newGood();
321 } else {
322 // Messages: botpasswords-insert-failed, botpasswords-update-failed
323 return Status::newFatal( "botpasswords-{$this->operation}-failed", $this->par );
324 }
325 }
326
327 public function onSuccess() {
328 $out = $this->getOutput();
329
330 $username = $this->getUser()->getName();
331 switch ( $this->operation ) {
332 case 'insert':
333 $out->setPageTitle( $this->msg( 'botpasswords-created-title' )->text() );
334 $out->addWikiMsg( 'botpasswords-created-body', $this->par, $username );
335 break;
336
337 case 'update':
338 $out->setPageTitle( $this->msg( 'botpasswords-updated-title' )->text() );
339 $out->addWikiMsg( 'botpasswords-updated-body', $this->par, $username );
340 break;
341
342 case 'delete':
343 $out->setPageTitle( $this->msg( 'botpasswords-deleted-title' )->text() );
344 $out->addWikiMsg( 'botpasswords-deleted-body', $this->par, $username );
345 $this->password = null;
346 break;
347 }
348
349 if ( $this->password !== null ) {
350 $sep = BotPassword::getSeparator();
351 $out->addWikiMsg(
352 'botpasswords-newpassword',
353 htmlspecialchars( $username . $sep . $this->par ),
354 htmlspecialchars( $this->password ),
355 htmlspecialchars( $username ),
356 htmlspecialchars( $this->par . $sep . $this->password )
357 );
358 $this->password = null;
359 }
360
361 $out->addReturnTo( $this->getPageTitle() );
362 }
363
364 protected function getGroupName() {
365 return 'users';
366 }
367
368 protected function getDisplayFormat() {
369 return 'ooui';
370 }
371 }