summaryrefslogtreecommitdiff
blob: 8d7e5085545cc2675fe64eb35f0de0bbab89f25b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
<?php

namespace MediaWiki\Extensions\OAuth;

use ApiMessage;
use GuzzleHttp\Psr7\ServerRequest;
use MediaWiki\Extensions\OAuth\Backend\Consumer;
use MediaWiki\Extensions\OAuth\Backend\ConsumerAcceptance;
use MediaWiki\Extensions\OAuth\Backend\MWOAuthException;
use MediaWiki\Extensions\OAuth\Backend\MWOAuthRequest;
use MediaWiki\Extensions\OAuth\Backend\Utils;
use MediaWiki\Extensions\OAuth\Repository\AccessTokenRepository;
use MediaWiki\Session\SessionBackend;
use MediaWiki\Session\SessionInfo;
use MediaWiki\Session\SessionManager;
use MediaWiki\Session\UserInfo;
use User;
use WebRequest;
use Wikimedia\Rdbms\DBError;

/**
 * Session provider for OAuth
 *
 * This is a fairly standard ImmutableSessionProviderWithCookie implementation:
 * the user identity is determined by the OAuth headers included in the
 * request. But since we want to make sure to fail the request when OAuth
 * headers are present but invalid, this takes the somewhat unusual step of
 * returning a bogus SessionInfo and then hooking ApiBeforeMain to throw a
 * fatal exception after MediaWiki is ready to handle it.
 *
 * It also takes advantage of the getAllowedUserRights() method for authz
 * purposes (limiting the rights to those included in the grant), and
 * registers some hooks to tag actions made via the provider.
 */
class SessionProvider extends \MediaWiki\Session\ImmutableSessionProviderWithCookie {

	public function __construct( array $params = [] ) {
		global $wgHooks;

		parent::__construct( $params );

		$wgHooks['ApiCheckCanExecute'][] = $this;
		$wgHooks['RecentChange_save'][] = $this;
		$wgHooks['MarkPatrolled'][] = $this;
	}

	/**
	 * Throw an exception, later
	 *
	 * @param string $key Key for the error message
	 * @param mixed ...$params Parameters as strings.
	 * @return SessionInfo
	 */
	private function makeException( $key, ...$params ) {
		global $wgHooks;

		// First, schedule the throwing of the exception for later when the API
		// is ready to catch it
		$msg = wfMessage( $key, $params );
		$exception = \ApiUsageException::newWithMessage( null, $msg );
		$wgHooks['ApiBeforeMain'][] = function () use ( $exception ) {
			throw $exception;
		};

		// Then return an appropriate SessionInfo
		$id = $this->hashToSessionId( 'bogus' );
		return new SessionInfo( SessionInfo::MAX_PRIORITY, [
			'provider' => $this,
			'id' => $id,
			'userInfo' => UserInfo::newAnonymous(),
			'persisted' => false,
		] );
	}

