Completed
Pull Request — master (#912)
by fizzka
02:04
created

AbstractGrant::setPrivateKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * OAuth 2.0 Abstract grant.
4
 *
5
 * @author      Alex Bilbie <[email protected]>
6
 * @copyright   Copyright (c) Alex Bilbie
7
 * @license     http://mit-license.org/
8
 *
9
 * @link        https://github.com/thephpleague/oauth2-server
10
 */
11
namespace League\OAuth2\Server\Grant;
12
13
use League\Event\EmitterAwareTrait;
14
use League\OAuth2\Server\CryptKey;
15
use League\OAuth2\Server\CryptTrait;
16
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
17
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
18
use League\OAuth2\Server\Entities\ClientEntityInterface;
19
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
20
use League\OAuth2\Server\Entities\ScopeEntityInterface;
21
use League\OAuth2\Server\Exception\OAuthServerException;
22
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
23
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
24
use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;
25
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
26
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
27
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
28
use League\OAuth2\Server\Repositories\UserRepositoryInterface;
29
use League\OAuth2\Server\RequestEvent;
30
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
31
use Psr\Http\Message\ServerRequestInterface;
32
33
/**
34
 * Abstract grant class.
35
 */
36
abstract class AbstractGrant implements GrantTypeInterface
37
{
38
    use EmitterAwareTrait, CryptTrait;
39
40
    const SCOPE_DELIMITER_STRING = ' ';
41
42
    const MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS = 10;
43
44
    /**
45
     * @var ClientRepositoryInterface
46
     */
47
    protected $clientRepository;
48
49
    /**
50
     * @var AccessTokenRepositoryInterface
51
     */
52
    protected $accessTokenRepository;
53
54
    /**
55
     * @var ScopeRepositoryInterface
56
     */
57
    protected $scopeRepository;
58
59
    /**
60
     * @var AuthCodeRepositoryInterface
61
     */
62
    protected $authCodeRepository;
63
64
    /**
65
     * @var RefreshTokenRepositoryInterface
66
     */
67
    protected $refreshTokenRepository;
68
69
    /**
70
     * @var UserRepositoryInterface
71
     */
72
    protected $userRepository;
73
74
    /**
75
     * @var \DateInterval
76
     */
77
    protected $refreshTokenTTL;
78
79
    /**
80
     * @var \League\OAuth2\Server\CryptKey
81
     */
82
    protected $privateKey;
83
84
    /**
85
     * @string
86
     */
87
    protected $defaultScope;
88
89
    /**
90
     * @param ClientRepositoryInterface $clientRepository
91
     */
92 64
    public function setClientRepository(ClientRepositoryInterface $clientRepository)
93
    {
94 64
        $this->clientRepository = $clientRepository;
95 64
    }
96
97
    /**
98
     * @param AccessTokenRepositoryInterface $accessTokenRepository
99
     */
100 42
    public function setAccessTokenRepository(AccessTokenRepositoryInterface $accessTokenRepository)
101
    {
102 42
        $this->accessTokenRepository = $accessTokenRepository;
103 42
    }
104
105
    /**
106
     * @param ScopeRepositoryInterface $scopeRepository
107
     */
108 32
    public function setScopeRepository(ScopeRepositoryInterface $scopeRepository)
109
    {
110 32
        $this->scopeRepository = $scopeRepository;
111 32
    }
112
113
    /**
114
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
115
     */
116 56
    public function setRefreshTokenRepository(RefreshTokenRepositoryInterface $refreshTokenRepository)
117
    {
118 56
        $this->refreshTokenRepository = $refreshTokenRepository;
119 56
    }
120
121
    /**
122
     * @param AuthCodeRepositoryInterface $authCodeRepository
123
     */
124 42
    public function setAuthCodeRepository(AuthCodeRepositoryInterface $authCodeRepository)
125
    {
126 42
        $this->authCodeRepository = $authCodeRepository;
127 42
    }
128
129
    /**
130
     * @param UserRepositoryInterface $userRepository
131
     */
132 5
    public function setUserRepository(UserRepositoryInterface $userRepository)
133
    {
134 5
        $this->userRepository = $userRepository;
135 5
    }
136
137
    /**
138
     * {@inheritdoc}
139
     */
140 1
    public function setRefreshTokenTTL(\DateInterval $refreshTokenTTL)
141
    {
142 1
        $this->refreshTokenTTL = $refreshTokenTTL;
143 1
    }
144
145
    /**
146
     * Set the private key
147
     *
148
     * @param \League\OAuth2\Server\CryptKey $key
149
     */
150 20
    public function setPrivateKey(CryptKey $key)
151
    {
152 20
        $this->privateKey = $key;
153 20
    }
154
155
    /**
156
     * @param string $scope
157
     */
158 16
    public function setDefaultScope($scope)
159
    {
160 16
        $this->defaultScope = $scope;
161 16
    }
162
163
    /**
164
     * Validate the client.
165
     *
166
     * @param ServerRequestInterface $request
167
     *
168
     * @throws OAuthServerException
169
     *
170
     * @return ClientEntityInterface
171
     */
172 42
    protected function validateClient(ServerRequestInterface $request)
173
    {
174 42
        list($basicAuthUser, $basicAuthPassword) = $this->getBasicAuthCredentials($request);
175
176 42
        $clientId = $this->getRequestParameter('client_id', $request, $basicAuthUser);
177 42
        if (is_null($clientId)) {
178 1
            throw OAuthServerException::invalidRequest('client_id');
179
        }
180
181
        // If the client is confidential require the client secret
182 41
        $clientSecret = $this->getRequestParameter('client_secret', $request, $basicAuthPassword);
183
184 41
        $client = $this->clientRepository->getClientEntity(
185 41
            $clientId,
186 41
            $this->getIdentifier(),
187 41
            $clientSecret,
188 41
            true
189
        );
190
191 41
        if ($client instanceof ClientEntityInterface === false) {
192 4
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
193 4
            throw OAuthServerException::invalidClient();
194
        }
195
196 37
        $redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
197
198 37
        if ($redirectUri !== null) {
199 20
            $this->validateRedirectUri($redirectUri, $client, $request);
200
        }
201
202 35
        return $client;
203
    }
204
205
    /**
206
     * Validate redirectUri from the request.
207
     * If a redirect URI is provided ensure it matches what is pre-registered
208
     *
209
     * @param string $redirectUri
210
     * @param ClientEntityInterface $client
211
     * @param ServerRequestInterface $request
212
     *
213
     * @throws OAuthServerException
214
     *
215
     * @return void
216
     */
217 34
    protected function validateRedirectUri(
218
        string $redirectUri,
219
        ClientEntityInterface $client,
220
        ServerRequestInterface $request
221
    ) {
222 34
        if (is_string($client->getRedirectUri())
223 34
            && (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
224
        ) {
225 3
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
226 3
            throw OAuthServerException::invalidClient();
227 31
        } elseif (is_array($client->getRedirectUri())
228 31
            && in_array($redirectUri, $client->getRedirectUri(), true) === false
229
        ) {
230 3
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
231 3
            throw OAuthServerException::invalidClient();
232
        }
233 28
    }
234
235
    /**
236
     * Validate scopes in the request.
237
     *
238
     * @param string $scopes
239
     * @param string $redirectUri
240
     *
241
     * @throws OAuthServerException
242
     *
243
     * @return ScopeEntityInterface[]
244
     */
245
    public function validateScopes($scopes, $redirectUri = null)
246
    {
247 23
        $scopesList = array_filter(explode(self::SCOPE_DELIMITER_STRING, trim($scopes)), function ($scope) {
248 23
            return !empty($scope);
249 23
        });
250
251 23
        $validScopes = [];
252
253 23
        foreach ($scopesList as $scopeItem) {
254 17
            $scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem);
255
256 17
            if ($scope instanceof ScopeEntityInterface === false) {
257 1
                throw OAuthServerException::invalidScope($scopeItem, $redirectUri);
258
            }
259
260 16
            $validScopes[] = $scope;
261
        }
262
263 22
        return $validScopes;
264
    }
265
266
    /**
267
     * Retrieve request parameter.
268
     *
269
     * @param string                 $parameter
270
     * @param ServerRequestInterface $request
271
     * @param mixed                  $default
272
     *
273
     * @return null|string
274
     */
275 42
    protected function getRequestParameter($parameter, ServerRequestInterface $request, $default = null)
276
    {
277 42
        $requestParameters = (array) $request->getParsedBody();
278
279 42
        return isset($requestParameters[$parameter]) ? $requestParameters[$parameter] : $default;
280
    }
281
282
    /**
283
     * Retrieve HTTP Basic Auth credentials with the Authorization header
284
     * of a request. First index of the returned array is the username,
285
     * second is the password (so list() will work). If the header does
286
     * not exist, or is otherwise an invalid HTTP Basic header, return
287
     * [null, null].
288
     *
289
     * @param ServerRequestInterface $request
290
     *
291
     * @return string[]|null[]
292
     */
293 47
    protected function getBasicAuthCredentials(ServerRequestInterface $request)
294
    {
295 47
        if (!$request->hasHeader('Authorization')) {
296 42
            return [null, null];
297
        }
298
299 5
        $header = $request->getHeader('Authorization')[0];
300 5
        if (strpos($header, 'Basic ') !== 0) {
301 1
            return [null, null];
302
        }
303
304 4
        if (!($decoded = base64_decode(substr($header, 6)))) {
305 1
            return [null, null];
306
        }
307
308 3
        if (strpos($decoded, ':') === false) {
309 1
            return [null, null]; // HTTP Basic header without colon isn't valid
310
        }
311
312 2
        return explode(':', $decoded, 2);
313
    }
314
315
    /**
316
     * Retrieve query string parameter.
317
     *
318
     * @param string                 $parameter
319
     * @param ServerRequestInterface $request
320
     * @param mixed                  $default
321
     *
322
     * @return null|string
323
     */
324 21
    protected function getQueryStringParameter($parameter, ServerRequestInterface $request, $default = null)
325
    {
326 21
        return isset($request->getQueryParams()[$parameter]) ? $request->getQueryParams()[$parameter] : $default;
327
    }
328
329
    /**
330
     * Retrieve cookie parameter.
331
     *
332
     * @param string                 $parameter
333
     * @param ServerRequestInterface $request
334
     * @param mixed                  $default
335
     *
336
     * @return null|string
337
     */
338 1
    protected function getCookieParameter($parameter, ServerRequestInterface $request, $default = null)
339
    {
340 1
        return isset($request->getCookieParams()[$parameter]) ? $request->getCookieParams()[$parameter] : $default;
341
    }
342
343
    /**
344
     * Retrieve server parameter.
345
     *
346
     * @param string                 $parameter
347
     * @param ServerRequestInterface $request
348
     * @param mixed                  $default
349
     *
350
     * @return null|string
351
     */
352 20
    protected function getServerParameter($parameter, ServerRequestInterface $request, $default = null)
353
    {
354 20
        return isset($request->getServerParams()[$parameter]) ? $request->getServerParams()[$parameter] : $default;
355
    }
356
357
    /**
358
     * Issue an access token.
359
     *
360
     * @param \DateInterval          $accessTokenTTL
361
     * @param ClientEntityInterface  $client
362
     * @param string|null            $userIdentifier
363
     * @param ScopeEntityInterface[] $scopes
364
     *
365
     * @throws OAuthServerException
366
     * @throws UniqueTokenIdentifierConstraintViolationException
367
     *
368
     * @return AccessTokenEntityInterface
369
     */
370 17
    protected function issueAccessToken(
371
        \DateInterval $accessTokenTTL,
372
        ClientEntityInterface $client,
373
        $userIdentifier,
374
        array $scopes = []
375
    ) {
376 17
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
377
378 17
        $accessToken = $this->accessTokenRepository->getNewToken($client, $scopes, $userIdentifier);
379 17
        $accessToken->setClient($client);
380 17
        $accessToken->setUserIdentifier($userIdentifier);
381 17
        $accessToken->setExpiryDateTime((new \DateTime())->add($accessTokenTTL));
382
383 17
        foreach ($scopes as $scope) {
384 13
            $accessToken->addScope($scope);
385
        }
386
387 17
        while ($maxGenerationAttempts-- > 0) {
388 17
            $accessToken->setIdentifier($this->generateUniqueIdentifier());
389
            try {
390 17
                $this->accessTokenRepository->persistNewAccessToken($accessToken);
391
392 15
                return $accessToken;
393 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
394 1
                if ($maxGenerationAttempts === 0) {
395 1
                    throw $e;
396
                }
397
            }
398
        }
399
    }
400
401
    /**
402
     * Issue an auth code.
403
     *
404
     * @param \DateInterval          $authCodeTTL
405
     * @param ClientEntityInterface  $client
406
     * @param string                 $userIdentifier
407
     * @param string|null            $redirectUri
408
     * @param ScopeEntityInterface[] $scopes
409
     *
410
     * @throws OAuthServerException
411
     * @throws UniqueTokenIdentifierConstraintViolationException
412
     *
413
     * @return AuthCodeEntityInterface
414
     */
415 6
    protected function issueAuthCode(
416
        \DateInterval $authCodeTTL,
417
        ClientEntityInterface $client,
418
        $userIdentifier,
419
        $redirectUri,
420
        array $scopes = []
421
    ) {
422 6
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
423
424 6
        $authCode = $this->authCodeRepository->getNewAuthCode();
425 6
        $authCode->setExpiryDateTime((new \DateTime())->add($authCodeTTL));
426 6
        $authCode->setClient($client);
427 6
        $authCode->setUserIdentifier($userIdentifier);
428
429 6
        if ($redirectUri !== null) {
430 1
            $authCode->setRedirectUri($redirectUri);
431
        }
432
433 6
        foreach ($scopes as $scope) {
434 1
            $authCode->addScope($scope);
435
        }
436
437 6
        while ($maxGenerationAttempts-- > 0) {
438 6
            $authCode->setIdentifier($this->generateUniqueIdentifier());
439
            try {
440 6
                $this->authCodeRepository->persistNewAuthCode($authCode);
441
442 4
                return $authCode;
443 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
444 1
                if ($maxGenerationAttempts === 0) {
445 1
                    throw $e;
446
                }
447
            }
448
        }
449
    }
450
451
    /**
452
     * @param AccessTokenEntityInterface $accessToken
453
     *
454
     * @throws OAuthServerException
455
     * @throws UniqueTokenIdentifierConstraintViolationException
456
     *
457
     * @return RefreshTokenEntityInterface
458
     */
459 10
    protected function issueRefreshToken(AccessTokenEntityInterface $accessToken)
460
    {
461 10
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
462
463 10
        $refreshToken = $this->refreshTokenRepository->getNewRefreshToken();
464 10
        $refreshToken->setExpiryDateTime((new \DateTime())->add($this->refreshTokenTTL));
465 10
        $refreshToken->setAccessToken($accessToken);
466
467 10
        while ($maxGenerationAttempts-- > 0) {
468 10
            $refreshToken->setIdentifier($this->generateUniqueIdentifier());
469
            try {
470 10
                $this->refreshTokenRepository->persistNewRefreshToken($refreshToken);
471
472 8
                return $refreshToken;
473 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
474 1
                if ($maxGenerationAttempts === 0) {
475 1
                    throw $e;
476
                }
477
            }
478
        }
479
    }
480
481
    /**
482
     * Generate a new unique identifier.
483
     *
484
     * @param int $length
485
     *
486
     * @throws OAuthServerException
487
     *
488
     * @return string
489
     */
490 25
    protected function generateUniqueIdentifier($length = 40)
491
    {
492
        try {
493 25
            return bin2hex(random_bytes($length));
494
            // @codeCoverageIgnoreStart
495
        } catch (\TypeError $e) {
496
            throw OAuthServerException::serverError('An unexpected error has occurred');
497
        } catch (\Error $e) {
498
            throw OAuthServerException::serverError('An unexpected error has occurred');
499
        } catch (\Exception $e) {
500
            // If you get this message, the CSPRNG failed hard.
501
            throw OAuthServerException::serverError('Could not generate a random string');
502
        }
503
        // @codeCoverageIgnoreEnd
504
    }
505
506
    /**
507
     * {@inheritdoc}
508
     */
509 5
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request)
510
    {
511 5
        $requestParameters = (array) $request->getParsedBody();
512
513
        return (
514 5
            array_key_exists('grant_type', $requestParameters)
515 5
            && $requestParameters['grant_type'] === $this->getIdentifier()
516
        );
517
    }
518
519
    /**
520
     * {@inheritdoc}
521
     */
522 1
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
523
    {
524 1
        return false;
525
    }
526
527
    /**
528
     * {@inheritdoc}
529
     */
530 1
    public function validateAuthorizationRequest(ServerRequestInterface $request)
531
    {
532 1
        throw new \LogicException('This grant cannot validate an authorization request');
533
    }
534
535
    /**
536
     * {@inheritdoc}
537
     */
538 1
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
539
    {
540 1
        throw new \LogicException('This grant cannot complete an authorization request');
541
    }
542
}
543