Merge "Log failure reasons in ApiLogin"
[lhc/web/wiklou.git] / includes / auth / AuthenticationRequest.php
1 <?php
2 /**
3 * Authentication request value object
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 Auth
22 */
23
24 namespace MediaWiki\Auth;
25
26 use Message;
27
28 /**
29 * This is a value object for authentication requests.
30 *
31 * An AuthenticationRequest represents a set of form fields that are needed on
32 * and provided from the login, account creation, or password change forms.
33 *
34 * @ingroup Auth
35 * @since 1.27
36 */
37 abstract class AuthenticationRequest {
38
39 /** Indicates that the request is not required for authentication to proceed. */
40 const OPTIONAL = 0;
41
42 /** Indicates that the request is required for authentication to proceed. */
43 const REQUIRED = 1;
44
45 /** Indicates that the request is required by a primary authentication
46 * provdier. Since the user can choose which primary to authenticate with,
47 * the request might or might not end up being actually required. */
48 const PRIMARY_REQUIRED = 2;
49
50 /** @var string|null The AuthManager::ACTION_* constant this request was
51 * created to be used for. The *_CONTINUE constants are not used here, the
52 * corresponding "begin" constant is used instead.
53 */
54 public $action = null;
55
56 /** @var int For login, continue, and link actions, one of self::OPTIONAL,
57 * self::REQUIRED, or self::PRIMARY_REQUIRED */
58 public $required = self::REQUIRED;
59
60 /** @var string|null Return-to URL, in case of redirect */
61 public $returnToUrl = null;
62
63 /** @var string|null Username. May not be used by all subclasses. */
64 public $username = null;
65
66 /**
67 * Supply a unique key for deduplication
68 *
69 * When the AuthenticationRequests instances returned by the providers are
70 * merged, the value returned here is used for keeping only one copy of
71 * duplicate requests.
72 *
73 * Subclasses should override this if multiple distinct instances would
74 * make sense, i.e. the request class has internal state of some sort.
75 *
76 * This value might be exposed to the user in web forms so it should not
77 * contain private information.
78 *
79 * @return string
80 */
81 public function getUniqueId() {
82 return get_called_class();
83 }
84
85 /**
86 * Fetch input field info
87 *
88 * The field info is an associative array mapping field names to info
89 * arrays. The info arrays have the following keys:
90 * - type: (string) Type of input. Types and equivalent HTML widgets are:
91 * - string: <input type="text">
92 * - password: <input type="password">
93 * - select: <select>
94 * - checkbox: <input type="checkbox">
95 * - multiselect: More a grid of checkboxes than <select multi>
96 * - button: <input type="submit"> (uses 'label' as button text)
97 * - hidden: Not visible to the user, but needs to be preserved for the next request
98 * - null: No widget, just display the 'label' message.
99 * - options: (array) Maps option values to Messages for the
100 * 'select' and 'multiselect' types.
101 * - value: (string) Value (for 'null' and 'hidden') or default value (for other types).
102 * - label: (Message) Text suitable for a label in an HTML form
103 * - help: (Message) Text suitable as a description of what the field is
104 * - optional: (bool) If set and truthy, the field may be left empty
105 *
106 * @return array As above
107 */
108 abstract public function getFieldInfo();
109
110 /**
111 * Returns metadata about this request.
112 *
113 * This is mainly for the benefit of API clients which need more detailed render hints
114 * than what's available through getFieldInfo(). Semantics are unspecified and left to the
115 * individual subclasses, but the contents of the array should be primitive types so that they
116 * can be transformed into JSON or similar formats.
117 *
118 * @return array A (possibly nested) array with primitive types
119 */
120 public function getMetadata() {
121 return [];
122 }
123
124 /**
125 * Initialize form submitted form data.
126 *
127 * Should always return false if self::getFieldInfo() returns an empty
128 * array.
129 *
130 * @param array $data Submitted data as an associative array
131 * @return bool Whether the request data was successfully loaded
132 */
133 public function loadFromSubmission( array $data ) {
134 $fields = array_filter( $this->getFieldInfo(), function ( $info ) {
135 return $info['type'] !== 'null';
136 } );
137 if ( !$fields ) {
138 return false;
139 }
140
141 foreach ( $fields as $field => $info ) {
142 // Checkboxes and buttons are special. Depending on the method used
143 // to populate $data, they might be unset meaning false or they
144 // might be boolean. Further, image buttons might submit the
145 // coordinates of the click rather than the expected value.
146 if ( $info['type'] === 'checkbox' || $info['type'] === 'button' ) {
147 $this->$field = isset( $data[$field] ) && $data[$field] !== false
148 || isset( $data["{$field}_x"] ) && $data["{$field}_x"] !== false;
149 if ( !$this->$field && empty( $info['optional'] ) ) {
150 return false;
151 }
152 continue;
153 }
154
155 // Multiselect are too, slightly
156 if ( !isset( $data[$field] ) && $info['type'] === 'multiselect' ) {
157 $data[$field] = [];
158 }
159
160 if ( !isset( $data[$field] ) ) {
161 return false;
162 }
163 if ( $data[$field] === '' || $data[$field] === [] ) {
164 if ( empty( $info['optional'] ) ) {
165 return false;
166 }
167 } else {
168 switch ( $info['type'] ) {
169 case 'select':
170 if ( !isset( $info['options'][$data[$field]] ) ) {
171 return false;
172 }
173 break;
174
175 case 'multiselect':
176 $data[$field] = (array)$data[$field];
177 $allowed = array_keys( $info['options'] );
178 if ( array_diff( $data[$field], $allowed ) !== [] ) {
179 return false;
180 }
181 break;
182 }
183 }
184
185 $this->$field = $data[$field];
186 }
187
188 return true;
189 }
190
191 /**
192 * Describe the credentials represented by this request
193 *
194 * This is used on requests returned by
195 * AuthenticationProvider::getAuthenticationRequests() for ACTION_LINK
196 * and ACTION_REMOVE and for requests returned in
197 * AuthenticationResponse::$linkRequest to create useful user interfaces.
198 *
199 * @return Message[] with the following keys:
200 * - provider: A Message identifying the service that provides
201 * the credentials, e.g. the name of the third party authentication
202 * service.
203 * - account: A Message identifying the credentials themselves,
204 * e.g. the email address used with the third party authentication
205 * service.
206 */
207 public function describeCredentials() {
208 return [
209 'provider' => new \RawMessage( '$1', [ get_called_class() ] ),
210 'account' => new \RawMessage( '$1', [ $this->getUniqueId() ] ),
211 ];
212 }
213
214 /**
215 * Update a set of requests with form submit data, discarding ones that fail
216 * @param AuthenticationRequest[] $reqs
217 * @param array $data
218 * @return AuthenticationRequest[]
219 */
220 public static function loadRequestsFromSubmission( array $reqs, array $data ) {
221 return array_values( array_filter( $reqs, function ( $req ) use ( $data ) {
222 return $req->loadFromSubmission( $data );
223 } ) );
224 }
225
226 /**
227 * Select a request by class name.
228 * @param AuthenticationRequest[] $reqs
229 * @param string $class Class name
230 * @param bool $allowSubclasses If true, also returns any request that's a subclass of the given
231 * class.
232 * @return AuthenticationRequest|null Returns null if there is not exactly
233 * one matching request.
234 */
235 public static function getRequestByClass( array $reqs, $class, $allowSubclasses = false ) {
236 $requests = array_filter( $reqs, function ( $req ) use ( $class, $allowSubclasses ) {
237 if ( $allowSubclasses ) {
238 return is_a( $req, $class, false );
239 } else {
240 return get_class( $req ) === $class;
241 }
242 } );
243 return count( $requests ) === 1 ? reset( $requests ) : null;
244 }
245
246 /**
247 * Get the username from the set of requests
248 *
249 * Only considers requests that have a "username" field.
250 *
251 * @param AuthenticationRequest[] $requests
252 * @return string|null
253 * @throws \UnexpectedValueException If multiple different usernames are present.
254 */
255 public static function getUsernameFromRequests( array $reqs ) {
256 $username = null;
257 $otherClass = null;
258 foreach ( $reqs as $req ) {
259 $info = $req->getFieldInfo();
260 if ( $info && array_key_exists( 'username', $info ) && $req->username !== null ) {
261 if ( $username === null ) {
262 $username = $req->username;
263 $otherClass = get_class( $req );
264 } elseif ( $username !== $req->username ) {
265 $requestClass = get_class( $req );
266 throw new \UnexpectedValueException( "Conflicting username fields: \"{$req->username}\" from "
267 . "$requestClass::\$username vs. \"$username\" from $otherClass::\$username" );
268 }
269 }
270 }
271 return $username;
272 }
273
274 /**
275 * Merge the output of multiple AuthenticationRequest::getFieldInfo() calls.
276 * @param AuthenticationRequest[] $reqs
277 * @return array
278 * @throws \UnexpectedValueException If fields cannot be merged
279 */
280 public static function mergeFieldInfo( array $reqs ) {
281 $merged = [];
282
283 // fields that are required by some primary providers but not others are not actually required
284 $primaryRequests = array_filter( $reqs, function ( $req ) {
285 return $req->required === AuthenticationRequest::PRIMARY_REQUIRED;
286 } );
287 $sharedRequiredPrimaryFields = array_reduce( $primaryRequests, function ( $shared, $req ) {
288 $required = array_keys( array_filter( $req->getFieldInfo(), function ( $options ) {
289 return empty( $options['optional'] );
290 } ) );
291 if ( $shared === null ) {
292 return $required;
293 } else {
294 return array_intersect( $shared, $required );
295 }
296 }, null );
297
298 foreach ( $reqs as $req ) {
299 $info = $req->getFieldInfo();
300 if ( !$info ) {
301 continue;
302 }
303
304 foreach ( $info as $name => $options ) {
305 if (
306 // If the request isn't required, its fields aren't required either.
307 $req->required === self::OPTIONAL
308 // If there is a primary not requiring this field, no matter how many others do,
309 // authentication can proceed without it.
310 || $req->required === self::PRIMARY_REQUIRED
311 && !in_array( $name, $sharedRequiredPrimaryFields, true )
312 ) {
313 $options['optional'] = true;
314 } else {
315 $options['optional'] = !empty( $options['optional'] );
316 }
317
318 if ( !array_key_exists( $name, $merged ) ) {
319 $merged[$name] = $options;
320 } elseif ( $merged[$name]['type'] !== $options['type'] ) {
321 throw new \UnexpectedValueException( "Field type conflict for \"$name\", " .
322 "\"{$merged[$name]['type']}\" vs \"{$options['type']}\""
323 );
324 } else {
325 if ( isset( $options['options'] ) ) {
326 if ( isset( $merged[$name]['options'] ) ) {
327 $merged[$name]['options'] += $options['options'];
328 } else {
329 // @codeCoverageIgnoreStart
330 $merged[$name]['options'] = $options['options'];
331 // @codeCoverageIgnoreEnd
332 }
333 }
334
335 $merged[$name]['optional'] = $merged[$name]['optional'] && $options['optional'];
336
337 // No way to merge 'value', 'image', 'help', or 'label', so just use
338 // the value from the first request.
339 }
340 }
341 }
342
343 return $merged;
344 }
345
346 /**
347 * Implementing this mainly for use from the unit tests.
348 * @param array $data
349 * @return AuthenticationRequest
350 */
351 public static function __set_state( $data ) {
352 $ret = new static();
353 foreach ( $data as $k => $v ) {
354 $ret->$k = $v;
355 }
356 return $ret;
357 }
358 }