Completed
Pull Request — master (#817)
by
unknown
34:42
created

disableForceEnabledCodeExchangeProof()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 * @author      Alex Bilbie <[email protected]>
4
 * @copyright   Copyright (c) Alex Bilbie
5
 * @license     http://mit-license.org/
6
 *
7
 * @link        https://github.com/thephpleague/oauth2-server
8
 */
9
10
namespace League\OAuth2\Server\Grant;
11
12
use League\OAuth2\Server\Entities\ClientEntityInterface;
13
use League\OAuth2\Server\Entities\ScopeEntityInterface;
14
use League\OAuth2\Server\Entities\UserEntityInterface;
15
use League\OAuth2\Server\Exception\OAuthServerException;
16
use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;
17
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
18
use League\OAuth2\Server\RequestEvent;
19
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
20
use League\OAuth2\Server\ResponseTypes\RedirectResponse;
21
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
22
use Psr\Http\Message\ServerRequestInterface;
23
24
class AuthCodeGrant extends AbstractAuthorizeGrant
25
{
26
    /**
27
     * @var \DateInterval
28
     */
29
    private $authCodeTTL;
30
31
    /**
32
     * @var bool
33
     */
34
    private $enableCodeExchangeProof = false;
35
36
    /**
37
     * @var bool
38
     */
39
    private $forceEnabledCodeExchangeProof = true;
40
41
    /**
42
     * @param AuthCodeRepositoryInterface     $authCodeRepository
43
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
44
     * @param \DateInterval                   $authCodeTTL
45
     */
46
    public function __construct(
47
        AuthCodeRepositoryInterface $authCodeRepository,
48
        RefreshTokenRepositoryInterface $refreshTokenRepository,
49
        \DateInterval $authCodeTTL
50
    ) {
51
        $this->setAuthCodeRepository($authCodeRepository);
52
        $this->setRefreshTokenRepository($refreshTokenRepository);
53
        $this->authCodeTTL = $authCodeTTL;
54
        $this->refreshTokenTTL = new \DateInterval('P1M');
55
    }
56
57
    public function enableCodeExchangeProof()
58
    {
59
        $this->enableCodeExchangeProof = true;
60
    }
61
62
    public function disableForceEnabledCodeExchangeProof()
63
    {
64
        $this->forceEnabledCodeExchangeProof = false;
65
    }
66
67
    /**
68
     * Respond to an access token request.
69
     *
70
     * @param ServerRequestInterface $request
71
     * @param ResponseTypeInterface  $responseType
72
     * @param \DateInterval          $accessTokenTTL
73
     *
74
     * @throws OAuthServerException
75
     *
76
     * @return ResponseTypeInterface
77
     */
78
    public function respondToAccessTokenRequest(
79
        ServerRequestInterface $request,
80
        ResponseTypeInterface $responseType,
81
        \DateInterval $accessTokenTTL
82
    ) {
83
        // Validate request
84
        $client = $this->validateClient($request);
85
        $encryptedAuthCode = $this->getRequestParameter('code', $request, null);
86
87
        if ($encryptedAuthCode === null) {
88
            throw OAuthServerException::invalidRequest('code');
89
        }
90
91
        // Validate the authorization code
92
        try {
93
            $authCodePayload = json_decode($this->decrypt($encryptedAuthCode));
94
            if (time() > $authCodePayload->expire_time) {
95
                throw OAuthServerException::invalidRequest('code', 'Authorization code has expired');
96
            }
97
98
            if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) {
99
                throw OAuthServerException::invalidRequest('code', 'Authorization code has been revoked');
100
            }
101
102
            if ($authCodePayload->client_id !== $client->getIdentifier()) {
103
                throw OAuthServerException::invalidRequest('code', 'Authorization code was not issued to this client');
104
            }
105
106
            // The redirect URI is required in this request
107
            $redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
108
            if (empty($authCodePayload->redirect_uri) === false && $redirectUri === null) {
109
                throw OAuthServerException::invalidRequest('redirect_uri');
110
            }
111
112
            if ($authCodePayload->redirect_uri !== $redirectUri) {
113
                throw OAuthServerException::invalidRequest('redirect_uri', 'Invalid redirect URI');
114
            }
115
116
            $scopes = [];
117
            foreach ($authCodePayload->scopes as $scopeId) {
118
                $scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeId);
119
120
                if ($scope instanceof ScopeEntityInterface === false) {
121
                    // @codeCoverageIgnoreStart
122
                    throw OAuthServerException::invalidScope($scopeId);
123
                    // @codeCoverageIgnoreEnd
124
                }
125
126
                $scopes[] = $scope;
127
            }
128
129
            // Finalize the requested scopes
130
            $scopes = $this->scopeRepository->finalizeScopes(
131
                $scopes,
132
                $this->getIdentifier(),
133
                $client,
134
                $authCodePayload->user_id
135
            );
136
        } catch (\LogicException  $e) {
137
            throw OAuthServerException::invalidRequest('code', 'Cannot decrypt the authorization code');
138
        }
139
140
        // Validate code challenge
141
        if (
142
            $this->enableCodeExchangeProof === true
143
            && ($authCodePayload->code_challenge !== null || $this->forceEnabledCodeExchangeProof === true)
144
        ) {
145
            $codeVerifier = $this->getRequestParameter('code_verifier', $request, null);
146
            if ($codeVerifier === null) {
147
                throw OAuthServerException::invalidRequest('code_verifier');
148
            }
149
150
            switch ($authCodePayload->code_challenge_method) {
151
                case 'plain':
152
                    if (hash_equals($codeVerifier, $authCodePayload->code_challenge) === false) {
153
                        throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
154
                    }
155
156
                    break;
157
                case 'S256':
158
                    if (
159
                        hash_equals(
160
                            urlencode(base64_encode(hash('sha256', $codeVerifier))),
161
                            $authCodePayload->code_challenge
162
                        ) === false
163
                    ) {
164
                        throw OAuthServerException::invalidGrant('Failed to verify `code_verifier`.');
165
                    }
166
                    // @codeCoverageIgnoreStart
167
                    break;
168
                default:
169
                    throw OAuthServerException::serverError(
170
                        sprintf(
171
                            'Unsupported code challenge method `%s`',
172
                            $authCodePayload->code_challenge_method
173
                        )
174
                    );
175
                // @codeCoverageIgnoreEnd
176
            }
177
        }
178
179
        // Issue and persist access + refresh tokens
180
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes);
181
        $refreshToken = $this->issueRefreshToken($accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken defined by $this->issueAccessToken(...load->user_id, $scopes) on line 180 can be null; however, League\OAuth2\Server\Gra...nt::issueRefreshToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
182
183
        // Inject tokens into response type
184
        $responseType->setAccessToken($accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken defined by $this->issueAccessToken(...load->user_id, $scopes) on line 180 can be null; however, League\OAuth2\Server\Res...rface::setAccessToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
185
        $responseType->setRefreshToken($refreshToken);
0 ignored issues
show
Bug introduced by
It seems like $refreshToken defined by $this->issueRefreshToken($accessToken) on line 181 can be null; however, League\OAuth2\Server\Res...face::setRefreshToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
186
187
        // Revoke used auth code
188
        $this->authCodeRepository->revokeAuthCode($authCodePayload->auth_code_id);
189
190
        return $responseType;
191
    }
192
193
    /**
194
     * Return the grant identifier that can be used in matching up requests.
195
     *
196
     * @return string
197
     */
198
    public function getIdentifier()
199
    {
200
        return 'authorization_code';
201
    }
202
203
    /**
204
     * {@inheritdoc}
205
     */
206
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
207
    {
208
        return (
209
            array_key_exists('response_type', $request->getQueryParams())
210
            && $request->getQueryParams()['response_type'] === 'code'
211
            && isset($request->getQueryParams()['client_id'])
212
        );
213
    }
214
215
    /**
216
     * {@inheritdoc}
217
     */
218
    public function validateAuthorizationRequest(ServerRequestInterface $request)
219
    {
220
        $clientId = $this->getQueryStringParameter(
221
            'client_id',
222
            $request,
223
            $this->getServerParameter('PHP_AUTH_USER', $request)
224
        );
225
        if (is_null($clientId)) {
226
            throw OAuthServerException::invalidRequest('client_id');
227
        }
228
229
        $client = $this->clientRepository->getClientEntity(
230
            $clientId,
231
            $this->getIdentifier(),
232
            null,
233
            false
234
        );
235
236
        if ($client instanceof ClientEntityInterface === false) {
237
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
238
            throw OAuthServerException::invalidClient();
239
        }
240
241
        $redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
242
        if ($redirectUri !== null) {
243
            if (
244
                is_string($client->getRedirectUri())
245
                && (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
246
            ) {
247
                $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
248
                throw OAuthServerException::invalidClient();
249
            } elseif (
250
                is_array($client->getRedirectUri())
251
                && in_array($redirectUri, $client->getRedirectUri()) === false
252
            ) {
253
                $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
254
                throw OAuthServerException::invalidClient();
255
            }
256
        } elseif (is_array($client->getRedirectUri()) && count($client->getRedirectUri()) !== 1
257
            || empty($client->getRedirectUri())
258
        ) {
259
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
260
            throw OAuthServerException::invalidClient();
261
        }
262
263
        $scopes = $this->validateScopes(
264
            $this->getQueryStringParameter('scope', $request, $this->defaultScope),
265
            is_array($client->getRedirectUri())
266
                ? $client->getRedirectUri()[0]
267
                : $client->getRedirectUri()
268
        );
269
270
        $stateParameter = $this->getQueryStringParameter('state', $request);
271
272
        $authorizationRequest = new AuthorizationRequest();
273
        $authorizationRequest->setGrantTypeId($this->getIdentifier());
274
        $authorizationRequest->setClient($client);
275
        $authorizationRequest->setRedirectUri($redirectUri);
276
        $authorizationRequest->setState($stateParameter);
277
        $authorizationRequest->setScopes($scopes);
278
279
        if (
280
            $this->enableCodeExchangeProof === true
281
            && (($codeChallenge = $this->getQueryStringParameter('code_challenge', $request)) !== null || $this->forceEnabledCodeExchangeProof === true)
282
        ) {
283
            if ($codeChallenge === null) {
284
                throw OAuthServerException::invalidRequest('code_challenge');
285
            }
286
287
            if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeChallenge) !== 1) {
288
                throw OAuthServerException::invalidRequest(
289
                    'code_challenge',
290
                    'The code_challenge must be between 43 and 128 characters'
291
                );
292
            }
293
294
            $codeChallengeMethod = $this->getQueryStringParameter('code_challenge_method', $request, 'plain');
295
            if (in_array($codeChallengeMethod, ['plain', 'S256']) === false) {
296
                throw OAuthServerException::invalidRequest(
297
                    'code_challenge_method',
298
                    'Code challenge method must be `plain` or `S256`'
299
                );
300
            }
301
302
            $authorizationRequest->setCodeChallenge($codeChallenge);
303
            $authorizationRequest->setCodeChallengeMethod($codeChallengeMethod);
304
        }
305
306
        return $authorizationRequest;
307
    }
