Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
97.03% |
294 / 303 |
|
76.92% |
10 / 13 |
CRAP | |
0.00% |
0 / 1 |
| ConsumerValidator | |
97.03% |
294 / 303 |
|
76.92% |
10 / 13 |
90 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| validateFields | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 | |||
| validateFieldsAndThrow | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
| getValidatorCallbacks | |
98.28% |
114 / 116 |
|
0.00% |
0 / 1 |
27 | |||
| expandConsumerData | |
90.00% |
36 / 40 |
|
0.00% |
0 / 1 |
15.22 | |||
| validateCallbackUrl | |
93.48% |
43 / 46 |
|
0.00% |
0 / 1 |
21.12 | |||
| isSecureContext | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
9 | |||
| getErrorStatus | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getGenericErrorStatus | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| getTooLongErrorStatus | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getStatusFormatter | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getConsumerFields | |
100.00% |
64 / 64 |
|
100.00% |
1 / 1 |
6 | |||
| raiseInvalidConfigError | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace MediaWiki\Extension\OAuth\Control; |
| 4 | |
| 5 | use Composer\Semver\VersionParser; |
| 6 | use MediaWiki\Api\ApiMessage; |
| 7 | use MediaWiki\Config\ServiceOptions; |
| 8 | use MediaWiki\Context\RequestContext; |
| 9 | use MediaWiki\Extension\OAuth\Backend\Consumer; |
| 10 | use MediaWiki\Extension\OAuth\Backend\NormalizedOAuthException; |
| 11 | use MediaWiki\Extension\OAuth\Backend\Utils; |
| 12 | use MediaWiki\Extension\OAuth\Entity\ClientEntity; |
| 13 | use MediaWiki\Extension\OAuth\Lib\OAuthException; |
| 14 | use MediaWiki\Json\FormatJson; |
| 15 | use MediaWiki\Language\FormatterFactory; |
| 16 | use MediaWiki\MainConfigNames; |
| 17 | use MediaWiki\Parser\Sanitizer; |
| 18 | use MediaWiki\SpecialPage\SpecialPage; |
| 19 | use MediaWiki\Status\StatusFormatter; |
| 20 | use MediaWiki\User\CentralId\CentralIdLookup; |
| 21 | use MediaWiki\Utils\MWCryptRand; |
| 22 | use MediaWiki\Utils\MWRestrictions; |
| 23 | use MediaWiki\WikiMap\WikiMap; |
| 24 | use StatusValue; |
| 25 | use UnexpectedValueException; |
| 26 | use Wikimedia\Assert\Assert; |
| 27 | use Wikimedia\Assert\ParameterTypeException; |
| 28 | use Wikimedia\Timestamp\ConvertibleTimestamp; |
| 29 | |
| 30 | /** |
| 31 | * Validates data sets representing Consumer objects. The data is either from a web request |
| 32 | * (e.g. Special:OAuthConsumerRegistration submission) or from configuration (e.g. $wgOAuthStaticApps), |
| 33 | * with significant differences in how they are validated. |
| 34 | */ |
| 35 | class ConsumerValidator { |
| 36 | |
| 37 | public const SERVICE_OPTIONS = [ |
| 38 | MainConfigNames::NoReplyAddress, |
| 39 | ]; |
| 40 | |
| 41 | /** |
| 42 | * MySQL Blob Size is 2^16 - 1 = 65535 as per "L + 2 bytes, where L < 216" on |
| 43 | * https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html |
| 44 | */ |
| 45 | public const BLOB_SIZE = 65535; |
| 46 | |
| 47 | /** |
| 48 | * Field name => Wikimedia\Assert type(s) |
| 49 | */ |
| 50 | private const FIELD_TYPES = [ |
| 51 | Consumer::FIELD_ID => 'integer', |
| 52 | Consumer::FIELD_CONSUMER_KEY => 'string', |
| 53 | Consumer::FIELD_NAME => 'string', |
| 54 | Consumer::FIELD_USER_ID => 'integer', |
| 55 | Consumer::FIELD_VERSION => 'string', |
| 56 | Consumer::FIELD_CALLBACK_URL => 'string', |
| 57 | Consumer::FIELD_CALLBACK_IS_PREFIX => 'boolean', |
| 58 | Consumer::FIELD_DESCRIPTION => 'string', |
| 59 | Consumer::FIELD_EMAIL => 'string', |
| 60 | Consumer::FIELD_OAUTH_VERSION => 'integer', |
| 61 | Consumer::FIELD_OWNER_ONLY => 'boolean', |
| 62 | Consumer::FIELD_WIKI => 'string', |
| 63 | Consumer::FIELD_GRANTS => 'array', |
| 64 | Consumer::FIELD_SECRET_KEY => 'string', |
| 65 | Consumer::FIELD_RSA_KEY => 'string', |
| 66 | Consumer::FIELD_OAUTH2_IS_CONFIDENTIAL => 'boolean', |
| 67 | Consumer::FIELD_RESTRICTIONS => MWRestrictions::class, |
| 68 | ]; |
| 69 | |
| 70 | public function __construct( |
| 71 | private readonly ServiceOptions $options, |
| 72 | private readonly FormatterFactory $formatterFactory, |
| 73 | ) { |
| 74 | $this->options->assertRequiredOptions( self::SERVICE_OPTIONS ); |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * Takes an array of consumer data and returns a validation status. |
| 79 | * |
| 80 | * Validation only checks the values of the provided fields - it does not check whether |
| 81 | * the data is sufficient to define a consumer, and it ignores unknown fields. It also |
| 82 | * cannot handle a value that is the wrong PHP type. Use expandConsumerData() for that. |
| 83 | * |
| 84 | * Warnings should be surfaced to the user when submitting a new consumer, but the user |
| 85 | * is allowed to ignore. Errors means this consumer should not be usable. |
| 86 | * |
| 87 | * @param array $fields <field name> => <value>; field names should match the |
| 88 | * Consumer::FIELD_* constants. |
| 89 | */ |
| 90 | public function validateFields( array $fields ): StatusValue { |
| 91 | $validatorCallbacks = $this->getValidatorCallbacks(); |
| 92 | $status = StatusValue::newGood(); |
| 93 | foreach ( $fields as $fieldName => $fieldValue ) { |
| 94 | $callback = $validatorCallbacks[$fieldName] ?? null; |
| 95 | if ( $callback ) { |
| 96 | $status->merge( $callback( $fieldValue, $fields ) ); |
| 97 | } |
| 98 | } |
| 99 | return $status; |
| 100 | } |
| 101 | |
| 102 | /** |
| 103 | * Like validateFields() but throws on error. |
| 104 | * |
| 105 | * @throws OAuthException |
| 106 | */ |
| 107 | public function validateFieldsAndThrow( array $fields ): void { |
| 108 | $status = $this->validateFields( $fields ); |
| 109 | if ( !$status->isOK() ) { |
| 110 | throw new NormalizedOAuthException( 'Consumer {consumer_key} is invalid: {reason}', [ |
| 111 | 'consumer_key' => $fields[Consumer::FIELD_CONSUMER_KEY] ?? '', |
| 112 | 'reason' => $this->getStatusFormatter()->getWikiText( $status, [ 'lang' => 'en' ] ), |
| 113 | ] ); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /** |
| 118 | * Returns an array of validator callbacks, indexed by field names. |
| 119 | * |
| 120 | * Callbacks take the field value and the array of all field values as arguments, |
| 121 | * and return a status which is either good or has a single warning or fatal error message |
| 122 | * in it. The single message is always an ApiMessage. Warnings are informational and can be |
| 123 | * ignored by the caller. |
| 124 | * |
| 125 | * PHP type validation (e.g. a field having a scalar value when it should be an array) is the |
| 126 | * caller's responsibility. Note that field types might differ in type-juggling-compatible |
| 127 | * ways between callers. |
| 128 | * |
| 129 | * @phan-return array<string,callable(mixed,array):StatusValue> |
| 130 | */ |
| 131 | public function getValidatorCallbacks(): array { |
| 132 | $alwaysValid = static function (): StatusValue { |
| 133 | return StatusValue::newGood(); |
| 134 | }; |
| 135 | $validateBlobSize = function ( $fieldName, $fieldValue ): StatusValue { |
| 136 | if ( strlen( $fieldValue ?? '' ) < self::BLOB_SIZE ) { |
| 137 | return StatusValue::newGood(); |
| 138 | } else { |
| 139 | return $this->getTooLongErrorStatus( $fieldName, self::BLOB_SIZE - 1 ); |
| 140 | } |
| 141 | }; |
| 142 | |
| 143 | return [ |
| 144 | Consumer::FIELD_ID => $alwaysValid, |
| 145 | Consumer::FIELD_CONSUMER_KEY => $alwaysValid, |
| 146 | Consumer::FIELD_NAME => function ( string $name ): StatusValue { |
| 147 | $len = strlen( $name ); |
| 148 | if ( !$len ) { |
| 149 | // unlikely to be reached due to HTMLForm validation, don't bother with a nice error |
| 150 | return $this->getGenericErrorStatus( Consumer::FIELD_NAME ); |
| 151 | } elseif ( $len > 128 ) { |
| 152 | return $this->getTooLongErrorStatus( Consumer::FIELD_NAME, 128 ); |
| 153 | } |
| 154 | return StatusValue::newGood(); |
| 155 | }, |
| 156 | Consumer::FIELD_USER_ID => function ( int $userId ): StatusValue { |
| 157 | $userName = Utils::getCentralIdLookup()->nameFromCentralId( |
| 158 | $userId, |
| 159 | CentralIdLookup::AUDIENCE_RAW |
| 160 | ); |
| 161 | return ( $userName === null ) |
| 162 | ? $this->getErrorStatus( Consumer::FIELD_USER_ID, 'mwoauth-invalid-field-userId' ) |
| 163 | : StatusValue::newGood(); |
| 164 | }, |
| 165 | Consumer::FIELD_VERSION => function ( string $version ): StatusValue { |
| 166 | if ( strlen( $version ) > 32 ) { |
| 167 | return $this->getTooLongErrorStatus( Consumer::FIELD_VERSION, 32 ); |
| 168 | } |
| 169 | $parser = new VersionParser(); |
| 170 | try { |
| 171 | $parser->normalize( $version ); |
| 172 | } catch ( UnexpectedValueException $e ) { |
| 173 | // can't be localized - probably still more useful than not providing details |
| 174 | $error = wfEscapeWikiText( $e->getMessage() ); |
| 175 | return $this->getGenericErrorStatus( Consumer::FIELD_VERSION, $error ); |
| 176 | } |
| 177 | return StatusValue::newGood(); |
| 178 | }, |
| 179 | Consumer::FIELD_CALLBACK_URL => $this->validateCallbackUrl( ... ), |
| 180 | Consumer::FIELD_CALLBACK_IS_PREFIX => $alwaysValid, |
| 181 | Consumer::FIELD_DESCRIPTION => static function ( $description ) use ( $validateBlobSize ): StatusValue { |
| 182 | return $validateBlobSize( Consumer::FIELD_DESCRIPTION, $description ); |
| 183 | }, |
| 184 | Consumer::FIELD_EMAIL => function ( $email ): StatusValue { |
| 185 | return Sanitizer::validateEmail( $email ) |
| 186 | ? StatusValue::newGood() |
| 187 | // can't happen, don't bother with a nice error |
| 188 | : $this->getGenericErrorStatus( Consumer::FIELD_EMAIL ); |
| 189 | }, |
| 190 | // EMAIL_AUTHENTICATED is omitted because it is never sent by the user |
| 191 | Consumer::FIELD_OAUTH_VERSION => function ( $version ): StatusValue { |
| 192 | return in_array( $version, [ Consumer::OAUTH_VERSION_1, Consumer::OAUTH_VERSION_2 ] ) |
| 193 | ? StatusValue::newGood() |
| 194 | : $this->getGenericErrorStatus( Consumer::FIELD_OAUTH_VERSION ); |
| 195 | }, |
| 196 | Consumer::FIELD_DEVELOPER_AGREEMENT => function ( $agreed ): StatusValue { |
| 197 | return $agreed |
| 198 | ? StatusValue::newGood() |
| 199 | : $this->getGenericErrorStatus( Consumer::FIELD_DEVELOPER_AGREEMENT ); |
| 200 | }, |
| 201 | Consumer::FIELD_OWNER_ONLY => $alwaysValid, |
| 202 | Consumer::FIELD_WIKI => function ( $wikiId ): StatusValue { |
| 203 | global $wgConf; |
| 204 | if ( $wikiId === '*' |
| 205 | || in_array( $wikiId, $wgConf->getLocalDatabases() ) |
| 206 | || in_array( $wikiId, Utils::getAllWikiNames() ) |
| 207 | ) { |
| 208 | return StatusValue::newGood(); |
| 209 | } else { |
| 210 | return $this->getGenericErrorStatus( Consumer::FIELD_WIKI ); |
| 211 | } |
| 212 | }, |
| 213 | Consumer::FIELD_GRANTS => function ( $grants ): StatusValue { |
| 214 | if ( is_string( $grants ) ) { |
| 215 | $status = FormatJson::parse( $grants, FormatJson::FORCE_ASSOC ); |
| 216 | if ( !$status->isOK() ) { |
| 217 | return $status; |
| 218 | } |
| 219 | $grants = $status->getValue(); |
| 220 | } |
| 221 | if ( !is_array( $grants ) ) { |
| 222 | return $this->getGenericErrorStatus( Consumer::FIELD_GRANTS ); |
| 223 | } |
| 224 | $status = StatusValue::newGood(); |
| 225 | if ( !Utils::grantsAreValid( $grants, $status ) ) { |
| 226 | return $status; |
| 227 | } |
| 228 | if ( strlen( FormatJson::encode( $grants ) ) >= self::BLOB_SIZE ) { |
| 229 | return $this->getTooLongErrorStatus( Consumer::FIELD_GRANTS, self::BLOB_SIZE - 1 ); |
| 230 | } |
| 231 | |
| 232 | return StatusValue::newGood(); |
| 233 | }, |
| 234 | // REGISTRATION and SECRET_KEY are omitted because it is never sent by the user |
| 235 | Consumer::FIELD_RSA_KEY => function ( $keyAsString ): StatusValue { |
| 236 | if ( trim( $keyAsString ) === '' ) { |
| 237 | return StatusValue::newGood(); |
| 238 | } |
| 239 | if ( strlen( $keyAsString ) >= self::BLOB_SIZE ) { |
| 240 | return $this->getTooLongErrorStatus( Consumer::FIELD_RSA_KEY, self::BLOB_SIZE - 1 ); |
| 241 | } |
| 242 | $key = openssl_pkey_get_public( $keyAsString ); |
| 243 | if ( $key === false ) { |
| 244 | $error = wfEscapeWikiText( openssl_error_string() ); |
| 245 | return $this->getGenericErrorStatus( Consumer::FIELD_RSA_KEY, $error ); |
| 246 | } |
| 247 | $info = openssl_pkey_get_details( $key ); |
| 248 | if ( $info['type'] !== OPENSSL_KEYTYPE_RSA ) { |
| 249 | return $this->getErrorStatus( Consumer::FIELD_RSA_KEY, 'mwoauth-invalid-field-rsaKey-not-rsa' ); |
| 250 | } |
| 251 | return StatusValue::newGood(); |
| 252 | }, |
| 253 | Consumer::FIELD_RESTRICTIONS => static function ( $restrictions ) use ( $validateBlobSize ): StatusValue { |
| 254 | return $validateBlobSize( Consumer::FIELD_RESTRICTIONS, (string)$restrictions ); |
| 255 | }, |
| 256 | // STAGE, STAGE_TIMESTAMP and DELETED are omitted because it is never sent by the user |
| 257 | Consumer::FIELD_OAUTH2_IS_CONFIDENTIAL => $alwaysValid, |
| 258 | Consumer::FIELD_OAUTH2_GRANT_TYPES => function ( $oauth2Grants, $fields ): StatusValue { |
| 259 | if ( $fields['oauthVersion'] == Consumer::OAUTH_VERSION_1 ) { |
| 260 | return StatusValue::newGood(); |
| 261 | } |
| 262 | |
| 263 | // OAuth 2 apps must have at least one grant type |
| 264 | if ( !$oauth2Grants ) { |
| 265 | return $this->getGenericErrorStatus( Consumer::FIELD_OAUTH2_GRANT_TYPES ); |
| 266 | } |
| 267 | |
| 268 | if ( strlen( FormatJson::encode( $oauth2Grants ) ) >= self::BLOB_SIZE ) { |
| 269 | return $this->getTooLongErrorStatus( Consumer::FIELD_OAUTH2_GRANT_TYPES, self::BLOB_SIZE - 1 ); |
| 270 | } |
| 271 | |
| 272 | if ( |
| 273 | in_array( ClientEntity::GRANT_TYPE_CLIENT_CREDENTIALS, $oauth2Grants, true ) && |
| 274 | count( $oauth2Grants ) > 1 |
| 275 | ) { |
| 276 | return $this->getErrorStatus( |
| 277 | Consumer::FIELD_OAUTH2_GRANT_TYPES, |
| 278 | 'mwoauth-invalid-field-oauth2GrantTypes-mixed' |
| 279 | ); |
| 280 | } |
| 281 | |
| 282 | return StatusValue::newGood(); |
| 283 | }, |
| 284 | ]; |
| 285 | } |
| 286 | |
| 287 | /** |
| 288 | * Takes an array of Consumer data (in the same format as Consumer::toArray() but potentially |
| 289 | * with some of the fields missing) and expands it so all fields are present. Only fields |
| 290 | * that don't affect the consumer's behavior can be missing (e.g. OAuth 2 specific fields for |
| 291 | * an OAuth 1 consumer). |
| 292 | * |
| 293 | * It also validates that all required fields are present, all present fields are known, and |
| 294 | * all fields are of the correct type. It does not validate field values beyond that - use |
| 295 | * validateFields() for that. |
| 296 | * |
| 297 | * @param array $consumerData |
| 298 | * @return array |
| 299 | * @throws OAuthException |
| 300 | */ |
| 301 | public function expandConsumerData( array $consumerData ): array { |
| 302 | // check OAuth version first as it determines what fields are required |
| 303 | if ( !array_key_exists( Consumer::FIELD_OAUTH_VERSION, $consumerData ) ) { |
| 304 | $this->raiseInvalidConfigError( $consumerData, 'missing required field oauthVersion' ); |
| 305 | } |
| 306 | $oauthVersion = $consumerData[Consumer::FIELD_OAUTH_VERSION]; |
| 307 | if ( !in_array( $oauthVersion, [ Consumer::OAUTH_VERSION_1, Consumer::OAUTH_VERSION_2 ], true ) ) { |
| 308 | $this->raiseInvalidConfigError( $consumerData, 'oauthVersion must be 1 or 2' ); |
| 309 | } |
| 310 | $isOwnerOnly = (bool)( $consumerData[Consumer::FIELD_OWNER_ONLY] ?? false ); |
| 311 | $oAuth2GrantTypes = (array)( $consumerData[Consumer::FIELD_OAUTH2_GRANT_TYPES] ?? [] ); |
| 312 | $hasAuthorizationCodeGrant = in_array( ClientEntity::GRANT_TYPE_AUTHORIZATION_CODE, $oAuth2GrantTypes, true ); |
| 313 | |
| 314 | // check required and unknown / unexpected keys |
| 315 | [ 'required' => $requiredKeys, 'optional' => $optionalKeys, 'unused' => $unusedKeys ] |
| 316 | = $this->getConsumerFields( $oauthVersion, $isOwnerOnly, $hasAuthorizationCodeGrant ); |
| 317 | |
| 318 | foreach ( $requiredKeys as $key => $_ ) { |
| 319 | $consumerData[$key] ?? $this->raiseInvalidConfigError( $consumerData, "$key is required" ); |
| 320 | } |
| 321 | $unknownKeys = array_keys( array_diff_key( $consumerData, $requiredKeys, $optionalKeys, $unusedKeys ) ); |
| 322 | if ( $unknownKeys ) { |
| 323 | $this->raiseInvalidConfigError( $consumerData, 'unknown fields: ' . implode( ', ', $unknownKeys ) ); |
| 324 | } |
| 325 | $unexpectedKeys = array_keys( array_diff_key( $consumerData, $requiredKeys, $optionalKeys ) ); |
| 326 | if ( $unexpectedKeys ) { |
| 327 | $appType = "OAuth $oauthVersion " . ( $isOwnerOnly ? 'owner-only' : 'non-owner-only' ); |
| 328 | $this->raiseInvalidConfigError( $consumerData, "these fields cannot be used with $appType apps: " |
| 329 | . implode( ', ', $unexpectedKeys ) ); |
| 330 | } |
| 331 | |
| 332 | foreach ( self::FIELD_TYPES as $field => $type ) { |
| 333 | if ( array_key_exists( $field, $consumerData ) ) { |
| 334 | try { |
| 335 | Assert::parameterType( $type, $consumerData[$field], 'not used' ); |
| 336 | } catch ( ParameterTypeException ) { |
| 337 | $this->raiseInvalidConfigError( $consumerData, "$field must be $type" ); |
| 338 | } |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | $needsSecret = $oauthVersion === Consumer::OAUTH_VERSION_1 |
| 343 | || $consumerData[Consumer::FIELD_OAUTH2_IS_CONFIDENTIAL]; |
| 344 | if ( $needsSecret |
| 345 | && !( $consumerData[Consumer::FIELD_SECRET_KEY] ?? null ) |
| 346 | && !( $consumerData[Consumer::FIELD_RSA_KEY] ?? null ) |
| 347 | ) { |
| 348 | $this->raiseInvalidConfigError( $consumerData, |
| 349 | 'Either secretKey or rsaKey is required for confidential clients' ); |
| 350 | } |
| 351 | |
| 352 | $unknownOauth2GrantTypes = array_diff( $consumerData[Consumer::FIELD_OAUTH2_GRANT_TYPES] ?? [], |
| 353 | ClientEntity::GRANT_TYPES ); |
| 354 | if ( $unknownOauth2GrantTypes ) { |
| 355 | $this->raiseInvalidConfigError( $consumerData, 'Invalid OAuth 2 grant types: ' |
| 356 | . implode( ', ', $unknownOauth2GrantTypes ) ); |
| 357 | } |
| 358 | |
| 359 | $consumerData += $optionalKeys; |
| 360 | $consumerData += $unusedKeys; |
| 361 | return $consumerData; |
| 362 | } |
| 363 | |
| 364 | /** |
| 365 | * Checks the callback URL / redirect URI. |
| 366 | * |
| 367 | * @param string $url |
| 368 | * @param array $fields Full consumer data |
| 369 | * @return StatusValue |
| 370 | */ |
| 371 | private function validateCallbackUrl( string $url, array $fields ): StatusValue { |
| 372 | $isOAuth1 = (int)$fields[Consumer::FIELD_OAUTH_VERSION] === Consumer::OAUTH_VERSION_1; |
| 373 | $isOAuth2 = !$isOAuth1; |
| 374 | $clientIsConfidential = $isOAuth1 || $fields[Consumer::FIELD_OAUTH2_IS_CONFIDENTIAL]; |
| 375 | $oauth2GrantTypes = $fields[Consumer::FIELD_OAUTH2_GRANT_TYPES] ?? []; |
| 376 | $isClientCredentialsOnly = $isOAuth2 |
| 377 | && count( $oauth2GrantTypes ) === 1 |
| 378 | && in_array( ClientEntity::GRANT_TYPE_CLIENT_CREDENTIALS, $oauth2GrantTypes, true ); |
| 379 | |
| 380 | if ( strlen( $url ) > 2000 ) { |
| 381 | return $this->getTooLongErrorStatus( Consumer::FIELD_CALLBACK_URL, 2000 ); |
| 382 | } elseif ( $fields[Consumer::FIELD_OWNER_ONLY] || $isClientCredentialsOnly ) { |
| 383 | return StatusValue::newGood(); |
| 384 | } |
| 385 | |
| 386 | $urlUtils = Utils::getOAuthUrlUtils(); |
| 387 | $urlParts = $urlUtils->parse( $url ); |
| 388 | if ( !$urlParts ) { |
| 389 | return $this->getGenericErrorStatus( Consumer::FIELD_CALLBACK_URL ); |
| 390 | } |
| 391 | $isCustomProtocol = !in_array( $urlParts['scheme'], [ '', 'http', 'https' ], true ); |
| 392 | |
| 393 | if ( $isCustomProtocol ) { |
| 394 | if ( $clientIsConfidential ) { |
| 395 | // Custom protocols are handled by an application installed on the device; |
| 396 | // so it cannot possibly be confidential. |
| 397 | return StatusValue::newFatal( |
| 398 | new ApiMessage( 'mwoauth-error-callback-url-custom-protocol-nonconfidential', |
| 399 | 'invalid_callback_url' ) |
| 400 | ); |
| 401 | } |
| 402 | // T412542: Follow RFC 8252 recommendation to use reverse domain name |
| 403 | // format for custom URI schemes. Require at least one period to avoid generic |
| 404 | // scheme names that could be confused with standard schemes. |
| 405 | if ( !str_contains( $urlParts['scheme'], '.' ) ) { |
| 406 | return StatusValue::newGood()->warning( |
| 407 | new ApiMessage( 'mwoauth-error-callback-url-custom-scheme-no-period', |
| 408 | 'invalid_callback_url' ) |
| 409 | ); |
| 410 | } |
| 411 | } elseif ( $isOAuth2 && !self::isSecureContext( $urlParts ) ) { |
| 412 | // The OAuth 2 spec requires an encrypted transport. |
| 413 | return StatusValue::newFatal( |
| 414 | new ApiMessage( 'mwoauth-error-callback-url-must-be-https', 'invalid_callback_url' ) |
| 415 | ); |
| 416 | } elseif ( $clientIsConfidential && WikiMap::getWikiFromUrl( $url ) ) { |
| 417 | // Reduce noise from clueless people using Wikipedia's URL as callback |
| 418 | // (except for public clients; it can be valid e.g. for gadgets). |
| 419 | return StatusValue::newGood()->warning( |
| 420 | new ApiMessage( 'mwoauth-error-callback-server-url', 'invalid_callback_url' ) |
| 421 | ); |
| 422 | } elseif ( ( $isOAuth2 || !$fields[Consumer::FIELD_CALLBACK_IS_PREFIX] ) |
| 423 | && in_array( $urlParts['path'] ?? '', [ '', '/' ], true ) |
| 424 | && !( $urlParts['query'] ?? false ) |
| 425 | && !( $urlParts['fragment'] ?? false ) |
| 426 | ) { |
| 427 | // Warn people using a bare domain name with no path or query part as |
| 428 | // the exact callback URL. It is valid, but it's rare that they actually mean it. |
| 429 | $message = $isOAuth1 |
| 430 | ? 'mwoauth-error-callback-bare-domain-oauth1' |
| 431 | : 'mwoauth-error-callback-bare-domain-oauth2'; |
| 432 | return StatusValue::newGood()->warning( |
| 433 | new ApiMessage( $message, 'invalid_callback_url' ) |
| 434 | ); |
| 435 | } |
| 436 | return StatusValue::newGood(); |
| 437 | } |
| 438 | |
| 439 | /** |
| 440 | * Decide whether the given (parsed) URL corresponds to a secure context. |
| 441 | * (This is only an approximation of the algorithm browsers use, |
| 442 | * since some considerations such as frames don't apply here.) |
| 443 | * |
| 444 | * @see https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts |
| 445 | * |
| 446 | * @param array $urlParts As returned by {@link UrlUtils::parse()}. |
| 447 | * @return bool |
| 448 | */ |
| 449 | private function isSecureContext( array $urlParts ): bool { |
| 450 | if ( $urlParts['scheme'] === 'https' ) { |
| 451 | return true; |
| 452 | } |
| 453 | |
| 454 | $host = $urlParts['host']; |
| 455 | if ( $host === 'localhost' |
| 456 | || $host === '127.0.0.1' |
| 457 | || $host === '[::1]' |
| 458 | || str_ends_with( $host, '.localhost' ) |
| 459 | // The wmftest.{com,net,org} domains hosted by the Wikimedia |
| 460 | // Foundation include a '*.local IN A 127.0.0.1' that is used in |
| 461 | // some local development environments. |
| 462 | || str_ends_with( $host, '.local.wmftest.com' ) |
| 463 | || str_ends_with( $host, '.local.wmftest.net' ) |
| 464 | || str_ends_with( $host, '.local.wmftest.org' ) |
| 465 | ) { |
| 466 | return true; |
| 467 | } |
| 468 | |
| 469 | return false; |
| 470 | } |
| 471 | |
| 472 | private function getErrorStatus( string $fieldName, string|array $msg, array $data = [] ): StatusValue { |
| 473 | return StatusValue::newFatal( new ApiMessage( $msg, 'invalid_field', $data + [ 'field' => $fieldName ] ) ); |
| 474 | } |
| 475 | |
| 476 | private function getGenericErrorStatus( string $fieldName, ?string $details = null ): StatusValue { |
| 477 | if ( $details === null ) { |
| 478 | return $this->getErrorStatus( $fieldName, [ 'mwoauth-invalid-field', $fieldName ] ); |
| 479 | } else { |
| 480 | return $this->getErrorStatus( $fieldName, [ 'mwoauth-invalid-field-with-details', $fieldName, $details ] ); |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | private function getTooLongErrorStatus( string $fieldName, int $maxLength ): StatusValue { |
| 485 | return $this->getErrorStatus( $fieldName, [ 'mwoauth-invalid-field-too-long', $fieldName, $maxLength ] ); |
| 486 | } |
| 487 | |
| 488 | private function getStatusFormatter(): StatusFormatter { |
| 489 | return $this->formatterFactory->getStatusFormatter( RequestContext::getMain() ); |
| 490 | } |
| 491 | |
| 492 | /** |
| 493 | * Returns what keys are required and optionally allowed for a given app type. |
| 494 | * |
| 495 | * Keys match Consumer properties. |
| 496 | * @return array Three arrays: |
| 497 | * - 'required': required keys, in `<key> => true` format |
| 498 | * - 'optional': optional keys, in `<key> => <default>` format |
| 499 | * - 'unused': keys not used for this consumer type, in `<key> => <db default>` format |
| 500 | * @phan-return array{required:array,optional:array,unused:array} |
| 501 | * @see Consumer::getSchema() |
| 502 | * @see examples/configurationBasedClient.php |
| 503 | */ |
| 504 | private function getConsumerFields( |
| 505 | int $oauthVersion, |
| 506 | bool $isOwnerOnly, |
| 507 | bool $hasAuthorizationCodeGrant, |
| 508 | ): array { |
| 509 | // default values for non-required keys |
| 510 | $dbDefaults = [ |
| 511 | Consumer::FIELD_OWNER_ONLY => false, |
| 512 | // need an URL for validation purposes even if it won't be used |
| 513 | // just in case, don't use anything that's not under our own control |
| 514 | Consumer::FIELD_CALLBACK_URL => SpecialPage::getTitleFor( 'OAuth' ) |
| 515 | ->getSubpage( 'verified' )->getCanonicalURL(), |
| 516 | Consumer::FIELD_CALLBACK_IS_PREFIX => false, |
| 517 | Consumer::FIELD_EMAIL => $this->options->get( MainConfigNames::NoReplyAddress ), |
| 518 | Consumer::FIELD_EMAIL_AUTHENTICATED => true, |
| 519 | Consumer::FIELD_DEVELOPER_AGREEMENT => true, |
| 520 | Consumer::FIELD_WIKI => '*', |
| 521 | Consumer::FIELD_REGISTRATION => ConvertibleTimestamp::now(), |
| 522 | // to be in the safe side, set this to something unguessable even for |
| 523 | // consumers that aren't supposed to use it |
| 524 | Consumer::FIELD_SECRET_KEY => MWCryptRand::generateHex( 32 ), |
| 525 | Consumer::FIELD_RSA_KEY => '', |
| 526 | Consumer::FIELD_RESTRICTIONS => MWRestrictions::newDefault(), |
| 527 | Consumer::FIELD_STAGE => Consumer::STAGE_APPROVED, |
| 528 | Consumer::FIELD_STAGE_TIMESTAMP => ConvertibleTimestamp::now(), |
| 529 | Consumer::FIELD_DELETED => false, |
| 530 | Consumer::FIELD_OAUTH2_IS_CONFIDENTIAL => true, |
| 531 | Consumer::FIELD_SKIP_AUTHORIZATION => false, |
| 532 | ]; |
| 533 | $requiredKeys = [ |
| 534 | Consumer::FIELD_ID, |
| 535 | Consumer::FIELD_CONSUMER_KEY, |
| 536 | Consumer::FIELD_NAME, |
| 537 | Consumer::FIELD_VERSION, |
| 538 | Consumer::FIELD_DESCRIPTION, |
| 539 | Consumer::FIELD_OAUTH_VERSION, |
| 540 | Consumer::FIELD_GRANTS, |
| 541 | // TODO make this not required |
| 542 | Consumer::FIELD_USER_ID, |
| 543 | ]; |
| 544 | $optionalKeys = [ |
| 545 | Consumer::FIELD_OWNER_ONLY, |
| 546 | Consumer::FIELD_SECRET_KEY, |
| 547 | Consumer::FIELD_WIKI, |
| 548 | Consumer::FIELD_RESTRICTIONS, |
| 549 | Consumer::FIELD_SKIP_AUTHORIZATION, |
| 550 | ]; |
| 551 | |
| 552 | if ( $oauthVersion === Consumer::OAUTH_VERSION_1 ) { |
| 553 | $optionalKeys[] = Consumer::FIELD_RSA_KEY; |
| 554 | if ( !$isOwnerOnly ) { |
| 555 | $requiredKeys[] = Consumer::FIELD_CALLBACK_URL; |
| 556 | $optionalKeys[] = Consumer::FIELD_CALLBACK_IS_PREFIX; |
| 557 | } |
| 558 | } else { |
| 559 | $requiredKeys[] = Consumer::FIELD_OAUTH2_IS_CONFIDENTIAL; |
| 560 | if ( !$isOwnerOnly ) { |
| 561 | $requiredKeys[] = Consumer::FIELD_OAUTH2_GRANT_TYPES; |
| 562 | if ( $hasAuthorizationCodeGrant ) { |
| 563 | $requiredKeys[] = Consumer::FIELD_CALLBACK_URL; |
| 564 | } |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | if ( $isOwnerOnly ) { |
| 569 | $dbDefaults += [ |
| 570 | Consumer::FIELD_OAUTH2_GRANT_TYPES => [ |
| 571 | ClientEntity::GRANT_TYPE_CLIENT_CREDENTIALS, |
| 572 | ], |
| 573 | ]; |
| 574 | } else { |
| 575 | $dbDefaults += [ |
| 576 | Consumer::FIELD_OAUTH2_GRANT_TYPES => [ |
| 577 | ClientEntity::GRANT_TYPE_AUTHORIZATION_CODE, |
| 578 | ClientEntity::GRANT_TYPE_REFRESH_TOKEN, |
| 579 | ], |
| 580 | ]; |
| 581 | } |
| 582 | |
| 583 | // More complex conditions checked elsewhere: |
| 584 | // - either SECRET_KEY or RSA_KEY is required for OAuth 1 apps and confidential OAuth 2 apps |
| 585 | // - TODO cannot set confidential=false for client credentials |
| 586 | |
| 587 | $toAssoc = static fn ( array $a ) => array_fill_keys( $a, true ); |
| 588 | return [ |
| 589 | 'required' => $toAssoc( $requiredKeys ), |
| 590 | 'optional' => array_intersect_key( $dbDefaults, $toAssoc( $optionalKeys ) ), |
| 591 | 'unused' => array_diff_key( $dbDefaults, $toAssoc( $requiredKeys ), $toAssoc( $optionalKeys ) ), |
| 592 | ]; |
| 593 | } |
| 594 | |
| 595 | /** |
| 596 | * @throws NormalizedOAuthException |
| 597 | */ |
| 598 | private function raiseInvalidConfigError( array $consumerData, string $reason ): never { |
| 599 | $consumerKey = $consumerData[Consumer::FIELD_CONSUMER_KEY] ?? 'missing key'; |
| 600 | throw new NormalizedOAuthException( 'Invalid configuration-based OAuth app ({consumerKey}): {reason}', [ |
| 601 | 'consumerKey' => $consumerKey, |
| 602 | 'reason' => $reason, |
| 603 | ] ); |
| 604 | } |
| 605 | |
| 606 | } |