	public function provideSessionInfo( WebRequest $request ) {
		// For some reason MWOAuth is restricted to be API-only.
		if ( !defined( 'MW_API' ) && !defined( 'MW_REST_API' ) ) {
			return null;
		}

		$oauthVersion = $this->getOAuthVersionFromRequest( $request );
		if ( $oauthVersion === null ) {
			// Not an OAuth request
			return null;
		}

		$logData = [
			'clientip' => $request->getIP(),
			'user' => false,
			'consumer' => '',
			'result' => 'fail',
		];

		$dbr = Utils::getCentralDB( DB_REPLICA );
		$access = null;
		try {
			if ( $oauthVersion === Consumer::OAUTH_VERSION_2 ) {
				$resourceServer = ResourceServer::factory();
				$accessTokenKey = $this->verifyOAuth2Request( $resourceServer, $request );
				$accessTokenRepo = new AccessTokenRepository();
				$accessId = $accessTokenRepo->getApprovalId( $accessTokenKey );
				if ( $accessId === 0 ) {
					if (
						$resourceServer->getUser()->getId() === 0 &&
						$resourceServer->getClient()->getOwnerOnly() === false
					) {
						// This tell us, with good degree of certainty, that the AT
						// was issued to a machine and represents no particular user
						$access = ConsumerAcceptance::newFromArray( [
							'id'           => null,
							'wiki'         => $resourceServer->getClient()->getWiki(),
							'userId'       => 0,
							'consumerId'   => $resourceServer->getClient()->getId(),
							'accessToken'  => '',
							'accessSecret' => '',
							'grants'       => $resourceServer->getClient()->getGrants(),
							'accepted'     => wfTimestampNow(),
							'oauth_version' => Consumer::OAUTH_VERSION_2
						] );
					}
				} else {
					$access = ConsumerAcceptance::newFromId(
						Utils::getCentralDB( DB_REPLICA ), $accessId
					);
				}
				if ( !$access ) {
					throw new MWOAuthException( 'mwoauth-oauth2-error-create-at-no-user-approval' );
				}

				// Set the scopes that are verified for this request
				$access->setField( 'grants', array_keys( $resourceServer->getScopes() ) );
			} else {
				$server = Utils::newMWOAuthServer();
				$oauthRequest = MWOAuthRequest::fromRequest( $request );
				$logData['consumer'] = $oauthRequest->getConsumerKey();
				list( , $accessToken ) = $server->verify_request( $oauthRequest );
				$accessTokenKey = $accessToken->key;
				$access = ConsumerAcceptance::newFromToken( $dbr, $accessTokenKey );
			}
		} catch ( \Exception $ex ) {
			$this->logger->info( 'Bad OAuth request from {ip}', $logData + [ 'exception' => $ex ] );
			return $this->makeException( 'mwoauth-invalid-authorization', $ex->getMessage() );
		}

		$logData['user'] = Utils::getCentralUserNameFromId( $access->getUserId(), 'raw' );

		$wiki = wfWikiID();
		// Access token is for this wiki
		if ( $access->getWiki() !== '*' && $access->getWiki() !== $wiki ) {
			$this->logger->debug( 'OAuth request for wrong wiki from user {user}', $logData );
			return $this->makeException( 'mwoauth-invalid-authorization-wrong-wiki', $wiki );
		}

		// There exists a local user
		$localUser = Utils::getLocalUserFromCentralId( $access->getUserId() );
		if ( !$localUser ) {
			$localUser = User::newFromId( 0 );
		}
		// If there is an actual approval, but user bound to it does not exist
		if ( $access->getId() > 0 && $localUser->getId() === 0 ) {
			$this->logger->debug( 'OAuth request for invalid or non-local user {user}', $logData );
			return $this->makeException( 'mwoauth-invalid-authorization-invalid-user',
				\Message::rawParam( \Linker::makeExternalLink(
					'https://www.mediawiki.org/wiki/Help:OAuth/Errors#E008',
					'E008',
					true
				) )
			);
		}
		if ( $localUser->isLocked() ||
			( $this->config->get( 'BlockDisablesLogin' ) && $localUser->isBlocked() )
		) {
			$this->logger->debug( 'OAuth request for blocked user {user}', $logData );
			return $this->makeException( 'mwoauth-invalid-authorization-blocked-user' );
		}

		// The consumer is approved or owned by $localUser, and is for this wiki.
		$consumer = Consumer::newFromId( $dbr, $access->getConsumerId() );
		if ( !$consumer->isUsableBy( $localUser ) ) {
			$this->logger->debug(
				'OAuth request for consumer {consumer} not approved by user {user}', $logData
			);
			return $this->makeException( 'mwoauth-invalid-authorization-not-approved',
				$consumer->getName() );
		} elseif ( $consumer->getWiki() !== '*' && $consumer->getWiki() !== $wiki ) {
			$this->logger->debug( 'OAuth request for consumer {consumer} to incorrect wiki', $logData );
			return $this->makeException( 'mwoauth-invalid-authorization-wrong-wiki', $wiki );
		}

		// Ok, use this user!
		if ( $this->sessionCookieName === null ) {
			// We're not configured to use cookies, so concatenate some of the
			// internal consumer-acceptance state to generate an ID.
			$id = $this->hashToSessionId( implode( "\n", [
				$access->getId(),
				$access->getWiki(),
				$access->getUserId(),
				$access->getConsumerId(),
				$access->getAccepted(),
				$wiki,
			] ) );
			$persisted = false;
			$forceUse = true;
		} else {
			$id = $this->getSessionIdFromCookie( $request );
			$persisted = $id !== null;
			$forceUse = false;
		}

		$logData['result'] = 'success';
		$this->logger->debug( 'OAuth request for consumer {consumer} by user {user}', $logData );

		return new SessionInfo( SessionInfo::MAX_PRIORITY, [
			'provider' => $this,
			'id' => $id,
			'userInfo' => UserInfo::newFromUser( $localUser, true ),
			'persisted' => $persisted,
			'forceUse' => $forceUse,
			'metadata' => [
				'oauthVersion' => $oauthVersion,
				'consumerId' => $consumer->getOwnerOnly() ? null : $consumer->getId(),
				'key' => $accessTokenKey,
				'rights' => \MWGrants::getGrantRights( $access->getGrants() ),
			],
		] );
	}

	/**
	 * Determine OAuth version of the request
	 *
	 * @param WebRequest $request
	 * @return int|null if request is not using OAuth header
	 */
	private function getOAuthVersionFromRequest( WebRequest $request ) {
		if ( Utils::hasOAuthHeaders( $request ) ) {
			return Consumer::OAUTH_VERSION_1;
		}
		if ( ResourceServer::isOAuth2Request( $request ) ) {
			return Consumer::OAUTH_VERSION_2;
		}

		return null;
	}