308
309
    /**
310
     * {@inheritdoc}
311
     */
312
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
313
    {
314
        if ($authorizationRequest->getUser() instanceof UserEntityInterface === false) {
315
            throw new \LogicException('An instance of UserEntityInterface should be set on the AuthorizationRequest');
316
        }
317
318
        $finalRedirectUri = ($authorizationRequest->getRedirectUri() === null)
319
            ? is_array($authorizationRequest->getClient()->getRedirectUri())
320
                ? $authorizationRequest->getClient()->getRedirectUri()[0]
321
                : $authorizationRequest->getClient()->getRedirectUri()
322
            : $authorizationRequest->getRedirectUri();
323
324
        // The user approved the client, redirect them back with an auth code
325
        if ($authorizationRequest->isAuthorizationApproved() === true) {
326
            $authCode = $this->issueAuthCode(
327
                $this->authCodeTTL,
328
                $authorizationRequest->getClient(),
329
                $authorizationRequest->getUser()->getIdentifier(),
330
                $authorizationRequest->getRedirectUri(),
331
                $authorizationRequest->getScopes()
332
            );
333
334
            $payload = [
335
                'client_id'             => $authCode->getClient()->getIdentifier(),
336
                'redirect_uri'          => $authCode->getRedirectUri(),
337
                'auth_code_id'          => $authCode->getIdentifier(),
338
                'scopes'                => $authCode->getScopes(),
339
                'user_id'               => $authCode->getUserIdentifier(),
340
                'expire_time'           => (new \DateTime())->add($this->authCodeTTL)->format('U'),
341
                'code_challenge'        => $authorizationRequest->getCodeChallenge(),
342
                'code_challenge_method' => $authorizationRequest->getCodeChallengeMethod(),
343
            ];
344
345
            $response = new RedirectResponse();
346
            $response->setRedirectUri(
347
                $this->makeRedirectUri(
348
                    $finalRedirectUri,
349
                    [
350
                        'code'  => $this->encrypt(
351
                            json_encode(
352
                                $payload
353
                            )
354
                        ),
355
                        'state' => $authorizationRequest->getState(),
356
                    ]
357
                )
358
            );
359
360
            return $response;
361
        }
362
363
        // The user denied the client, redirect them back with an error
364
        throw OAuthServerException::accessDenied(
365
            'The user denied the request',
366
            $this->makeRedirectUri(
367
                $finalRedirectUri,
368
                [
369
                    'state' => $authorizationRequest->getState(),
370
                ]
371
            )
372
        );
373
    }
374
}
375