Failed Conditions
Pull Request — ng (#102)
by Florent
12:50 queued 09:11
created

ClientAssertionJwt::tryToDecryptClientAssertion()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 8.7624
c 0
b 0
f 0
cc 5
eloc 12
nc 10
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\ClientAuthentication;
15
16
use Base64Url\Base64Url;
17
use Jose\Component\Checker\ClaimCheckerManager;
18
use Jose\Component\Checker\HeaderCheckerManager;
19
use Jose\Component\Core\Converter\JsonConverter;
20
use Jose\Component\Core\JWK;
21
use Jose\Component\Core\JWKSet;
22
use Jose\Component\Encryption\JWELoader;
23
use Jose\Component\KeyManagement\JKUFactory;
24
use Jose\Component\Signature\JWS;
25
use Jose\Component\Signature\JWSVerifier;
26
use Jose\Component\Signature\Serializer\CompactSerializer;
27
use OAuth2Framework\Bundle\Tests\TestBundle\Entity\TrustedIssuerRepository;
28
use OAuth2Framework\Component\Core\Client\Client;
29
use OAuth2Framework\Component\Core\Client\ClientId;
30
use OAuth2Framework\Component\Core\DataBag\DataBag;
31
use OAuth2Framework\Component\Core\Exception\OAuth2Exception;
32
use Psr\Http\Message\ServerRequestInterface;
33
34
class ClientAssertionJwt implements AuthenticationMethod
35
{
36
    private const CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
37
38
    /**
39
     * @var JWSVerifier
40
     */
41
    private $jwsVerifier;
42
43
    /**
44
     * @var null|TrustedIssuerRepository
45
     */
46
    private $trustedIssuerRepository = null;
47
48
    /**
49
     * @var null|JKUFactory
50
     */
51
    private $jkuFactory = null;
52
53
    /**
54
     * @var null|JWELoader
55
     */
56
    private $jweLoader = null;
57
58
    /**
59
     * @var null|JWKSet
60
     */
61
    private $keyEncryptionKeySet = null;
62
63
    /**
64
     * @var bool
65
     */
66
    private $encryptionRequired = false;
67
68
    /**
69
     * @var int
70
     */
71
    private $secretLifetime;
72
73
    /**
74
     * @var HeaderCheckerManager
75
     */
76
    private $headerCheckerManager;
77
78
    /**
79
     * @var ClaimCheckerManager
80
     */
81
    private $claimCheckerManager;
82
83
    /**
84
     * @var JsonConverter
85
     */
86
    private $jsonConverter;
87
88
    /**
89
     * ClientAssertionJwt constructor.
90
     *
91
     * @param JsonConverter        $jsonConverter
92
     * @param JWSVerifier          $jwsVerifier
93
     * @param HeaderCheckerManager $headerCheckerManager
94
     * @param ClaimCheckerManager  $claimCheckerManager
95
     * @param int                  $secretLifetime
96
     */
97
    public function __construct(JsonConverter $jsonConverter, JWSVerifier $jwsVerifier, HeaderCheckerManager $headerCheckerManager, ClaimCheckerManager $claimCheckerManager, int $secretLifetime = 0)
98
    {
99
        if ($secretLifetime < 0) {
100
            throw new \InvalidArgumentException('The secret lifetime must be at least 0 (= unlimited).');
101
        }
102
        $this->jsonConverter = $jsonConverter;
103
        $this->jwsVerifier = $jwsVerifier;
104
        $this->headerCheckerManager = $headerCheckerManager;
105
        $this->claimCheckerManager = $claimCheckerManager;
106
        $this->secretLifetime = $secretLifetime;
107
    }
108
109
    /**
110
     * @param TrustedIssuerRepository $trustedIssuerRepository
111
     */
112
    public function enableTrustedIssuerSupport(TrustedIssuerRepository $trustedIssuerRepository)
113
    {
114
        $this->trustedIssuerRepository = $trustedIssuerRepository;
115
    }
116
117
    /**
118
     * @param JKUFactory $jkuFactory
119
     */
120
    public function enableJkuSupport(JKUFactory $jkuFactory)
121
    {
122
        $this->jkuFactory = $jkuFactory;
123
    }
124
125
    /**
126
     * @param JWELoader $jweLoader
127
     * @param JWKSet    $keyEncryptionKeySet
128
     * @param bool      $encryptionRequired
129
     */
130
    public function enableEncryptedAssertions(JWELoader $jweLoader, JWKSet $keyEncryptionKeySet, bool $encryptionRequired)
131
    {
132
        $this->jweLoader = $jweLoader;
133
        $this->encryptionRequired = $encryptionRequired;
134
        $this->keyEncryptionKeySet = $keyEncryptionKeySet;
135
    }
136
137
    /**
138
     * @return string[]
139
     */
140
    public function getSupportedSignatureAlgorithms(): array
141
    {
142
        return $this->jwsVerifier->getSignatureAlgorithmManager()->list();
143
    }
144
145
    /**
146
     * @return string[]
147
     */
148
    public function getSupportedContentEncryptionAlgorithms(): array
149
    {
150
        return null === $this->jweLoader ? [] : $this->jweLoader->getJweDecrypter()->getContentEncryptionAlgorithmManager()->list();
151
    }
152
153
    /**
154
     * @return string[]
155
     */
156
    public function getSupportedKeyEncryptionAlgorithms(): array
157
    {
158
        return null === $this->jweLoader ? [] : $this->jweLoader->getJweDecrypter()->getKeyEncryptionAlgorithmManager()->list();
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     */
164
    public function getSchemesParameters(): array
165
    {
166
        return [];
167
    }
168
169
    /**
170
     * {@inheritdoc}
171
     */
172
    public function findClientIdAndCredentials(ServerRequestInterface $request, &$clientCredentials = null): ? ClientId
173
    {
174
        $parameters = $request->getParsedBody() ?? [];
175
        if (!array_key_exists('client_assertion_type', $parameters)) {
176
            return null;
177
        }
178
        $clientAssertionType = $parameters['client_assertion_type'];
179
180
        if (self::CLIENT_ASSERTION_TYPE !== $clientAssertionType) {
181
            return null;
182
        }
183
184
        try {
185
            if (!array_key_exists('client_assertion', $parameters)) {
186
                throw new \InvalidArgumentException('Parameter "client_assertion" is missing.');
187
            }
188
            $client_assertion = $parameters['client_assertion'];
189
            $client_assertion = $this->tryToDecryptClientAssertion($client_assertion);
190
            $serializer = new CompactSerializer($this->jsonConverter);
191
            $jws = $serializer->unserialize($client_assertion);
192
            if (1 !== $jws->countSignatures()) {
193
                throw new \InvalidArgumentException('The assertion must have only one signature.');
194
            }
195
            $this->headerCheckerManager->check($jws, 0);
196
            $claims = $this->jsonConverter->decode($jws->getPayload());
197
            $this->claimCheckerManager->check($claims);
198
199
            // FIXME: Other claims can be considered as mandatory
200
            $diff = array_diff(['iss', 'sub', 'aud', 'exp'], array_keys($claims));
201
            if (!empty($diff)) {
202
                throw new \InvalidArgumentException(sprintf('The following claim(s) is/are mandatory: "%s".', implode(', ', array_values($diff))));
203
            }
204
205
            $clientCredentials = $jws;
206
207
            return ClientId::create($claims['sub']);
208
        } catch (\Exception $e) {
209
            throw new OAuth2Exception(400, OAuth2Exception::ERROR_INVALID_REQUEST, $e->getMessage(), $e);
210
        }
211
    }
212
213
    /**
214
     * @param string $assertion
215
     *
216
     * @return string
217
     *
218
     * @throws OAuth2Exception
219
     */
220
    private function tryToDecryptClientAssertion(string $assertion): string
221
    {
222
        if (null === $this->jweLoader) {
223
            return $assertion;
224
        }
225
226
        try {
227
            $jwe = $this->jweLoader->loadAndDecryptWithKeySet($assertion, $this->keyEncryptionKeySet, $recipient);
0 ignored issues
show
Bug introduced by
The variable $recipient does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
228
            if (1 !== $jwe->countRecipients()) {
229
                throw new \InvalidArgumentException('The client assertion must have only one recipient.');
230
            }
231
232
            return $jwe->getPayload();
233
        } catch (\Exception $e) {
234
            if (true === $this->encryptionRequired) {
235
                throw new OAuth2Exception(400, OAuth2Exception::ERROR_INVALID_REQUEST, $e->getMessage(), $e);
236
            }
237
238
            return $assertion;
239
        }
240
    }
241
242
    /**
243
     * {@inheritdoc}
244
     */
245
    public function isClientAuthenticated(Client $client, $clientCredentials, ServerRequestInterface $request): bool
246
    {
247
        try {
248
            if (!$clientCredentials instanceof JWS) {
0 ignored issues
show
Bug introduced by
The class Jose\Component\Signature\JWS does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
249
                return false;
250
            }
251
252
            $claims = $this->jsonConverter->decode($clientCredentials->getPayload());
253
            $jwkset = $this->retrieveIssuerKeySet($client, $clientCredentials, $claims);
254
255
            return $this->jwsVerifier->verifyWithKeySet($clientCredentials, $jwkset, 0);
256
        } catch (\Exception $e) {
257
            return false;
258
        }
259
    }
260
261
    /**
262
     * {@inheritdoc}
263
     */
264
    public function getSupportedMethods(): array
265
    {
266
        return ['client_secret_jwt', 'private_key_jwt'];
267
    }
268
269
    /**
270
     * {@inheritdoc}
271
     */
272
    public function checkClientConfiguration(DataBag $commandParameters, DataBag $validatedParameters): DataBag
273
    {
274
        if ('client_secret_jwt' === $commandParameters->get('token_endpoint_auth_method')) {
275
            $validatedParameters = $validatedParameters->with('client_secret', $this->createClientSecret());
276
            $validatedParameters = $validatedParameters->with('client_secret_expires_at', (0 === $this->secretLifetime ? 0 : time() + $this->secretLifetime));
277
        } elseif ('private_key_jwt' === $commandParameters->get('token_endpoint_auth_method')) {
278
            if (!($commandParameters->has('jwks') xor $commandParameters->has('jwks_uri'))) {
279
                throw new \InvalidArgumentException('The parameter "jwks" or "jwks_uri" must be set.');
280
            }
281
            if ($commandParameters->has('jwks')) {
282
                $jwks = JWKSet::createFromKeyData($commandParameters->get('jwks'));
283
                if (!$jwks instanceof JWKSet) {
0 ignored issues
show
Bug introduced by
The class Jose\Component\Core\JWKSet does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
284
                    throw new \InvalidArgumentException('The parameter "jwks" must be a valid JWKSet object.');
285
                }
286
                $validatedParameters = $validatedParameters->with('jwks', $commandParameters->get('jwks'));
287
            } else {
288
                $jwks = $this->jkuFactory->loadFromUrl($commandParameters->get('jwks_uri'));
289
                if (empty($jwks)) {
290
                    throw new \InvalidArgumentException('The parameter "jwks_uri" must be a valid uri to a JWK Set and at least one key.');
291
                }
292
                $validatedParameters = $validatedParameters->with('jwks_uri', $commandParameters->get('jwks_uri'));
293
            }
294
        } else {
295
            throw new \InvalidArgumentException('Unsupported token endpoint authentication method.');
296
        }
297
298
        return $validatedParameters;
299
    }
300
301
    /**
302
     * @return string
303
     */
304
    private function createClientSecret(): string
305
    {
306
        return bin2hex(random_bytes(128));
307
    }
308
309
    /**
310
     * @param Client $client
311
     * @param array  $claims
312
     *
313
     * @return JWKSet
314
     */
315
    private function retrieveIssuerKeySet(Client $client, JWS $jws, array $claims): JWKSet
316
    {
317
        if ($claims['sub'] === $claims['iss']) { // The client is the issuer
318
            return $this->getClientKeySet($client);
319
        }
320
321
        if (null === $this->trustedIssuerRepository || null === $trustedIssuer = $this->trustedIssuerRepository->find($claims['iss'])) {
322
            throw new \InvalidArgumentException('Unable to retrieve the key set of the issuer.');
323
        }
324
325
        if (!in_array(self::CLIENT_ASSERTION_TYPE, $trustedIssuer->getAllowedAssertionTypes())) {
326
            throw new \InvalidArgumentException(sprintf('The assertion type "%s" is not allowed for that issuer.', self::CLIENT_ASSERTION_TYPE));
327
        }
328
329
        $signatureAlgorithm = $jws->getSignature(0)->getProtectedHeaderParameter('alg');
330
        if (!in_array($signatureAlgorithm, $trustedIssuer->getAllowedSignatureAlgorithms())) {
331
            throw new \InvalidArgumentException(sprintf('The signature algorithm "%s" is not allowed for that issuer.', $signatureAlgorithm));
332
        }
333
334
        return $trustedIssuer->getJWKSet();
335
    }
336
337
    /**
338
     * @param Client $client
339
     *
340
     * @return JWKSet
341
     */
342
    private function getClientKeySet(Client $client): JWKSet
343
    {
344
        switch (true) {
345
            case $client->has('jwks'):
346
                return JWKSet::createFromJson($client->get('jwks'));
347
            case $client->has('client_secret') && in_array($client->getTokenEndpointAuthenticationMethod(), $this->getSupportedMethods()):
348
                $jwk = JWK::create([
349
                    'kty' => 'oct',
350
                    'use' => 'sig',
351
                    'k' => Base64Url::encode($client->get('client_secret')),
352
                ]);
353
354
                return JWKSet::createFromKeys([$jwk]);
355
            case $client->has('jwks_uri') && null !== $this->jkuFactory:
356
                return $this->jkuFactory->loadFromUrl($client->get('jwks_uri'));
357
            default:
358
                throw new \InvalidArgumentException('The client has no key or key set.');
359
        }
360
    }
361
}
362