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