Passed
Pull Request — master (#1122)
by Andrew
04:11 queued 31s
created

AbstractGrant::setClaimRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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