Completed
Pull Request — master (#1122)
by Sebastian
05:10 queued 01:22
created

AbstractGrant::setDefaultScope()   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
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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 74
    public function setClientRepository(ClientRepositoryInterface $clientRepository)
107
    {
108 74
        $this->clientRepository = $clientRepository;
109 74
    }
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 44
    public function setScopeRepository(ScopeRepositoryInterface $scopeRepository)
123
    {
124 44
        $this->scopeRepository = $scopeRepository;
125 44
    }
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 65
    public function setRefreshTokenRepository(RefreshTokenRepositoryInterface $refreshTokenRepository)
139
    {
140 65
        $this->refreshTokenRepository = $refreshTokenRepository;
141 65
    }
142
143
    /**
144
     * @param AuthCodeRepositoryInterface $authCodeRepository
145
     */
146 48
    public function setAuthCodeRepository(AuthCodeRepositoryInterface $authCodeRepository)
147
    {
148 48
        $this->authCodeRepository = $authCodeRepository;
149 48
    }
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 19
    public function setDefaultScope($scope)
181
    {
182 19
        $this->defaultScope = $scope;
183 19
    }
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 34
        $redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
208
209 34
        if ($redirectUri !== null) {
210 16
            $this->validateRedirectUri($redirectUri, $client, $request);
211
        }
212
213 32
        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 63
    protected function getClientEntityOrFail($clientId, ServerRequestInterface $request)
232
    {
233 63
        $client = $this->clientRepository->getClientEntity($clientId);
234
235 63
        if ($client instanceof ClientEntityInterface === false) {
236 3
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
237 3
            throw OAuthServerException::invalidClient($request);
238
        }
239
240 60
        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 40
    public function validateScopes($scopes, $redirectUri = null)
305
    {
306 40
        if (!\is_array($scopes)) {
307 26
            $scopes = $this->convertScopesQueryStringToArray($scopes);
308
        }
309
310 40
        $validScopes = [];
311
312 40
        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 38
        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 26
    private function convertScopesQueryStringToArray($scopes)
333
    {
334
        return \array_filter(\explode(self::SCOPE_DELIMITER_STRING, \trim($scopes)), function ($scope) {
335 26
            return !empty($scope);
336 26
        });
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 23
    protected function getQueryStringParameter($parameter, ServerRequestInterface $request, $default = null)
398
    {
399 23
        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 22
    protected function getServerParameter($parameter, ServerRequestInterface $request, $default = null)
426
    {
427 22
        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, $claims);
454 22
        $accessToken->setExpiryDateTime((new DateTimeImmutable())->add($accessTokenTTL));
455 22
        $accessToken->setPrivateKey($this->privateKey);
456
457 22
        while ($maxGenerationAttempts-- > 0) {
458 22
            $accessToken->setIdentifier($this->generateUniqueIdentifier());
459
            try {
460 22
                $this->accessTokenRepository->persistNewAccessToken($accessToken);
461
462 20
                return $accessToken;
463 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
464 1
                if ($maxGenerationAttempts === 0) {
465 1
                    throw $e;
466
                }
467
            }
468
        }
469
    }
470
471
    /**
472
     * Issue an auth code.
473
     *
474
     * @param DateInterval           $authCodeTTL
475
     * @param ClientEntityInterface  $client
476
     * @param string                 $userIdentifier
477
     * @param string|null            $redirectUri
478
     * @param ScopeEntityInterface[] $scopes
479
     *
480
     * @throws OAuthServerException
481
     * @throws UniqueTokenIdentifierConstraintViolationException
482
     *
483
     * @return AuthCodeEntityInterface
484
     */
485 6
    protected function issueAuthCode(
486
        DateInterval $authCodeTTL,
487
        ClientEntityInterface $client,
488
        $userIdentifier,
489
        $redirectUri,
490
        array $scopes = []
491
    ) {
492 6
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
493
494 6
        $authCode = $this->authCodeRepository->getNewAuthCode();
495 6
        $authCode->setExpiryDateTime((new DateTimeImmutable())->add($authCodeTTL));
496 6
        $authCode->setClient($client);
497 6
        $authCode->setUserIdentifier($userIdentifier);
498
499 6
        if ($redirectUri !== null) {
500 1
            $authCode->setRedirectUri($redirectUri);
501
        }
502
503 6
        foreach ($scopes as $scope) {
504 1
            $authCode->addScope($scope);
505
        }
506
507 6
        while ($maxGenerationAttempts-- > 0) {
508 6
            $authCode->setIdentifier($this->generateUniqueIdentifier());
509
            try {
510 6
                $this->authCodeRepository->persistNewAuthCode($authCode);
511
512 4
                return $authCode;
513 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
514 1
                if ($maxGenerationAttempts === 0) {
515 1
                    throw $e;
516
                }
517
            }
518
        }
519
    }
520
521
    /**
522
     * @param AccessTokenEntityInterface $accessToken
523
     *
524
     * @throws OAuthServerException
525
     * @throws UniqueTokenIdentifierConstraintViolationException
526
     *
527
     * @return RefreshTokenEntityInterface|null
528
     */
529 16
    protected function issueRefreshToken(AccessTokenEntityInterface $accessToken)
530
    {
531 16
        $refreshToken = $this->refreshTokenRepository->getNewRefreshToken();
532
533 16
        if ($refreshToken === null) {
534 4
            return null;
535
        }
536
537 12
        $refreshToken->setExpiryDateTime((new DateTimeImmutable())->add($this->refreshTokenTTL));
538 12
        $refreshToken->setAccessToken($accessToken);
539
540 12
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
541
542 12
        while ($maxGenerationAttempts-- > 0) {
543 12
            $refreshToken->setIdentifier($this->generateUniqueIdentifier());
544
            try {
545 12
                $this->refreshTokenRepository->persistNewRefreshToken($refreshToken);
546
547 10
                return $refreshToken;
548 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
549 1
                if ($maxGenerationAttempts === 0) {
550 1
                    throw $e;
551
                }
552
            }
553
        }
554
    }
555
556
    /**
557
     * Generate a new unique identifier.
558
     *
559
     * @param int $length
560
     *
561
     * @throws OAuthServerException
562
     *
563
     * @return string
564
     */
565 30
    protected function generateUniqueIdentifier($length = 40)
566
    {
567
        try {
568 30
            return \bin2hex(\random_bytes($length));
569
            // @codeCoverageIgnoreStart
570
        } catch (TypeError $e) {
571
            throw OAuthServerException::serverError('An unexpected error has occurred', $e);
572
        } catch (Error $e) {
573
            throw OAuthServerException::serverError('An unexpected error has occurred', $e);
574
        } catch (Exception $e) {
575
            // If you get this message, the CSPRNG failed hard.
576
            throw OAuthServerException::serverError('Could not generate a random string', $e);
577
        }
578
        // @codeCoverageIgnoreEnd
579
    }
580
581
    /**
582
     * {@inheritdoc}
583
     */
584 5
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request)
585
    {
586 5
        $requestParameters = (array) $request->getParsedBody();
587
588
        return (
589 5
            \array_key_exists('grant_type', $requestParameters)
590 5
            && $requestParameters['grant_type'] === $this->getIdentifier()
591
        );
592
    }
593
594
    /**
595
     * {@inheritdoc}
596
     */
597 1
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
598
    {
599 1
        return false;
600
    }
601
602
    /**
603
     * {@inheritdoc}
604
     */
605 1
    public function validateAuthorizationRequest(ServerRequestInterface $request)
606
    {
607 1
        throw new LogicException('This grant cannot validate an authorization request');
608
    }
609
610
    /**
611
     * {@inheritdoc}
612
     */
613 1
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
614
    {
615 1
        throw new LogicException('This grant cannot complete an authorization request');
616
    }
617
}
618