Passed
Pull Request — master (#1410)
by
unknown
34:53
created

DeviceCodeGrant::generateUserCode()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 10
c 0
b 0
f 0
nc 8
nop 1
dl 0
loc 17
ccs 4
cts 4
cp 1
crap 4
rs 9.9332
1
<?php
2
3
/**
4
 * OAuth 2.0 Device Code grant.
5
 *
6
 * @author      Andrew Millington <[email protected]>
7
 * @copyright   Copyright (c) Alex Bilbie
8
 * @license     http://mit-license.org/
9
 *
10
 * @link        https://github.com/thephpleague/oauth2-server
11
 */
12
13
declare(strict_types=1);
14
15
namespace League\OAuth2\Server\Grant;
16
17
use DateInterval;
18
use DateTimeImmutable;
19
use Error;
20
use Exception;
21
use League\OAuth2\Server\Entities\ClientEntityInterface;
22
use League\OAuth2\Server\Entities\DeviceCodeEntityInterface;
23
use League\OAuth2\Server\Entities\ScopeEntityInterface;
24
use League\OAuth2\Server\Exception\OAuthServerException;
25
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
26
use League\OAuth2\Server\Repositories\DeviceCodeRepositoryInterface;
27
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
28
use League\OAuth2\Server\RequestEvent;
29
use League\OAuth2\Server\ResponseTypes\DeviceCodeResponse;
30
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
31
use Psr\Http\Message\ServerRequestInterface;
32
use TypeError;
33
34
use function is_null;
35
use function random_int;
36
use function strlen;
37
use function time;
38
39
/**
40
 * Device Code grant class.
41
 */
42
class DeviceCodeGrant extends AbstractGrant
43
{
44
    protected DeviceCodeRepositoryInterface $deviceCodeRepository;
45
    private bool $includeVerificationUriComplete = false;
46
    private bool $intervalVisibility = false;
47
    private string $verificationUri;
48
49 17
    public function __construct(
50
        DeviceCodeRepositoryInterface $deviceCodeRepository,
51
        RefreshTokenRepositoryInterface $refreshTokenRepository,
52
        private DateInterval $deviceCodeTTL,
53
        string $verificationUri,
54
        private readonly int $defaultInterval = 5
55
    ) {
56 17
        $this->setDeviceCodeRepository($deviceCodeRepository);
57 17
        $this->setRefreshTokenRepository($refreshTokenRepository);
58
59 17
        $this->refreshTokenTTL = new DateInterval('P1M');
60
61 17
        $this->setVerificationUri($verificationUri);
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 2
    public function canRespondToDeviceAuthorizationRequest(ServerRequestInterface $request): bool
68
    {
69 2
        return true;
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75 7
    public function respondToDeviceAuthorizationRequest(ServerRequestInterface $request): DeviceCodeResponse
76
    {
77 7
        $clientId = $this->getRequestParameter(
78 7
            'client_id',
79 7
            $request,
80 7
            $this->getServerParameter('PHP_AUTH_USER', $request)
81 7
        );
82
83 7
        if ($clientId === null) {
84 2
            throw OAuthServerException::invalidRequest('client_id');
85
        }
86
87 5
        $client = $this->getClientEntityOrFail($clientId, $request);
88
89 4
        $scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
90
91 4
        $deviceCodeEntity = $this->issueDeviceCode(
92 4
            $this->deviceCodeTTL,
93 4
            $client,
94 4
            $this->verificationUri,
95 4
            $scopes
96 4
        );
97
98 4
        $response = new DeviceCodeResponse();
99
100 4
        if ($this->includeVerificationUriComplete === true) {
101 1
            $response->includeVerificationUriComplete();
102
        }
103
104 4
        if ($this->intervalVisibility === true) {
105
            $response->includeInterval();
106 4
        }
107
108
        $response->setDeviceCodeEntity($deviceCodeEntity);
109
110
        return $response;
111
    }
112 3
113
    /**
114 3
     * {@inheritdoc}
115
     */
116 3
    public function completeDeviceAuthorizationRequest(string $deviceCode, string $userId, bool $userApproved): void
117
    {
118
        $deviceCode = $this->deviceCodeRepository->getDeviceCodeEntityByDeviceCode($deviceCode);
119
120 3
        if ($deviceCode instanceof DeviceCodeEntityInterface === false) {
121
            throw OAuthServerException::invalidRequest('device_code', 'Device code does not exist');
122
        }
123
124 3
        if ($userId === '') {
125 3
            throw OAuthServerException::invalidRequest('user_id', 'User ID is required');
126
        }
127 3
128
        $deviceCode->setUserIdentifier($userId);
129
        $deviceCode->setUserApproved($userApproved);
130
131
        $this->deviceCodeRepository->persistDeviceCode($deviceCode);
132
    }
133 7
134
    /**
135
     * {@inheritdoc}
136
     */
137
    public function respondToAccessTokenRequest(
138
        ServerRequestInterface $request,
139 7
        ResponseTypeInterface $responseType,
140 6
        DateInterval $accessTokenTTL
141
    ): ResponseTypeInterface {
142 3
        // Validate request
143 3
        $client = $this->validateClient($request);
144
        $deviceCodeEntity = $this->validateDeviceCode($request, $client);
145
146 3
        // If device code has no user associated, respond with pending or slow down
147 1
        if (is_null($deviceCodeEntity->getUserIdentifier())) {
148
            $shouldSlowDown = false;
149
150 2
            if ($this->deviceCodePolledTooSoon($deviceCodeEntity) === true) {
151 1
                $deviceCodeEntity->setInterval($deviceCodeEntity->getInterval() + 5);
152
153
                $shouldSlowDown = true;
154
            }
155 1
156
            $deviceCodeEntity->setLastPolledAt(new DateTimeImmutable());
157
            $this->deviceCodeRepository->persistDeviceCode($deviceCodeEntity);
158 1
159 1
            if ($shouldSlowDown) {
160 1
                throw OAuthServerException::slowDown(
161
                    interval: $this->intervalVisibility ? $deviceCodeEntity->getInterval() : null
162
                );
163 1
            }
164
165 1
            throw OAuthServerException::authorizationPending();
166 1
        }
167 1
168
        if ($deviceCodeEntity->getUserApproved() === false) {
169
            throw OAuthServerException::accessDenied();
170 1
        }
171
172 1
        // Finalize the requested scopes
173
        $finalizedScopes = $this->scopeRepository->finalizeScopes($deviceCodeEntity->getScopes(), $this->getIdentifier(), $client, $deviceCodeEntity->getUserIdentifier());
174
175
        // Issue and persist new access token
176
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $deviceCodeEntity->getUserIdentifier(), $finalizedScopes);
177
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
178 6
        $responseType->setAccessToken($accessToken);
179
180 6
        // Issue and persist new refresh token if given
181
        $refreshToken = $this->issueRefreshToken($accessToken);
182 6
183 1
        if ($refreshToken !== null) {
184
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
185
            $responseType->setRefreshToken($refreshToken);
186 5
        }
187 5
188 5
        $this->deviceCodeRepository->revokeDeviceCode($deviceCodeEntity->getIdentifier());
189
190 5
        return $responseType;
191
    }
192
193
    /**
194
     * @throws OAuthServerException
195
     */
196 5
    protected function validateDeviceCode(ServerRequestInterface $request, ClientEntityInterface $client): DeviceCodeEntityInterface
197 1
    {
198
        $deviceCode = $this->getRequestParameter('device_code', $request);
199
200 4
        if (is_null($deviceCode)) {
201
            throw OAuthServerException::invalidRequest('device_code');
202
        }
203
204 4
        $deviceCodeEntity = $this->deviceCodeRepository->getDeviceCodeEntityByDeviceCode(
205
            $deviceCode
206
        );
207
208 4
        if ($deviceCodeEntity instanceof DeviceCodeEntityInterface === false) {
209 1
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));
210
211
            throw OAuthServerException::invalidGrant();
212 3
        }
213
214
        if (time() > $deviceCodeEntity->getExpiryDateTime()->getTimestamp()) {
215 4
            throw OAuthServerException::expiredToken('device_code');
216
        }
217 4
218
        if ($this->deviceCodeRepository->isDeviceCodeRevoked($deviceCode) === true) {
219
            throw OAuthServerException::invalidRequest('device_code', 'Device code has been revoked');
220
        }
221
222
        if ($deviceCodeEntity->getClient()->getIdentifier() !== $client->getIdentifier()) {
223 17
            throw OAuthServerException::invalidRequest('device_code', 'Device code was not issued to this client');
224
        }
225 17
226
        return $deviceCodeEntity;
227
    }
228
229
    private function deviceCodePolledTooSoon(DeviceCodeEntityInterface $deviceCodeEntity): bool
230
    {
231 8
        $lastPoll = $deviceCodeEntity->getLastPolledAt();
232
233 8
        return $lastPoll !== null && $lastPoll->getTimestamp() + $deviceCodeEntity->getInterval() > time();
234
    }
235
236 17
    /**
237
     * Set the verification uri
238 17
     */
239
    public function setVerificationUri(string $verificationUri): void
240
    {
241
        $this->verificationUri = $verificationUri;
242
    }
243
244
    /**
245
     * {@inheritdoc}
246
     */
247
    public function getIdentifier(): string
248
    {
249 4
        return 'urn:ietf:params:oauth:grant-type:device_code';
250
    }
251
252
    private function setDeviceCodeRepository(DeviceCodeRepositoryInterface $deviceCodeRepository): void
253
    {
254
        $this->deviceCodeRepository = $deviceCodeRepository;
255 4
    }
256
257 4
    /**
258 4
     * Issue a device code.
259 4
     *
260 4
     * @param ScopeEntityInterface[] $scopes
261
     *
262 4
     * @throws OAuthServerException
263 1
     * @throws UniqueTokenIdentifierConstraintViolationException
264
     */
265
    protected function issueDeviceCode(
266 4
        DateInterval $deviceCodeTTL,
267 4
        ClientEntityInterface $client,
268
        string $verificationUri,
269
        array $scopes = [],
270 4
    ): DeviceCodeEntityInterface {
271 4
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
272 4
273
        $deviceCode = $this->deviceCodeRepository->getNewDeviceCode();
274
        $deviceCode->setExpiryDateTime((new DateTimeImmutable())->add($deviceCodeTTL));
275 4
        $deviceCode->setClient($client);
276
        $deviceCode->setVerificationUri($verificationUri);
277 4
        $deviceCode->setInterval($this->defaultInterval);
278
279
        foreach ($scopes as $scope) {
280
            $deviceCode->addScope($scope);
281
        }
282
283
        while ($maxGenerationAttempts-- > 0) {
284
            $deviceCode->setIdentifier($this->generateUniqueIdentifier());
285
            $deviceCode->setUserCode($this->generateUserCode());
286
287
            try {
288
                $this->deviceCodeRepository->persistDeviceCode($deviceCode);
289
290
                return $deviceCode;
291
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
292
                if ($maxGenerationAttempts === 0) {
293
                    throw $e;
294 4
                }
295
            }
296
        }
297 4
298 4
        // This should never be hit. It is here to work around a PHPStan false error
299
        return $deviceCode;
300 4
    }
301 4
302
    /**
303
     * Generate a new user code.
304 4
     *
305
     * @throws OAuthServerException
306
     */
307
    protected function generateUserCode(int $length = 8): string
308
    {
309
        try {
310
            $userCode = '';
311
            $userCodeCharacters = 'BCDFGHJKLMNPQRSTVWXZ';
312
313
            while (strlen($userCode) < $length) {
314
                $userCode .= $userCodeCharacters[random_int(0, 19)];
315 1
            }
316
317 1
            return $userCode;
318
            // @codeCoverageIgnoreStart
319
        } catch (TypeError | Error $e) {
320 4
            throw OAuthServerException::serverError('An unexpected error has occurred', $e);
321
        } catch (Exception $e) {
322 4
            // If you get this message, the CSPRNG failed hard.
323
            throw OAuthServerException::serverError('Could not generate a random string', $e);
324
        }
325 1
        // @codeCoverageIgnoreEnd
326
    }
327 1
328
    public function setIntervalVisibility(bool $intervalVisibility): void
329
    {
330
        $this->intervalVisibility = $intervalVisibility;
331
    }
332
333
    public function getIntervalVisibility(): bool
334
    {
335
        return $this->intervalVisibility;
336
    }
337
338
    public function setIncludeVerificationUriComplete(bool $includeVerificationUriComplete): void
339
    {
340
        $this->includeVerificationUriComplete = $includeVerificationUriComplete;
341
    }
342
}
343