	/**
	 * @param ResourceServer &$resourceServer
	 * @param WebRequest $request
	 * @return string
	 * @throws MWOAuthException
	 */
	private function verifyOAuth2Request( ResourceServer &$resourceServer, WebRequest $request ) {
		$request = ServerRequest::fromGlobals()->withHeader(
			'authorization',
			$request->getHeader( 'authorization' )
		);

		$response = new Response();
		$valid = false;
		$resourceServer->verify(
			$request,
			$response,
			function ( $request, $response ) use ( &$valid ) {
				$valid = true;
			}
		);

		if ( $valid ) {
			return $resourceServer->getAccessTokenId();
		}

		throw new MWOAuthException( 'mwoauth-oauth2-invalid-access-token' );
	}

	public function preventSessionsForUser( $username ) {
		$id = Utils::getCentralIdFromUserName( $username );
		$dbw = Utils::getCentralDB( DB_MASTER );

		$dbw->startAtomic( __METHOD__ );
		try {
			// Remove any approvals for the user's consumers before deleting them
			$dbw->deleteJoin(
				'oauth_accepted_consumer',
				'oauth_registered_consumer',
				'oaac_consumer_id',
				'oarc_id',
				[ 'oarc_user_id' => $id ],
				__METHOD__
			);
			$dbw->delete(
				'oauth_registered_consumer',
				[ 'oarc_user_id' => $id ],
				__METHOD__
			);

			// Remove any approvals by this user, too
			$dbw->delete(
				'oauth_accepted_consumer',
				[ 'oaac_user_id' => $id ],
				__METHOD__
			);
		} catch ( DBError $e ) {
			$dbw->rollback( __METHOD__ );
			throw $e;
		}
		$dbw->endAtomic( __METHOD__ );
	}

	public function getVaryHeaders() {
		return [
			'Authorization' => null,
		];
	}

	/**
	 * Fetch the access data, if any, for this user-session
	 * @param \User|null $user
	 * @return array|null
	 */
	private function getSessionData( \User $user = null ) {
		if ( $user ) {
			$session = $user->getRequest()->getSession();
			if ( $session->getProvider() === $this &&
				$user->equals( $session->getUser() )
			) {
				return $session->getProviderMetadata();
			}
		} else {
			$session = SessionManager::getGlobalSession();
			if ( $session->getProvider() === $this ) {
				return $session->getProviderMetadata();
			}
		}

		return null;
	}

	public function getAllowedUserRights( SessionBackend $backend ) {
		if ( $backend->getProvider() !== $this ) {
			throw new \InvalidArgumentException( 'Backend\'s provider isn\'t $this' );
		}
		$data = $backend->getProviderMetadata();
		if ( $data ) {
			return $data['rights'];
		}

		// Should never happen
		$this->logger->debug( __METHOD__ . ': No provider metadata, returning no rights allowed' );
		return [];
	}

	/**
	 * Disable certain API modules when used with OAuth
	 *
	 * @param \ApiBase $module
	 * @param \User $user
	 * @param string|array &$message
	 * @return bool
	 */
	public function onApiCheckCanExecute( \ApiBase $module, \User $user, &$message ) {
		global $wgMWOauthDisabledApiModules;
		if ( !$this->getSessionData( $user ) ) {
			return true;
		}

		foreach ( $wgMWOauthDisabledApiModules as $badModule ) {
			if ( $module instanceof $badModule ) {
				$message = ApiMessage::create(
					[ 'mwoauth-api-module-disabled', $module->getModuleName() ],
					'mwoauth-api-module-disabled'
				);
				return false;
			}
		}

		return true;
	}

	/**
	 * Record the fact that OAuth was used for anything added to RecentChanges.
	 *
	 * @param \RecentChange $rc
	 * @return bool true
	 */
	public function onRecentChange_save( $rc ) {
		$consumerId = $this->getPublicConsumerId( $rc->getPerformer() ?: null );
		if ( $consumerId !== null ) {
			$rc->addTags( Utils::getTagName( $consumerId ) );
		}
		return true;
	}

	/**
	 * Get the consumer ID of the non-owner-only OAuth consumer associated with this user, or null.
	 * @param User|null $user
	 * @return int|null
	 */
	protected function getPublicConsumerId( User $user = null ) {
		$data = $this->getSessionData( $user );
		if ( $data && isset( $data['consumerId'] ) ) {
			return $data['consumerId'];
		}
		return null;
	}

	/**
	 * Record the fact that OAuth was used for marking an existing RecentChange as patrolled.
	 * (RecentChange::doMarkPatrolled() does not use RecentChange::save()
	 * and therefore bypasses the above hook handler.)
	 *
	 * @param int $rcid
	 * @param User $user
	 * @param bool $wcOnlySysopsCanPatrol
	 * @param bool $auto
	 * @param string[] &$tags
	 *
	 * @return bool true
	 */
	public function onMarkPatrolled(
		$rcid,
		User $user,
		$wcOnlySysopsCanPatrol,
		$auto,
		array &$tags
	) {
		$consumerId = $this->getPublicConsumerId( $user );
		if ( $consumerId !== null ) {
			$tags[] = Utils::getTagName( $consumerId );
		}
		return true;
	}

	/**
	 * OAuth tokens already protect against CSRF. CSRF tokens are not required.
	 *
	 * @return bool true
	 */
	public function safeAgainstCsrf() {
		return true;
	}
}