Passed
Pull Request — master (#1122)
by Sebastian
02:08
created

AbstractGrant::getClientCredentials()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 13
ccs 7
cts 7
cp 1
crap 2
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);
454 22
        $accessToken->setExpiryDateTime((new DateTimeImmutable())->add($accessTokenTTL));
455 22
        $accessToken->setPrivateKey($this->privateKey);
456 22
        foreach ($claims as $claim){
457
            $accessToken->addClaim($claim);
458
        }
459
460 22
        while ($maxGenerationAttempts-- > 0) {
461 22
            $accessToken->setIdentifier($this->generateUniqueIdentifier());
462
            try {
463 22
                $this->accessTokenRepository->persistNewAccessToken($accessToken);
464
465 20
                return $accessToken;
466 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
467 1
                if ($maxGenerationAttempts === 0) {
468 1
                    throw $e;
469
                }
470
            }
471
        }
472
    }
473
474
    /**
475
     * Issue an auth code.
476
     *
477
     * @param DateInterval           $authCodeTTL
478
     * @param ClientEntityInterface  $client
479
     * @param string                 $userIdentifier
480
     * @param string|null            $redirectUri
481
     * @param ScopeEntityInterface[] $scopes
482
     *
483
     * @throws OAuthServerException
484
     * @throws UniqueTokenIdentifierConstraintViolationException
485
     *
486
     * @return AuthCodeEntityInterface
487
     */
488 6
    protected function issueAuthCode(
489
        DateInterval $authCodeTTL,
490
        ClientEntityInterface $client,
491
        $userIdentifier,
492
        $redirectUri,
493
        array $scopes = []
494
    ) {
495 6
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
496
497 6
        $authCode = $this->authCodeRepository->getNewAuthCode();
498 6
        $authCode->setExpiryDateTime((new DateTimeImmutable())->add($authCodeTTL));
499 6
        $authCode->setClient($client);
500 6
        $authCode->setUserIdentifier($userIdentifier);
501
502 6
        if ($redirectUri !== null) {
503 1
            $authCode->setRedirectUri($redirectUri);
504
        }
505
506 6
        foreach ($scopes as $scope) {
507 1
            $authCode->addScope($scope);
508
        }
509
510 6
        while ($maxGenerationAttempts-- > 0) {
511 6
            $authCode->setIdentifier($this->generateUniqueIdentifier());
512
            try {
513 6
                $this->authCodeRepository->persistNewAuthCode($authCode);
514
515 4
                return $authCode;
516 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
517 1
                if ($maxGenerationAttempts === 0) {
518 1
                    throw $e;
519
                }
520
            }
521
        }
522
    }
523
524
    /**
525
     * @param AccessTokenEntityInterface $accessToken
526
     *
527
     * @throws OAuthServerException
528
     * @throws UniqueTokenIdentifierConstraintViolationException
529
     *
530
     * @return RefreshTokenEntityInterface|null
531
     */
532 16
    protected function issueRefreshToken(AccessTokenEntityInterface $accessToken)
533
    {
534 16
        $refreshToken = $this->refreshTokenRepository->getNewRefreshToken();
535
536 16
        if ($refreshToken === null) {
537 4
            return null;
538
        }
539
540 12
        $refreshToken->setExpiryDateTime((new DateTimeImmutable())->add($this->refreshTokenTTL));
541 12
        $refreshToken->setAccessToken($accessToken);
542
543 12
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
544
545 12
        while ($maxGenerationAttempts-- > 0) {
546 12
            $refreshToken->setIdentifier($this->generateUniqueIdentifier());
547
            try {
548 12
                $this->refreshTokenRepository->persistNewRefreshToken($refreshToken);
549
550 10
                return $refreshToken;
551 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
552 1
                if ($maxGenerationAttempts === 0) {
553 1
                    throw $e;
554
                }
555
            }
556
        }
557
    }
558
559
    /**
560
     * Generate a new unique identifier.
561
     *
562
     * @param int $length
563
     *
564
     * @throws OAuthServerException
565
     *
566
     * @return string
567
     */
568 30
    protected function generateUniqueIdentifier($length = 40)
569
    {
570
        try {
571 30
            return \bin2hex(\random_bytes($length));
572
            // @codeCoverageIgnoreStart
573
        } catch (TypeError $e) {
574
            throw OAuthServerException::serverError('An unexpected error has occurred', $e);
575
        } catch (Error $e) {
576
            throw OAuthServerException::serverError('An unexpected error has occurred', $e);
577
        } catch (Exception $e) {
578
            // If you get this message, the CSPRNG failed hard.
579
            throw OAuthServerException::serverError('Could not generate a random string', $e);
580
        }
581
        // @codeCoverageIgnoreEnd
582
    }
583
584
    /**
585
     * {@inheritdoc}
586
     */
587 5
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request)
588
    {
589 5
        $requestParameters = (array) $request->getParsedBody();
590
591
        return (
592 5
            \array_key_exists('grant_type', $requestParameters)
593 5
            && $requestParameters['grant_type'] === $this->getIdentifier()
594
        );
595
    }
596
597
    /**
598
     * {@inheritdoc}
599
     */
600 1
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
601
    {
602 1
        return false;
603
    }
604
605
    /**
606
     * {@inheritdoc}
607
     */
608 1
    public function validateAuthorizationRequest(ServerRequestInterface $request)
609
    {
610 1
        throw new LogicException('This grant cannot validate an authorization request');
611
    }
612
613
    /**
614
     * {@inheritdoc}
615
     */
616 1
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
617
    {
618 1
        throw new LogicException('This grant cannot complete an authorization request');
619
    }
620
}
621