Merge "Handle missing namespace prefix in XML dumps more gracefully"
[lhc/web/wiklou.git] / includes / api / ApiAuthManagerHelper.php
1 <?php
2 /**
3 * Copyright © 2016 Brad Jorsch <bjorsch@wikimedia.org>
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 * @since 1.27
22 */
23
24 use MediaWiki\Auth\AuthManager;
25 use MediaWiki\Auth\AuthenticationRequest;
26 use MediaWiki\Auth\AuthenticationResponse;
27 use MediaWiki\Auth\CreateFromLoginAuthenticationRequest;
28 use MediaWiki\Logger\LoggerFactory;
29
30 /**
31 * Helper class for AuthManager-using API modules. Intended for use via
32 * composition.
33 *
34 * @ingroup API
35 */
36 class ApiAuthManagerHelper {
37
38 /** @var ApiBase API module, for context and parameters */
39 private $module;
40
41 /** @var string Message output format */
42 private $messageFormat;
43
44 /**
45 * @param ApiBase $module API module, for context and parameters
46 */
47 public function __construct( ApiBase $module ) {
48 $this->module = $module;
49
50 $params = $module->extractRequestParams();
51 $this->messageFormat = isset( $params['messageformat'] ) ? $params['messageformat'] : 'wikitext';
52 }
53
54 /**
55 * Static version of the constructor, for chaining
56 * @param ApiBase $module API module, for context and parameters
57 * @return ApiAuthManagerHelper
58 */
59 public static function newForModule( ApiBase $module ) {
60 return new self( $module );
61 }
62
63 /**
64 * Format a message for output
65 * @param array &$res Result array
66 * @param string $key Result key
67 * @param Message $message
68 */
69 private function formatMessage( array &$res, $key, Message $message ) {
70 switch ( $this->messageFormat ) {
71 case 'none':
72 break;
73
74 case 'wikitext':
75 $res[$key] = $message->setContext( $this->module )->text();
76 break;
77
78 case 'html':
79 $res[$key] = $message->setContext( $this->module )->parseAsBlock();
80 $res[$key] = Parser::stripOuterParagraph( $res[$key] );
81 break;
82
83 case 'raw':
84 $res[$key] = [
85 'key' => $message->getKey(),
86 'params' => $message->getParams(),
87 ];
88 ApiResult::setIndexedTagName( $res[$key]['params'], 'param' );
89 break;
90 }
91 }
92
93 /**
94 * Call $manager->securitySensitiveOperationStatus()
95 * @param string $operation Operation being checked.
96 * @throws ApiUsageException
97 */
98 public function securitySensitiveOperation( $operation ) {
99 $status = AuthManager::singleton()->securitySensitiveOperationStatus( $operation );
100 switch ( $status ) {
101 case AuthManager::SEC_OK:
102 return;
103
104 case AuthManager::SEC_REAUTH:
105 $this->module->dieWithError( 'apierror-reauthenticate' );
106
107 case AuthManager::SEC_FAIL:
108 $this->module->dieWithError( 'apierror-cannotreauthenticate' );
109
110 default:
111 throw new UnexpectedValueException( "Unknown status \"$status\"" );
112 }
113 }
114
115 /**
116 * Filter out authentication requests by class name
117 * @param AuthenticationRequest[] $reqs Requests to filter
118 * @param string[] $blacklist Class names to remove
119 * @return AuthenticationRequest[]
120 */
121 public static function blacklistAuthenticationRequests( array $reqs, array $blacklist ) {
122 if ( $blacklist ) {
123 $blacklist = array_flip( $blacklist );
124 $reqs = array_filter( $reqs, function ( $req ) use ( $blacklist ) {
125 return !isset( $blacklist[get_class( $req )] );
126 } );
127 }
128 return $reqs;
129 }
130
131 /**
132 * Fetch and load the AuthenticationRequests for an action
133 * @param string $action One of the AuthManager::ACTION_* constants
134 * @return AuthenticationRequest[]
135 */
136 public function loadAuthenticationRequests( $action ) {
137 $params = $this->module->extractRequestParams();
138
139 $manager = AuthManager::singleton();
140 $reqs = $manager->getAuthenticationRequests( $action, $this->module->getUser() );
141
142 // Filter requests, if requested to do so
143 $wantedRequests = null;
144 if ( isset( $params['requests'] ) ) {
145 $wantedRequests = array_flip( $params['requests'] );
146 } elseif ( isset( $params['request'] ) ) {
147 $wantedRequests = [ $params['request'] => true ];
148 }
149 if ( $wantedRequests !== null ) {
150 $reqs = array_filter( $reqs, function ( $req ) use ( $wantedRequests ) {
151 return isset( $wantedRequests[$req->getUniqueId()] );
152 } );
153 }
154
155 // Collect the fields for all the requests
156 $fields = [];
157 $sensitive = [];
158 foreach ( $reqs as $req ) {
159 $info = (array)$req->getFieldInfo();
160 $fields += $info;
161 $sensitive += array_filter( $info, function ( $opts ) {
162 return !empty( $opts['sensitive'] );
163 } );
164 }
165
166 // Extract the request data for the fields and mark those request
167 // parameters as used
168 $data = array_intersect_key( $this->module->getRequest()->getValues(), $fields );
169 $this->module->getMain()->markParamsUsed( array_keys( $data ) );
170
171 if ( $sensitive ) {
172 $this->module->requirePostedParameters( array_keys( $sensitive ), 'noprefix' );
173 }
174
175 return AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
176 }
177
178 /**
179 * Format an AuthenticationResponse for return
180 * @param AuthenticationResponse $res
181 * @return array
182 */
183 public function formatAuthenticationResponse( AuthenticationResponse $res ) {
184 $ret = [
185 'status' => $res->status,
186 ];
187
188 if ( $res->status === AuthenticationResponse::PASS && $res->username !== null ) {
189 $ret['username'] = $res->username;
190 }
191
192 if ( $res->status === AuthenticationResponse::REDIRECT ) {
193 $ret['redirecttarget'] = $res->redirectTarget;
194 if ( $res->redirectApiData !== null ) {
195 $ret['redirectdata'] = $res->redirectApiData;
196 }
197 }
198
199 if ( $res->status === AuthenticationResponse::REDIRECT ||
200 $res->status === AuthenticationResponse::UI ||
201 $res->status === AuthenticationResponse::RESTART
202 ) {
203 $ret += $this->formatRequests( $res->neededRequests );
204 }
205
206 if ( $res->status === AuthenticationResponse::FAIL ||
207 $res->status === AuthenticationResponse::UI ||
208 $res->status === AuthenticationResponse::RESTART
209 ) {
210 $this->formatMessage( $ret, 'message', $res->message );
211 $ret['messagecode'] = ApiMessage::create( $res->message )->getApiCode();
212 }
213
214 if ( $res->status === AuthenticationResponse::FAIL ||
215 $res->status === AuthenticationResponse::RESTART
216 ) {
217 $this->module->getRequest()->getSession()->set(
218 'ApiAuthManagerHelper::createRequest',
219 $res->createRequest
220 );
221 $ret['canpreservestate'] = $res->createRequest !== null;
222 } else {
223 $this->module->getRequest()->getSession()->remove( 'ApiAuthManagerHelper::createRequest' );
224 }
225
226 return $ret;
227 }
228
229 /**
230 * Logs successful or failed authentication.
231 * @param string|AuthenticationResponse $result Response or error message
232 * @param string $event Event type (e.g. 'accountcreation')
233 */
234 public function logAuthenticationResult( $event, $result ) {
235 if ( is_string( $result ) ) {
236 $status = Status::newFatal( $result );
237 } elseif ( $result->status === AuthenticationResponse::PASS ) {
238 $status = Status::newGood();
239 } elseif ( $result->status === AuthenticationResponse::FAIL ) {
240 $status = Status::newFatal( $result->message );
241 } else {
242 return;
243 }
244
245 $module = $this->module->getModuleName();
246 LoggerFactory::getInstance( 'authevents' )->info( "$module API attempt", [
247 'event' => $event,
248 'status' => $status,
249 'module' => $module,
250 ] );
251 }
252
253 /**
254 * Fetch the preserved CreateFromLoginAuthenticationRequest, if any
255 * @return CreateFromLoginAuthenticationRequest|null
256 */
257 public function getPreservedRequest() {
258 $ret = $this->module->getRequest()->getSession()->get( 'ApiAuthManagerHelper::createRequest' );
259 return $ret instanceof CreateFromLoginAuthenticationRequest ? $ret : null;
260 }
261
262 /**
263 * Format an array of AuthenticationRequests for return
264 * @param AuthenticationRequest[] $reqs
265 * @return array Will have a 'requests' key, and also 'fields' if $module's
266 * params include 'mergerequestfields'.
267 */
268 public function formatRequests( array $reqs ) {
269 $params = $this->module->extractRequestParams();
270 $mergeFields = !empty( $params['mergerequestfields'] );
271
272 $ret = [ 'requests' => [] ];
273 foreach ( $reqs as $req ) {
274 $describe = $req->describeCredentials();
275 $reqInfo = [
276 'id' => $req->getUniqueId(),
277 'metadata' => $req->getMetadata() + [ ApiResult::META_TYPE => 'assoc' ],
278 ];
279 switch ( $req->required ) {
280 case AuthenticationRequest::OPTIONAL:
281 $reqInfo['required'] = 'optional';
282 break;
283 case AuthenticationRequest::REQUIRED:
284 $reqInfo['required'] = 'required';
285 break;
286 case AuthenticationRequest::PRIMARY_REQUIRED:
287 $reqInfo['required'] = 'primary-required';
288 break;
289 }
290 $this->formatMessage( $reqInfo, 'provider', $describe['provider'] );
291 $this->formatMessage( $reqInfo, 'account', $describe['account'] );
292 if ( !$mergeFields ) {
293 $reqInfo['fields'] = $this->formatFields( (array)$req->getFieldInfo() );
294 }
295 $ret['requests'][] = $reqInfo;
296 }
297
298 if ( $mergeFields ) {
299 $fields = AuthenticationRequest::mergeFieldInfo( $reqs );
300 $ret['fields'] = $this->formatFields( $fields );
301 }
302
303 return $ret;
304 }
305
306 /**
307 * Clean up a field array for output
308 * @param ApiBase $module For context and parameters 'mergerequestfields'
309 * and 'messageformat'
310 * @param array $fields
311 * @return array
312 */
313 private function formatFields( array $fields ) {
314 static $copy = [
315 'type' => true,
316 'value' => true,
317 ];
318
319 $module = $this->module;
320 $retFields = [];
321
322 foreach ( $fields as $name => $field ) {
323 $ret = array_intersect_key( $field, $copy );
324
325 if ( isset( $field['options'] ) ) {
326 $ret['options'] = array_map( function ( $msg ) use ( $module ) {
327 return $msg->setContext( $module )->plain();
328 }, $field['options'] );
329 ApiResult::setArrayType( $ret['options'], 'assoc' );
330 }
331 $this->formatMessage( $ret, 'label', $field['label'] );
332 $this->formatMessage( $ret, 'help', $field['help'] );
333 $ret['optional'] = !empty( $field['optional'] );
334 $ret['sensitive'] = !empty( $field['sensitive'] );
335
336 $retFields[$name] = $ret;
337 }
338
339 ApiResult::setArrayType( $retFields, 'assoc' );
340
341 return $retFields;
342 }
343
344 /**
345 * Fetch the standard parameters this helper recognizes
346 * @param string $action AuthManager action
347 * @param string $param... Parameters to use
348 * @return array
349 */
350 public static function getStandardParams( $action, $param /* ... */ ) {
351 $params = [
352 'requests' => [
353 ApiBase::PARAM_TYPE => 'string',
354 ApiBase::PARAM_ISMULTI => true,
355 ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-requests', $action ],
356 ],
357 'request' => [
358 ApiBase::PARAM_TYPE => 'string',
359 ApiBase::PARAM_REQUIRED => true,
360 ApiBase::PARAM_HELP_MSG => [ 'api-help-authmanagerhelper-request', $action ],
361 ],
362 'messageformat' => [
363 ApiBase::PARAM_DFLT => 'wikitext',
364 ApiBase::PARAM_TYPE => [ 'html', 'wikitext', 'raw', 'none' ],
365 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-messageformat',
366 ],
367 'mergerequestfields' => [
368 ApiBase::PARAM_DFLT => false,
369 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-mergerequestfields',
370 ],
371 'preservestate' => [
372 ApiBase::PARAM_DFLT => false,
373 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-preservestate',
374 ],
375 'returnurl' => [
376 ApiBase::PARAM_TYPE => 'string',
377 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-returnurl',
378 ],
379 'continue' => [
380 ApiBase::PARAM_DFLT => false,
381 ApiBase::PARAM_HELP_MSG => 'api-help-authmanagerhelper-continue',
382 ],
383 ];
384
385 $ret = [];
386 $wantedParams = func_get_args();
387 array_shift( $wantedParams );
388 foreach ( $wantedParams as $name ) {
389 if ( isset( $params[$name] ) ) {
390 $ret[$name] = $params[$name];
391 }
392 }
393 return $ret;
394 }
395 }