Failed Conditions
Push — master ( aacec5...b5a0b4 )
by Florent
04:50
created

IdTokenBuilder::withAuthorizationCodeId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2018 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace OAuth2Framework\Component\OpenIdConnect;
15
16
use Base64Url\Base64Url;
17
use Jose\Component\Core\Converter\StandardConverter;
18
use Jose\Component\Core\JWK;
19
use Jose\Component\Core\JWKSet;
20
use Jose\Component\Encryption\JWEBuilder;
21
use Jose\Component\Encryption\Serializer\CompactSerializer as JweCompactSerializer;
22
use Jose\Component\KeyManagement\JKUFactory;
23
use Jose\Component\Signature\JWSBuilder;
24
use Jose\Component\Signature\Serializer\CompactSerializer as JwsCompactSerializer;
25
use OAuth2Framework\Component\AuthorizationCodeGrant\AuthorizationCodeId;
26
use OAuth2Framework\Component\AuthorizationCodeGrant\AuthorizationCodeRepository;
27
use OAuth2Framework\Component\Core\AccessToken\AccessToken;
28
use OAuth2Framework\Component\Core\AccessToken\AccessTokenId;
29
use OAuth2Framework\Component\Core\Client\Client;
30
use OAuth2Framework\Component\Core\UserAccount\UserAccount;
31
use OAuth2Framework\Component\OpenIdConnect\UserInfo\UserInfo;
32
33
class IdTokenBuilder
34
{
35
    /**
36
     * @var string
37
     */
38
    private $issuer;
39
40
    /**
41
     * @var Client
42
     */
43
    private $client;
44
45
    /**
46
     * @var UserAccount
47
     */
48
    private $userAccount;
49
50
    /**
51
     * @var string
52
     */
53
    private $redirectUri;
54
55
    /**
56
     * @var UserInfo
57
     */
58
    private $userinfo;
59
60
    /**
61
     * @var JWKSet
62
     */
63
    private $signatureKeys;
64
65
    /**
66
     * @var int
67
     */
68
    private $lifetime;
69
70
    /**
71
     * @var string
72
     */
73
    private $scope;
74
75
    /**
76
     * @var array
77
     */
78
    private $requestedClaims = [];
79
80
    /**
81
     * @var string
82
     */
83
    private $claimsLocales;
84
85
    /**
86
     * @var AccessTokenId|null
87
     */
88
    private $accessTokenId;
89
90
    /**
91
     * @var AuthorizationCodeId|null
92
     */
93
    private $authorizationCodeId;
94
95
    /**
96
     * @var string
97
     */
98
    private $nonce;
99
100
    /**
101
     * @var bool
102
     */
103
    private $withAuthenticationTime = false;
104
105
    /**
106
     * @var JWSBuilder
107
     */
108
    private $jwsBuilder;
109
110
    /**
111
     * @var string
112
     */
113
    private $signatureAlgorithm;
114
115
    /**
116
     * @var JWEBuilder
117
     */
118
    private $jweBuilder;
119
120
    /**
121
     * @var string
122
     */
123
    private $keyEncryptionAlgorithm;
124
125
    /**
126
     * @var string
127
     */
128
    private $contentEncryptionAlgorithm;
129
130
    /**
131
     * @var \DateTimeImmutable
132
     */
133
    private $expiresAt;
134
135
    /**
136
     * @var JKUFactory|null
137
     */
138
    private $jkuFactory;
139
140
    /**
141
     * @var AuthorizationCodeRepository|null
142
     */
143
    private $authorizationCodeRepository;
144
145
    public function __construct(string $issuer, UserInfo $userinfo, int $lifetime, Client $client, UserAccount $userAccount, string $redirectUri, ?JKUFactory $jkuFactory, ?AuthorizationCodeRepository $authorizationCodeRepository)
146
    {
147
        $this->issuer = $issuer;
148
        $this->userinfo = $userinfo;
149
        $this->lifetime = $lifetime;
150
        $this->client = $client;
151
        $this->userAccount = $userAccount;
152
        $this->redirectUri = $redirectUri;
153
        $this->jkuFactory = $jkuFactory;
154
        $this->authorizationCodeRepository = $authorizationCodeRepository;
155
    }
156
157
    public function setAccessToken(AccessToken $accessToken): void
158
    {
159
        $this->accessTokenId = $accessToken->getId();
160
        $this->expiresAt = $accessToken->getExpiresAt();
161
        $this->scope = $accessToken->getParameter()->has('scope') ? $accessToken->getParameter()->get('scope') : null;
162
163
        if ($accessToken->getMetadata()->has('authorization_code_id') && null !== $this->authorizationCodeRepository) {
164
            $authorizationCodeId = new AuthorizationCodeId($accessToken->getMetadata()->get('authorization_code_id'));
165
            $authorizationCode = $this->authorizationCodeRepository->find($authorizationCodeId);
166
            if (null === $authorizationCode) {
167
                return;
168
            }
169
            $this->authorizationCodeId = $authorizationCodeId;
170
            $queryParams = $authorizationCode->getQueryParameters();
171
            foreach (['nonce' => 'nonce', 'claims_locales' => 'claimsLocales'] as $k => $v) {
172
                if (\array_key_exists($k, $queryParams)) {
173
                    $this->$v = $queryParams[$k];
174
                }
175
            }
176
            $this->withAuthenticationTime = \array_key_exists('max_age', $authorizationCode->getQueryParameters());
177
        }
178
    }
179
180
    public function withAccessTokenId(AccessTokenId $accessTokenId): void
181
    {
182
        $this->accessTokenId = $accessTokenId;
183
    }
184
185
    public function withAuthorizationCodeId(AuthorizationCodeId $authorizationCodeId): void
186
    {
187
        $this->authorizationCodeId = $authorizationCodeId;
188
    }
189
190
    public function withClaimsLocales(string $claimsLocales): void
191
    {
192
        $this->claimsLocales = $claimsLocales;
193
    }
194
195
    public function withAuthenticationTime(): void
196
    {
197
        $this->withAuthenticationTime = true;
198
    }
199
200
    public function withScope(string $scope): void
201
    {
202
        $this->scope = $scope;
203
    }
204
205
    public function withRequestedClaims(array $requestedClaims): void
206
    {
207
        $this->requestedClaims = $requestedClaims;
208
    }
209
210
    public function withNonce(string $nonce): void
211
    {
212
        $this->nonce = $nonce;
213
    }
214
215
    public function withExpirationAt(\DateTimeImmutable $expiresAt): void
216
    {
217
        $this->expiresAt = $expiresAt;
218
    }
219
220
    public function withoutAuthenticationTime(): void
221
    {
222
        $this->withAuthenticationTime = false;
223
    }
224
225
    public function withSignature(JWSBuilder $jwsBuilder, JWKSet $signatureKeys, string $signatureAlgorithm): void
226
    {
227
        if (!\in_array($signatureAlgorithm, $jwsBuilder->getSignatureAlgorithmManager()->list(), true)) {
228
            throw new \InvalidArgumentException(\Safe\sprintf('Unsupported signature algorithm "%s". Please use one of the following one: %s', $signatureAlgorithm, \implode(', ', $jwsBuilder->getSignatureAlgorithmManager()->list())));
229
        }
230
        if (0 === $signatureKeys->count()) {
231
            throw new \InvalidArgumentException('The signature key set must contain at least one key.');
232
        }
233
        $this->jwsBuilder = $jwsBuilder;
234
        $this->signatureKeys = $signatureKeys;
235
        $this->signatureAlgorithm = $signatureAlgorithm;
236
    }
237
238
    public function withEncryption(JWEBuilder $jweBuilder, string $keyEncryptionAlgorithm, string $contentEncryptionAlgorithm): void
239
    {
240
        if (!\in_array($keyEncryptionAlgorithm, $jweBuilder->getKeyEncryptionAlgorithmManager()->list(), true)) {
241
            throw new \InvalidArgumentException(\Safe\sprintf('Unsupported key encryption algorithm "%s". Please use one of the following one: %s', $keyEncryptionAlgorithm, \implode(', ', $jweBuilder->getKeyEncryptionAlgorithmManager()->list())));
242
        }
243
        if (!\in_array($contentEncryptionAlgorithm, $jweBuilder->getContentEncryptionAlgorithmManager()->list(), true)) {
244
            throw new \InvalidArgumentException(\Safe\sprintf('Unsupported content encryption algorithm "%s". Please use one of the following one: %s', $contentEncryptionAlgorithm, \implode(', ', $jweBuilder->getContentEncryptionAlgorithmManager()->list())));
245
        }
246
        $this->jweBuilder = $jweBuilder;
247
        $this->keyEncryptionAlgorithm = $keyEncryptionAlgorithm;
248
        $this->contentEncryptionAlgorithm = $contentEncryptionAlgorithm;
249
    }
250
251
    public function build(): string
252
    {
253
        if (null === $this->scope) {
254
            throw new \LogicException('It is mandatory to set the scope.');
255
        }
256
        $data = $this->userinfo->getUserinfo($this->client, $this->userAccount, $this->redirectUri, $this->requestedClaims, $this->scope, $this->claimsLocales);
257
        //$data = $this->updateClaimsWithAmrAndAcrInfo($data, $this->userAccount);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
258
        $data = $this->updateClaimsWithAuthenticationTime($data, $this->requestedClaims);
259
        $data = $this->updateClaimsWithNonce($data);
260
        if (null !== $this->signatureAlgorithm) {
261
            $data = $this->updateClaimsWithJwtClaims($data);
262
            $data = $this->updateClaimsWithTokenHash($data);
263
            $data = $this->updateClaimsAudience($data);
264
            $result = $this->computeIdToken($data);
265
        } else {
266
            $result = \Safe\json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
267
        }
268
269
        if (null !== $this->keyEncryptionAlgorithm && null !== $this->contentEncryptionAlgorithm) {
270
            $result = $this->tryToEncrypt($this->client, $result);
271
        }
272
273
        return $result;
274
    }
275
276
    private function updateClaimsWithJwtClaims(array $claims): array
277
    {
278
        if (null === $this->expiresAt) {
279
            $this->expiresAt = (new \DateTimeImmutable())->setTimestamp(\time() + $this->lifetime);
0 ignored issues
show
Documentation Bug introduced by
It seems like (new \DateTimeImmutable(...me() + $this->lifetime) can also be of type false. However, the property $expiresAt is declared as type object<DateTimeImmutable>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
280
        }
281
        $claims += [
282
            'iat' => \time(),
283
            'nbf' => \time(),
284
            'exp' => $this->expiresAt->getTimestamp(),
285
            'jti' => Base64Url::encode(\random_bytes(16)),
286
            'iss' => $this->issuer,
287
        ];
288
289
        return $claims;
290
    }
291
292
    private function updateClaimsWithAuthenticationTime(array $claims, array $requestedClaims): array
293
    {
294
        if ((true === $this->withAuthenticationTime || \array_key_exists('auth_time', $requestedClaims)) && null !== $this->userAccount->getLastLoginAt()) {
295
            $claims['auth_time'] = $this->userAccount->getLastLoginAt();
296
        }
297
298
        return $claims;
299
    }
300
301
    private function updateClaimsWithNonce(array $claims): array
302
    {
303
        if (null !== $this->nonce) {
304
            $claims['nonce'] = $this->nonce;
305
        }
306
307
        return $claims;
308
    }
309
310
    private function updateClaimsAudience(array $claims): array
311
    {
312
        $claims['aud'] = [
313
            $this->client->getPublicId()->getValue(),
314
            $this->issuer,
315
        ];
316
        $claims['azp'] = $this->client->getPublicId()->getValue();
317
318
        return $claims;
319
    }
320
321
    private function computeIdToken(array $claims): string
322
    {
323
        $signatureKey = $this->getSignatureKey($this->signatureAlgorithm);
324
        $header = $this->getHeaders($signatureKey, $this->signatureAlgorithm);
325
        $jsonConverter = new StandardConverter();
0 ignored issues
show
Deprecated Code introduced by
The class Jose\Component\Core\Converter\StandardConverter has been deprecated with message: This class is deprecated in v1.3 and will be removed in v2.0

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
326
        $claims = $jsonConverter->encode($claims);
327
        $jws = $this->jwsBuilder
328
            ->create()
329
            ->withPayload($claims)
330
            ->addSignature($signatureKey, $header)
331
            ->build();
332
        $serializer = new JwsCompactSerializer($jsonConverter);
333
334
        return $serializer->serialize($jws, 0);
335
    }
336
337
    private function tryToEncrypt(Client $client, string $jwt): string
338
    {
339
        $clientKeySet = $this->getClientKeySet($client);
340
        $keyEncryptionAlgorithm = $this->jweBuilder->getKeyEncryptionAlgorithmManager()->get($this->keyEncryptionAlgorithm);
341
        $encryptionKey = $clientKeySet->selectKey('enc', $keyEncryptionAlgorithm);
342
        if (null === $encryptionKey) {
343
            throw new \InvalidArgumentException('No encryption key available for the client.');
344
        }
345
        $header = [
346
            'typ' => 'JWT',
347
            'jti' => Base64Url::encode(\random_bytes(16)),
348
            'alg' => $this->keyEncryptionAlgorithm,
349
            'enc' => $this->contentEncryptionAlgorithm,
350
        ];
351
        $jwe = $this->jweBuilder
352
            ->create()
353
            ->withPayload($jwt)
354
            ->withSharedProtectedHeader($header)
355
            ->addRecipient($encryptionKey)
356
            ->build();
357
        $jsonConverter = new StandardConverter();
0 ignored issues
show
Deprecated Code introduced by
The class Jose\Component\Core\Converter\StandardConverter has been deprecated with message: This class is deprecated in v1.3 and will be removed in v2.0

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
358
        $serializer = new JweCompactSerializer($jsonConverter);
359
360
        return $serializer->serialize($jwe, 0);
361
    }
362
363
    private function getSignatureKey(string $signatureAlgorithm): JWK
364
    {
365
        $keys = $this->signatureKeys;
366
        if ($this->client->has('client_secret')) {
367
            $jwk = JWK::create([
368
                'kty' => 'oct',
369
                'use' => 'sig',
370
                'k' => Base64Url::encode($this->client->get('client_secret')),
371
            ]);
372
            $keys = $keys->with($jwk);
373
        }
374
        $signatureAlgorithm = $this->jwsBuilder->getSignatureAlgorithmManager()->get($signatureAlgorithm);
375
        if ('none' === $signatureAlgorithm->name()) {
376
            return JWK::create(['kty' => 'none', 'alg' => 'none', 'use' => 'sig']);
377
        }
378
        $signatureKey = $keys->selectKey('sig', $signatureAlgorithm);
379
        if (null === $signatureKey) {
380
            throw new \InvalidArgumentException('Unable to find a key to sign the ID Token. Please verify the selected key set contains suitable keys.');
381
        }
382
383
        return $signatureKey;
384
    }
385
386
    private function getHeaders(JWK $signatureKey, string $signatureAlgorithm): array
387
    {
388
        $header = [
389
            'typ' => 'JWT',
390
            'alg' => $signatureAlgorithm,
391
        ];
392
        if ($signatureKey->has('kid')) {
393
            $header['kid'] = $signatureKey->get('kid');
394
        }
395
396
        return $header;
397
    }
398
399
    private function updateClaimsWithTokenHash(array $claims): array
400
    {
401
        if ('none' === $this->signatureAlgorithm) {
402
            return $claims;
403
        }
404
        if (null !== $this->accessTokenId) {
405
            $claims['at_hash'] = $this->getHash($this->accessTokenId->getValue());
406
        }
407
        if (null !== $this->authorizationCodeId) {
408
            $claims['c_hash'] = $this->getHash($this->authorizationCodeId->getValue());
409
        }
410
411
        return $claims;
412
    }
413
414
    private function getHash(string $tokenId): string
415
    {
416
        return Base64Url::encode(\mb_substr(\hash($this->getHashMethod(), $tokenId, true), 0, $this->getHashSize(), '8bit'));
417
    }
418
419
    private function getHashMethod(): string
420
    {
421
        $map = [
422
            'HS256' => 'sha256',
423
            'ES256' => 'sha256',
424
            'RS256' => 'sha256',
425
            'PS256' => 'sha256',
426
            'HS384' => 'sha384',
427
            'ES384' => 'sha384',
428
            'RS384' => 'sha384',
429
            'PS384' => 'sha384',
430
            'HS512' => 'sha512',
431
            'ES512' => 'sha512',
432
            'RS512' => 'sha512',
433
            'PS512' => 'sha512',
434
        ];
435
436
        if (!\array_key_exists($this->signatureAlgorithm, $map)) {
437
            throw new \InvalidArgumentException(\Safe\sprintf('Algorithm "%s" is not supported', $this->signatureAlgorithm));
438
        }
439
440
        return $map[$this->signatureAlgorithm];
441
    }
442
443
    private function getHashSize(): int
444
    {
445
        $map = [
446
            'HS256' => 16,
447
            'ES256' => 16,
448
            'RS256' => 16,
449
            'PS256' => 16,
450
            'HS384' => 24,
451
            'ES384' => 24,
452
            'RS384' => 24,
453
            'PS384' => 24,
454
            'HS512' => 32,
455
            'ES512' => 32,
456
            'RS512' => 32,
457
            'PS512' => 32,
458
        ];
459
460
        if (!\array_key_exists($this->signatureAlgorithm, $map)) {
461
            throw new \InvalidArgumentException(\Safe\sprintf('Algorithm "%s" is not supported', $this->signatureAlgorithm));
462
        }
463
464
        return $map[$this->signatureAlgorithm];
465
    }
466
467
    private function getClientKeySet(Client $client): JWKSet
468
    {
469
        $keyset = JWKSet::createFromKeys([]);
470
        if ($client->has('jwks')) {
471
            $jwks = JWKSet::createFromJson($client->get('jwks'));
472
            foreach ($jwks as $jwk) {
473
                $keyset = $keyset->with($jwk);
474
            }
475
        }
476
        if ($client->has('client_secret')) {
477
            $jwk = JWK::create([
478
                'kty' => 'oct',
479
                'use' => 'enc',
480
                'k' => Base64Url::encode($client->get('client_secret')),
481
            ]);
482
            $keyset = $keyset->with($jwk);
483
        }
484
        if ($client->has('jwks_uri') && null !== $this->jkuFactory) {
485
            $jwksUri = $this->jkuFactory->loadFromUrl($client->get('jwks_uri'));
486
            foreach ($jwksUri as $jwk) {
487
                $keyset = $keyset->with($jwk);
488
            }
489
        }
490
491
        if (empty($keyset)) {
492
            throw new \InvalidArgumentException('The client has no key or key set.');
493
        }
494
495
        return $keyset;
496
    }
497
}
498