-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathAbstractOauth2AuthAction.class.php
More file actions
403 lines (344 loc) · 13 KB
/
AbstractOauth2AuthAction.class.php
File metadata and controls
403 lines (344 loc) · 13 KB
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
<?php
namespace wcf\action;
use CuyZ\Valinor\MapperBuilder;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Psr7\Request;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Diactoros\Uri;
use ParagonIE\ConstantTime\Base64UrlSafe;
use ParagonIE\ConstantTime\Hex;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use wcf\data\user\User;
use wcf\event\user\authentication\UserLoggedIn;
use wcf\form\AccountManagementForm;
use wcf\form\RegisterForm;
use wcf\system\event\EventHandler;
use wcf\system\exception\IllegalLinkException;
use wcf\system\exception\NamedUserException;
use wcf\system\exception\PermissionDeniedException;
use wcf\system\io\HttpFactory;
use wcf\system\request\LinkHandler;
use wcf\system\user\authentication\LoginRedirect;
use wcf\system\user\authentication\oauth\exception\StateValidationException;
use wcf\system\user\authentication\oauth\Failure as OAuth2Failure;
use wcf\system\user\authentication\oauth\Success as OAuth2Success;
use wcf\system\user\authentication\oauth\User as OauthUser;
use wcf\system\WCF;
use wcf\util\HtmlString;
/**
* Generic implementation to handle the OAuth 2 flow.
*
* @author Olaf Braun
* @copyright 2001-2024 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @since 6.1
*/
abstract class AbstractOauth2AuthAction implements RequestHandlerInterface
{
private const STATE = self::class . "\0state_parameter";
private const PKCE = self::class . "\0pkce";
private ClientInterface $httpClient;
#[\Override]
public function handle(ServerRequestInterface $request): ResponseInterface
{
if (!$this->isEnabled()) {
throw new IllegalLinkException();
}
if (WCF::getSession()->spiderIdentifier) {
throw new PermissionDeniedException();
}
$parameters = $this->mapParameters($request);
try {
if ($parameters instanceof OAuth2Success) {
$accessToken = $this->getAccessToken($parameters);
$user = $this->getUser($accessToken);
return $this->processUser($user);
} elseif ($parameters instanceof OAuth2Failure) {
return $this->handleError($parameters);
} else {
return $this->initiate();
}
} catch (NamedUserException $e) {
throw $e;
} catch (StateValidationException $e) {
throw new NamedUserException(HtmlString::fromSafeHtml(
WCF::getLanguage()->getDynamicVariable(
'wcf.user.3rdparty.login.error.stateValidation'
)
));
} catch (\Exception $e) {
$exceptionID = \wcf\functions\exception\logThrowable($e);
$type = 'genericException';
if ($e instanceof ClientExceptionInterface) {
$type = 'httpError';
}
throw new NamedUserException(HtmlString::fromSafeHtml(
WCF::getLanguage()->getDynamicVariable(
'wcf.user.3rdparty.login.error.' . $type,
[
'exceptionID' => $exceptionID,
]
)
));
}
}
/**
* Returns whether this OAuth provider is enabled.
*/
protected function isEnabled(): bool
{
return !empty($this->getClientId()) && !empty($this->getClientSecret());
}
protected function mapParameters(ServerRequestInterface $request): OAuth2Success | OAuth2Failure | null
{
try {
$mapper = (new MapperBuilder())
->allowSuperfluousKeys()
->mapper();
return $mapper->map(
\sprintf("%s|%s", OAuth2Success::class, OAuth2Failure::class),
$request->getQueryParams()
);
} catch (\Throwable) {
return null;
}
}
/**
* Turns the 'code' into an access token.
*
* @return mixed[]
*/
protected function getAccessToken(OAuth2Success $auth2Success): array
{
$payload = [
'grant_type' => 'authorization_code',
'client_id' => $this->getClientId(),
'client_secret' => $this->getClientSecret(),
'redirect_uri' => $this->getCallbackUrl(),
'code' => $auth2Success->code,
];
if ($this->usePkce()) {
if (!($verifier = WCF::getSession()->getVar(self::PKCE))) {
throw new StateValidationException('Missing PKCE verifier in session');
}
$payload['code_verifier'] = $verifier;
}
$request = new Request('POST', $this->getTokenEndpoint(), [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded',
], \http_build_query($payload, '', '&', \PHP_QUERY_RFC1738));
try {
$response = $this->getHttpClient()->send($request);
} finally {
// Validate state. Validation of state is executed after fetching the
// access_token to invalidate 'code'.
//
// Validation is happening within the `finally` so that the StateValidationException
// overwrites any HTTP exception (improving the error message).
if ($this->supportsState()) {
$this->validateState($auth2Success);
}
}
$parsed = \json_decode((string)$response->getBody(), true, flags: \JSON_THROW_ON_ERROR);
if (!empty($parsed['error'])) {
throw new \Exception(
\sprintf(
"Access token response indicates an error: '%s'",
$parsed['error']
)
);
}
if (empty($parsed['access_token'])) {
throw new \Exception("Access token response does not have the 'access_token' key.");
}
return $parsed;
}
/**
* Returns the 'client_id'.
*/
abstract protected function getClientId(): string;
/**
* Returns the 'client_secret'.
*/
abstract protected function getClientSecret(): string;
/**
* Returns the callback URL. This should most likely be:
*
* LinkHandler::getInstance()->getControllerLink(self::class)
*/
abstract protected function getCallbackUrl(): string;
/**
* Whether to use PKCE (RFC 7636). Defaults to 'false'.
*/
protected function usePkce(): bool
{
return false;
}
/**
* Returns the URL of the '/token' endpoint that turns the code into an access token.
*/
abstract protected function getTokenEndpoint(): string;
/**
* Returns a "static" instance of the HTTP client to use to allow
* for TCP connection reuse.
*/
protected function getHttpClient(): ClientInterface
{
if (!isset($this->httpClient)) {
$this->httpClient = HttpFactory::makeClientWithTimeout(5);
}
return $this->httpClient;
}
/**
* Whether to validate the state or not. Should be 'true' to protect
* against CSRF attacks.
*/
abstract protected function supportsState(): bool;
/**
* Validates the state parameter.
*/
protected function validateState(OAuth2Success $auth2Success): void
{
try {
if (!($sessionState = WCF::getSession()->getVar(self::STATE))) {
throw new StateValidationException('Missing state in session');
}
if (!\hash_equals($sessionState, $auth2Success->state)) {
throw new StateValidationException('Mismatching state');
}
} finally {
WCF::getSession()->unregister(self::STATE);
}
}
/**
* Turns the access token response into an oauth user.
*
* @param mixed[] $accessToken
*/
abstract protected function getUser(array $accessToken): OauthUser;
/**
* Processes the user (e.g. by registering session variables and redirecting somewhere).
*/
protected function processUser(OauthUser $oauthUser): ResponseInterface
{
$user = $this->getInternalUser($oauthUser);
if ($user->userID) {
if (WCF::getUser()->userID) {
// This account belongs to an existing user, but we are already logged in.
// This can't be handled.
throw new NamedUserException(HtmlString::fromSafeHtml($this->getInUseErrorMessage()));
} else {
// This account belongs to an existing user, we are not logged in.
// Perform the login.
WCF::getSession()->changeUser($user);
WCF::getSession()->update();
EventHandler::getInstance()->fire(
new UserLoggedIn($user)
);
return new RedirectResponse(
LoginRedirect::getUrl()
);
}
} else {
WCF::getSession()->register('__3rdPartyProvider', $this->getProviderName());
if (WCF::getUser()->userID) {
// This account does not belong to anyone and we are already logged in.
// Thus we want to connect this account.
WCF::getSession()->register('__oauthUser', $oauthUser);
return new RedirectResponse(
LinkHandler::getInstance()->getControllerLink(
AccountManagementForm::class,
[],
'#3rdParty'
)
);
} else {
// This account does not belong to anyone and we are not logged in.
// Thus we want to connect this account to a newly registered user.
return $this->redirectToRegistration($oauthUser);
}
}
}
/**
* Returns the user who is assigned to the OAuth user.
*/
protected function getInternalUser(OauthUser $oauthUser): User
{
return User::getUserByAuthData(\sprintf("%s:%s", $this->getProviderName(), $oauthUser->getId()));
}
/**
* Returns the name of the provider.
*/
abstract protected function getProviderName(): string;
/**
* Returns the error message if the user is logged in and the external account is linked to another user.
*/
protected function getInUseErrorMessage(): string
{
return WCF::getLanguage()->getDynamicVariable(
"wcf.user.3rdparty.{$this->getProviderName()}.connect.error.inuse"
);
}
protected function redirectToRegistration(OauthUser $oauthUser): ResponseInterface
{
WCF::getSession()->register('__oauthUser', $oauthUser);
WCF::getSession()->register('__username', $oauthUser->getUsername());
WCF::getSession()->register('__email', $oauthUser->getEmail());
// We assume that bots won't register an external account first, so
// we skip the captcha.
WCF::getSession()->register('noRegistrationCaptcha', true);
WCF::getSession()->update();
return new RedirectResponse(
LinkHandler::getInstance()->getControllerLink(RegisterForm::class)
);
}
protected function handleError(OAuth2Failure $oauth2Failure): ResponseInterface
{
throw new NamedUserException(HtmlString::fromSafeHtml(
WCF::getLanguage()->getDynamicVariable('wcf.user.3rdparty.login.error.' . $oauth2Failure->error)
));
}
/**
* Initiates the OAuth flow by redirecting to the '/authorize' URL.
*/
protected function initiate(): ResponseInterface
{
$parameters = [
'response_type' => 'code',
'client_id' => $this->getClientId(),
'scope' => $this->getScope(),
'redirect_uri' => $this->getCallbackUrl(),
];
if ($this->supportsState()) {
$token = Hex::encode(\random_bytes(16));
WCF::getSession()->register(self::STATE, $token);
$parameters['state'] = $token;
}
if ($this->usePkce()) {
$verifier = Hex::encode(\random_bytes(32));
WCF::getSession()->register(self::PKCE, $verifier);
$parameters['code_challenge'] = Base64UrlSafe::encodeUnpadded(\hash('sha256', $verifier, true));
$parameters['code_challenge_method'] = 'S256';
}
$encodedParameters = \http_build_query($parameters, '', '&');
$url = new Uri($this->getAuthorizeUrl());
$query = $url->getQuery();
if ($query !== '') {
$url = $url->withQuery("{$query}&{$encodedParameters}");
} else {
$url = $url->withQuery($encodedParameters);
}
return new RedirectResponse($url);
}
/**
* Returns the 'scope' to request.
*/
abstract protected function getScope(): string;
/**
* Returns the URL of the '/authorize' endpoint where the user is redirected to.
*/
abstract protected function getAuthorizeUrl(): string;
}