• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

prince-chrismc / jwt-cpp / 22089023730

17 Feb 2026 07:00AM UTC coverage: 94.625% (+0.08%) from 94.549%
22089023730

Pull #38

github

web-flow
Merge 36bcaf55a into 971b897d7
Pull Request #38: replace hmac impl to use BIGNUM

36 of 37 new or added lines in 1 file covered. (97.3%)

35 existing lines in 1 file now uncovered.

1338 of 1414 relevant lines covered (94.63%)

258.18 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.0
/include/jwt-cpp/jwt.h
1
#ifndef JWT_CPP_JWT_H
2
#define JWT_CPP_JWT_H
3

4
#ifndef JWT_DISABLE_PICOJSON
5
#ifndef PICOJSON_USE_INT64
6
#define PICOJSON_USE_INT64
7
#endif
8
#include "picojson/picojson.h"
9
#endif
10

11
#ifndef JWT_DISABLE_BASE64
12
#include "base.h"
13
#endif
14

15
#include <openssl/ec.h>
16
#include <openssl/ecdsa.h>
17
#include <openssl/err.h>
18
#include <openssl/evp.h>
19
#include <openssl/hmac.h>
20
#include <openssl/pem.h>
21
#include <openssl/rsa.h>
22
#include <openssl/ssl.h>
23

24
#include <algorithm>
25
#include <chrono>
26
#include <climits>
27
#include <cmath>
28
#include <cstring>
29
#include <functional>
30
#include <iterator>
31
#include <locale>
32
#include <memory>
33
#include <set>
34
#include <system_error>
35
#include <type_traits>
36
#include <unordered_map>
37
#include <utility>
38
#include <vector>
39

40
#if __cplusplus >= 201402L
41
#ifdef __has_include
42
#if __has_include(<experimental/type_traits>)
43
#include <experimental/type_traits>
44
#endif
45
#endif
46
#endif
47

48
#if OPENSSL_VERSION_NUMBER >= 0x30000000L // 3.0.0
49
#define JWT_OPENSSL_3_0
50
#include <openssl/param_build.h>
51
#elif OPENSSL_VERSION_NUMBER >= 0x10101000L // 1.1.1
52
#define JWT_OPENSSL_1_1_1
53
#elif OPENSSL_VERSION_NUMBER >= 0x10100000L // 1.1.0
54
#define JWT_OPENSSL_1_1_0
55
#elif OPENSSL_VERSION_NUMBER >= 0x10000000L // 1.0.0
56
#define JWT_OPENSSL_1_0_0
57
#endif
58

59
#if defined(LIBRESSL_VERSION_NUMBER)
60
#if LIBRESSL_VERSION_NUMBER >= 0x3070100fL // 3.7.1 - EdDSA support
61
#define JWT_OPENSSL_1_1_1
62
#elif LIBRESSL_VERSION_NUMBER >= 0x3050300fL // 3.5.3
63
#define JWT_OPENSSL_1_1_0
64
#else
65
#define JWT_OPENSSL_1_0_0
66
#endif
67
#endif
68

69
#if defined(LIBWOLFSSL_VERSION_HEX)
70
#define JWT_OPENSSL_1_1_1
71
#endif
72

73
#ifndef JWT_CLAIM_EXPLICIT
74
#define JWT_CLAIM_EXPLICIT explicit
75
#endif
76

77
/**
78
 * \brief JSON Web Token.
79
 *
80
 * A namespace to contain everything related to handling JSON Web Tokens, JWT for short,
81
 * as a part of [RFC7519](https://tools.ietf.org/html/rfc7519), or alternatively for
82
 * JWS (JSON Web Signature) from [RFC7515](https://tools.ietf.org/html/rfc7515)
83
 */
84
namespace jwt {
85
        /**
86
         * Default system time point in UTC
87
         */
88
        using date = std::chrono::system_clock::time_point;
89

90
        /**
91
         * \brief Everything related to error codes issued by the library
92
         */
93
        namespace error {
94
                struct signature_verification_exception : public std::system_error {
95
                        using system_error::system_error;
96
                };
97
                struct signature_generation_exception : public std::system_error {
98
                        using system_error::system_error;
99
                };
100
                struct rsa_exception : public std::system_error {
101
                        using system_error::system_error;
102
                };
103
                struct ecdsa_exception : public std::system_error {
104
                        using system_error::system_error;
105
                };
106
                struct token_verification_exception : public std::system_error {
107
                        using system_error::system_error;
108
                };
109
                /**
110
                 * \brief Errors related to processing of RSA signatures
111
                 */
112
                enum class rsa_error {
113
                        ok = 0,
114
                        cert_load_failed = 10,
115
                        get_key_failed,
116
                        write_key_failed,
117
                        write_cert_failed,
118
                        convert_to_pem_failed,
119
                        load_key_bio_write,
120
                        load_key_bio_read,
121
                        create_mem_bio_failed,
122
                        no_key_provided,
123
                        set_rsa_failed,
124
                        create_context_failed
125
                };
126
                /**
127
                 * \brief Error category for RSA errors
128
                 */
129
                inline std::error_category& rsa_error_category() {
277✔
130
                        class rsa_error_cat : public std::error_category {
131
                        public:
132
                                const char* name() const noexcept override { return "rsa_error"; };
1✔
133
                                std::string message(int ev) const override {
71✔
134
                                        switch (static_cast<rsa_error>(ev)) {
71✔
135
                                        case rsa_error::ok: return "no error";
3✔
136
                                        case rsa_error::cert_load_failed: return "error loading cert into memory";
15✔
137
                                        case rsa_error::get_key_failed: return "error getting key from certificate";
9✔
138
                                        case rsa_error::write_key_failed: return "error writing key data in PEM format";
9✔
139
                                        case rsa_error::write_cert_failed: return "error writing cert data in PEM format";
9✔
140
                                        case rsa_error::convert_to_pem_failed: return "failed to convert key to pem";
21✔
141
                                        case rsa_error::load_key_bio_write: return "failed to load key: bio write failed";
24✔
142
                                        case rsa_error::load_key_bio_read: return "failed to load key: bio read failed";
18✔
143
                                        case rsa_error::create_mem_bio_failed: return "failed to create memory bio";
36✔
144
                                        case rsa_error::no_key_provided: return "at least one of public or private key need to be present";
9✔
145
                                        case rsa_error::set_rsa_failed: return "set modulus and exponent to RSA failed";
9✔
146
                                        case rsa_error::create_context_failed: return "failed to create context";
9✔
147
                                        default: return "unknown RSA error";
42✔
148
                                        }
149
                                }
150
                        };
151
                        static rsa_error_cat cat;
277✔
152
                        return cat;
277✔
153
                }
154
                /**
155
                 * \brief Converts JWT-CPP errors into generic STL error_codes
156
                 */
157
                inline std::error_code make_error_code(rsa_error e) { return {static_cast<int>(e), rsa_error_category()}; }
169✔
158
                /**
159
                 * \brief Errors related to processing of RSA signatures
160
                 */
161
                enum class ecdsa_error {
162
                        ok = 0,
163
                        load_key_bio_write = 10,
164
                        load_key_bio_read,
165
                        create_mem_bio_failed,
166
                        no_key_provided,
167
                        invalid_key_size,
168
                        invalid_key,
169
                        create_context_failed,
170
                        cert_load_failed,
171
                        get_key_failed,
172
                        write_key_failed,
173
                        write_cert_failed,
174
                        convert_to_pem_failed,
175
                        unknown_curve,
176
                        set_ecdsa_failed
177
                };
178
                /**
179
                 * \brief Error category for ECDSA errors
180
                 */
181
                inline std::error_category& ecdsa_error_category() {
207✔
182
                        class ecdsa_error_cat : public std::error_category {
183
                        public:
184
                                const char* name() const noexcept override { return "ecdsa_error"; };
1✔
185
                                std::string message(int ev) const override {
90✔
186
                                        switch (static_cast<ecdsa_error>(ev)) {
90✔
187
                                        case ecdsa_error::ok: return "no error";
3✔
188
                                        case ecdsa_error::load_key_bio_write: return "failed to load key: bio write failed";
18✔
189
                                        case ecdsa_error::load_key_bio_read: return "failed to load key: bio read failed";
18✔
190
                                        case ecdsa_error::create_mem_bio_failed: return "failed to create memory bio";
21✔
191
                                        case ecdsa_error::no_key_provided:
3✔
192
                                                return "at least one of public or private key need to be present";
6✔
193
                                        case ecdsa_error::invalid_key_size: return "invalid key size";
75✔
194
                                        case ecdsa_error::invalid_key: return "invalid key";
9✔
195
                                        case ecdsa_error::create_context_failed: return "failed to create context";
15✔
196
                                        case ecdsa_error::cert_load_failed: return "error loading cert into memory";
12✔
197
                                        case ecdsa_error::get_key_failed: return "error getting key from certificate";
6✔
198
                                        case ecdsa_error::write_key_failed: return "error writing key data in PEM format";
6✔
199
                                        case ecdsa_error::write_cert_failed: return "error writing cert data in PEM format";
3✔
200
                                        case ecdsa_error::convert_to_pem_failed: return "failed to convert key to pem";
9✔
201
                                        case ecdsa_error::unknown_curve: return "unknown curve";
3✔
202
                                        case ecdsa_error::set_ecdsa_failed: return "set parameters to ECDSA failed";
12✔
203
                                        default: return "unknown ECDSA error";
51✔
204
                                        }
205
                                }
206
                        };
207
                        static ecdsa_error_cat cat;
207✔
208
                        return cat;
207✔
209
                }
210
                /**
211
                 * \brief Converts JWT-CPP errors into generic STL error_codes
212
                 */
213
                inline std::error_code make_error_code(ecdsa_error e) { return {static_cast<int>(e), ecdsa_error_category()}; }
142✔
214

215
                /**
216
                 * \brief Errors related to verification of signatures
217
                 */
218
                enum class signature_verification_error {
219
                        ok = 0,
220
                        invalid_signature = 10,
221
                        create_context_failed,
222
                        verifyinit_failed,
223
                        verifyupdate_failed,
224
                        verifyfinal_failed,
225
                        get_key_failed,
226
                        set_rsa_pss_saltlen_failed,
227
                        signature_encoding_failed
228
                };
229
                /**
230
                 * \brief Error category for verification errors
231
                 */
232
                inline std::error_category& signature_verification_error_category() {
112✔
233
                        class verification_error_cat : public std::error_category {
234
                        public:
235
                                const char* name() const noexcept override { return "signature_verification_error"; };
1✔
236
                                std::string message(int ev) const override {
37✔
237
                                        switch (static_cast<signature_verification_error>(ev)) {
37✔
238
                                        case signature_verification_error::ok: return "no error";
3✔
239
                                        case signature_verification_error::invalid_signature: return "invalid signature";
33✔
240
                                        case signature_verification_error::create_context_failed:
1✔
241
                                                return "failed to verify signature: could not create context";
2✔
242
                                        case signature_verification_error::verifyinit_failed:
1✔
243
                                                return "failed to verify signature: VerifyInit failed";
2✔
244
                                        case signature_verification_error::verifyupdate_failed:
1✔
245
                                                return "failed to verify signature: VerifyUpdate failed";
2✔
246
                                        case signature_verification_error::verifyfinal_failed:
8✔
247
                                                return "failed to verify signature: VerifyFinal failed";
16✔
248
                                        case signature_verification_error::get_key_failed:
1✔
249
                                                return "failed to verify signature: Could not get key";
2✔
250
                                        case signature_verification_error::set_rsa_pss_saltlen_failed:
1✔
251
                                                return "failed to verify signature: EVP_PKEY_CTX_set_rsa_pss_saltlen failed";
2✔
252
                                        case signature_verification_error::signature_encoding_failed:
1✔
253
                                                return "failed to verify signature: i2d_ECDSA_SIG failed";
2✔
254
                                        default: return "unknown signature verification error";
33✔
255
                                        }
256
                                }
257
                        };
258
                        static verification_error_cat cat;
112✔
259
                        return cat;
112✔
260
                }
261
                /**
262
                 * \brief Converts JWT-CPP errors into generic STL error_codes
263
                 */
264
                inline std::error_code make_error_code(signature_verification_error e) {
74✔
265
                        return {static_cast<int>(e), signature_verification_error_category()};
74✔
266
                }
267

268
                /**
269
                 * \brief Errors related to signature generation errors
270
                 */
271
                enum class signature_generation_error {
272
                        ok = 0,
273
                        hmac_failed = 10,
274
                        create_context_failed,
275
                        signinit_failed,
276
                        signupdate_failed,
277
                        signfinal_failed,
278
                        ecdsa_do_sign_failed,
279
                        digestinit_failed,
280
                        digestupdate_failed,
281
                        digestfinal_failed,
282
                        rsa_padding_failed,
283
                        rsa_private_encrypt_failed,
284
                        get_key_failed,
285
                        set_rsa_pss_saltlen_failed,
286
                        signature_decoding_failed
287
                };
288
                /**
289
                 * \brief Error category for signature generation errors
290
                 */
291
                inline std::error_category& signature_generation_error_category() {
94✔
292
                        class signature_generation_error_cat : public std::error_category {
293
                        public:
294
                                const char* name() const noexcept override { return "signature_generation_error"; };
1✔
295
                                std::string message(int ev) const override {
36✔
296
                                        switch (static_cast<signature_generation_error>(ev)) {
36✔
297
                                        case signature_generation_error::ok: return "no error";
3✔
298
                                        case signature_generation_error::hmac_failed: return "hmac failed";
3✔
299
                                        case signature_generation_error::create_context_failed:
1✔
300
                                                return "failed to create signature: could not create context";
2✔
301
                                        case signature_generation_error::signinit_failed:
1✔
302
                                                return "failed to create signature: SignInit failed";
2✔
303
                                        case signature_generation_error::signupdate_failed:
1✔
304
                                                return "failed to create signature: SignUpdate failed";
2✔
305
                                        case signature_generation_error::signfinal_failed:
5✔
306
                                                return "failed to create signature: SignFinal failed";
10✔
307
                                        case signature_generation_error::ecdsa_do_sign_failed: return "failed to generate ecdsa signature";
3✔
308
                                        case signature_generation_error::digestinit_failed:
1✔
309
                                                return "failed to create signature: DigestInit failed";
2✔
310
                                        case signature_generation_error::digestupdate_failed:
1✔
311
                                                return "failed to create signature: DigestUpdate failed";
2✔
312
                                        case signature_generation_error::digestfinal_failed:
1✔
313
                                                return "failed to create signature: DigestFinal failed";
2✔
314
                                        case signature_generation_error::rsa_padding_failed:
1✔
315
                                                return "failed to create signature: EVP_PKEY_CTX_set_rsa_padding failed";
2✔
316
                                        case signature_generation_error::rsa_private_encrypt_failed:
1✔
317
                                                return "failed to create signature: RSA_private_encrypt failed";
2✔
318
                                        case signature_generation_error::get_key_failed:
1✔
319
                                                return "failed to generate signature: Could not get key";
2✔
320
                                        case signature_generation_error::set_rsa_pss_saltlen_failed:
1✔
321
                                                return "failed to create signature: EVP_PKEY_CTX_set_rsa_pss_saltlen failed";
2✔
322
                                        case signature_generation_error::signature_decoding_failed:
1✔
323
                                                return "failed to create signature: d2i_ECDSA_SIG failed";
2✔
324
                                        default: return "unknown signature generation error";
51✔
325
                                        }
326
                                }
327
                        };
328
                        static signature_generation_error_cat cat = {};
94✔
329
                        return cat;
94✔
330
                }
331
                /**
332
                 * \brief Converts JWT-CPP errors into generic STL error_codes
333
                 */
334
                inline std::error_code make_error_code(signature_generation_error e) {
73✔
335
                        return {static_cast<int>(e), signature_generation_error_category()};
73✔
336
                }
337

338
                /**
339
                 * \brief Errors related to token verification errors
340
                 */
341
                enum class token_verification_error {
342
                        ok = 0,
343
                        wrong_algorithm = 10,
344
                        missing_claim,
345
                        claim_type_missmatch,
346
                        claim_value_missmatch,
347
                        token_expired,
348
                        audience_missmatch
349
                };
350
                /**
351
                 * \brief Error category for token verification errors
352
                 */
353
                inline std::error_category& token_verification_error_category() {
65✔
354
                        class token_verification_error_cat : public std::error_category {
355
                        public:
356
                                const char* name() const noexcept override { return "token_verification_error"; };
1✔
357
                                std::string message(int ev) const override {
33✔
358
                                        switch (static_cast<token_verification_error>(ev)) {
33✔
359
                                        case token_verification_error::ok: return "no error";
3✔
360
                                        case token_verification_error::wrong_algorithm: return "wrong algorithm";
6✔
361
                                        case token_verification_error::missing_claim: return "decoded JWT is missing required claim(s)";
15✔
362
                                        case token_verification_error::claim_type_missmatch:
2✔
363
                                                return "claim type does not match expected type";
4✔
364
                                        case token_verification_error::claim_value_missmatch:
3✔
365
                                                return "claim value does not match expected value";
6✔
366
                                        case token_verification_error::token_expired: return "token expired";
24✔
367
                                        case token_verification_error::audience_missmatch:
3✔
368
                                                return "token doesn't contain the required audience";
6✔
369
                                        default: return "unknown token verification error";
27✔
370
                                        }
371
                                }
372
                        };
373
                        static token_verification_error_cat cat = {};
65✔
374
                        return cat;
65✔
375
                }
376
                /**
377
                 * \brief Converts JWT-CPP errors into generic STL error_codes
378
                 */
379
                inline std::error_code make_error_code(token_verification_error e) {
41✔
380
                        return {static_cast<int>(e), token_verification_error_category()};
41✔
381
                }
382
                /**
383
                 * \brief Raises an exception if any JWT-CPP error codes are active
384
                 */
385
                inline void throw_if_error(std::error_code ec) {
360✔
386
                        if (ec) {
360✔
387
                                if (ec.category() == rsa_error_category()) throw rsa_exception(ec);
108✔
388
                                if (ec.category() == ecdsa_error_category()) throw ecdsa_exception(ec);
65✔
389
                                if (ec.category() == signature_verification_error_category())
38✔
390
                                        throw signature_verification_exception(ec);
17✔
391
                                if (ec.category() == signature_generation_error_category()) throw signature_generation_exception(ec);
21✔
392
                                if (ec.category() == token_verification_error_category()) throw token_verification_exception(ec);
17✔
393
                        }
394
                }
252✔
395
        } // namespace error
396
} // namespace jwt
397

398
namespace std {
399
        template<>
400
        struct is_error_code_enum<jwt::error::rsa_error> : true_type {};
401
        template<>
402
        struct is_error_code_enum<jwt::error::ecdsa_error> : true_type {};
403
        template<>
404
        struct is_error_code_enum<jwt::error::signature_verification_error> : true_type {};
405
        template<>
406
        struct is_error_code_enum<jwt::error::signature_generation_error> : true_type {};
407
        template<>
408
        struct is_error_code_enum<jwt::error::token_verification_error> : true_type {};
409
} // namespace std
410

411
namespace jwt {
412
        /**
413
         * \brief A collection for working with certificates
414
         *
415
         * These _helpers_ are usefully when working with certificates OpenSSL APIs.
416
         * For example, when dealing with JWKS (JSON Web Key Set)[https://tools.ietf.org/html/rfc7517]
417
         * you maybe need to extract the modulus and exponent of an RSA Public Key.
418
         */
419
        namespace helper {
420
                /**
421
                 * \brief Handle class for EVP_PKEY structures
422
                 *
423
                 * Starting from OpenSSL 1.1.0, EVP_PKEY has internal reference counting. This handle class allows
424
                 * jwt-cpp to leverage that and thus safe an allocation for the control block in std::shared_ptr.
425
                 * The handle uses shared_ptr as a fallback on older versions. The behaviour should be identical between both.
426
                 */
427
                class evp_pkey_handle {
428
                public:
429
                        /**
430
                         * \brief Creates a null key pointer.
431
                         */
432
                        constexpr evp_pkey_handle() noexcept = default;
160✔
433
#ifdef JWT_OPENSSL_1_0_0
434
                        /**
435
                         * \brief Construct a new handle. The handle takes ownership of the key.
436
                         * \param key The key to store
437
                         */
438
                        explicit evp_pkey_handle(EVP_PKEY* key) { m_key = std::shared_ptr<EVP_PKEY>(key, EVP_PKEY_free); }
439

440
                        EVP_PKEY* get() const noexcept { return m_key.get(); }
441
                        bool operator!() const noexcept { return m_key == nullptr; }
442
                        explicit operator bool() const noexcept { return m_key != nullptr; }
443

444
                private:
445
                        std::shared_ptr<EVP_PKEY> m_key{nullptr};
446
#else
447
                        /**
448
                         * \brief Construct a new handle. The handle takes ownership of the key.
449
                         * \param key The key to store
450
                         */
451
                        explicit constexpr evp_pkey_handle(EVP_PKEY* key) noexcept : m_key{key} {}
129✔
452
                        evp_pkey_handle(const evp_pkey_handle& other) : m_key{other.m_key} {
74✔
453
                                if (m_key != nullptr && EVP_PKEY_up_ref(m_key) != 1) throw std::runtime_error("EVP_PKEY_up_ref failed");
74✔
454
                        }
74✔
455
// C++11 requires the body of a constexpr constructor to be empty
456
#if __cplusplus >= 201402L
457
                        constexpr
458
#endif
459
                                evp_pkey_handle(evp_pkey_handle&& other) noexcept
121✔
460
                                : m_key{other.m_key} {
121✔
461
                                other.m_key = nullptr;
121✔
462
                        }
121✔
463
                        evp_pkey_handle& operator=(const evp_pkey_handle& other) {
464
                                if (&other == this) return *this;
465
                                decrement_ref_count(m_key);
466
                                m_key = other.m_key;
467
                                increment_ref_count(m_key);
468
                                return *this;
469
                        }
470
                        evp_pkey_handle& operator=(evp_pkey_handle&& other) noexcept {
91✔
471
                                if (&other == this) return *this;
91✔
472
                                decrement_ref_count(m_key);
91✔
473
                                m_key = other.m_key;
91✔
474
                                other.m_key = nullptr;
91✔
475
                                return *this;
91✔
476
                        }
477
                        evp_pkey_handle& operator=(EVP_PKEY* key) {
478
                                decrement_ref_count(m_key);
479
                                m_key = key;
480
                                increment_ref_count(m_key);
481
                                return *this;
482
                        }
483
                        ~evp_pkey_handle() noexcept { decrement_ref_count(m_key); }
484✔
484

485
                        EVP_PKEY* get() const noexcept { return m_key; }
215✔
486
                        bool operator!() const noexcept { return m_key == nullptr; }
181✔
487
                        explicit operator bool() const noexcept { return m_key != nullptr; }
5✔
488

489
                private:
490
                        EVP_PKEY* m_key{nullptr};
491

492
                        static void increment_ref_count(EVP_PKEY* key) {
493
                                if (key != nullptr && EVP_PKEY_up_ref(key) != 1) throw std::runtime_error("EVP_PKEY_up_ref failed");
494
                        }
495
                        static void decrement_ref_count(EVP_PKEY* key) noexcept {
575✔
496
                                if (key != nullptr) EVP_PKEY_free(key);
575✔
497
                        }
575✔
498
#endif
499
                };
500

501
                /**
502
                 * \brief Handle class for BIGNUM structures
503
                 *
504
                 * This handle class wraps OpenSSL's BIGNUM type and manages its lifecycle.
505
                 * It provides copy semantics (via BN_dup) and move semantics for efficient
506
                 * passing between containers.
507
                 */
508
                class bn_handle {
509
                public:
510
                        /**
511
                         * \brief Creates a new BIGNUM initialized to zero.
512
                         * \throws std::runtime_error if BIGNUM allocation fails
513
                         */
514
                        bn_handle() {
11✔
515
                                m_bn = BN_new();
11✔
516
                                if (m_bn == nullptr) throw std::runtime_error("BN_new failed");
11✔
517
                        }
11✔
518

519
                        /**
520
                         * \brief Construct a handle from a pointer. The handle takes ownership.
521
                         * \param bn The BIGNUM to store. Performs BN_dup() to create an independent copy.
522
                         * \throws std::runtime_error if BIGNUM duplication fails
523
                         */
524
                        explicit bn_handle(const BIGNUM* bn) {
138✔
525
                                if (bn == nullptr) throw std::runtime_error("BIGNUM pointer is null");
138✔
526
                                m_bn = BN_dup(bn);
137✔
527
                                if (m_bn == nullptr) throw std::runtime_error("BN_dup failed");
137✔
528
                        }
137✔
529

530
                        /**
531
                         * \brief Copy constructor. Creates an independent copy of the BIGNUM.
532
                         * \throws std::runtime_error if BIGNUM duplication fails
533
                         */
534
                        bn_handle(const bn_handle& other) {
52✔
535
                                if (other.m_bn == nullptr) throw std::runtime_error("BIGNUM is null");
52✔
536
                                m_bn = BN_dup(other.m_bn);
52✔
537
                                if (m_bn == nullptr) throw std::runtime_error("BN_dup failed");
52✔
538
                        }
52✔
539

540
                        /**
541
                         * \brief Move constructor. Steals ownership from other.
542
                         */
543
                        bn_handle(bn_handle&& other) noexcept : m_bn{other.m_bn} { other.m_bn = nullptr; }
4✔
544

545
                        /**
546
                         * \brief Destructor. Frees the BIGNUM.
547
                         */
548
                        ~bn_handle() noexcept {
204✔
549
                                if (m_bn != nullptr) BN_free(m_bn);
204✔
550
                        }
204✔
551

552
                        /**
553
                         * \brief Copy assignment. Deleted to maintain immutability.
554
                         */
555
                        bn_handle& operator=(const bn_handle&) = delete;
556

557
                        /**
558
                         * \brief Move assignment. Deleted to maintain immutability.
559
                         */
560
                        bn_handle& operator=(bn_handle&&) = delete;
561

562
                        /**
563
                         * \brief Get the underlying BIGNUM pointer.
564
                         */
565
                        BIGNUM* get() const noexcept { return m_bn; }
160✔
566

567
                        /**
568
                         * \brief Take ownership of the underlying BIGNUM pointer.
569
                         */
570
                        BIGNUM* release() noexcept {
45✔
571
                                BIGNUM* temp = m_bn;
45✔
572
                                m_bn = nullptr;
45✔
573
                                return temp;
45✔
574
                        }
575

576
                        /**
577
                         * \brief Check if the handle is null.
578
                         */
579
                        bool operator!() const noexcept { return m_bn == nullptr; }
3✔
580

581
                        /**
582
                         * \brief Check if the handle is non-null.
583
                         */
584
                        explicit operator bool() const noexcept { return m_bn != nullptr; }
1✔
585

586
                private:
587
                        BIGNUM* m_bn{nullptr};
588
                };
589

590
                inline std::unique_ptr<BIO, decltype(&BIO_free_all)> make_mem_buf_bio() {
212✔
591
                        return std::unique_ptr<BIO, decltype(&BIO_free_all)>(BIO_new(BIO_s_mem()), BIO_free_all);
212✔
592
                }
593

594
                inline std::unique_ptr<BIO, decltype(&BIO_free_all)> make_mem_buf_bio(const std::string& data) {
33✔
595
                        return std::unique_ptr<BIO, decltype(&BIO_free_all)>(
596
#if OPENSSL_VERSION_NUMBER <= 0x10100003L
597
                                BIO_new_mem_buf(const_cast<char*>(data.data()), static_cast<int>(data.size())), BIO_free_all
598
#else
599
                                BIO_new_mem_buf(data.data(), static_cast<int>(data.size())), BIO_free_all
66✔
600
#endif
601
                        );
66✔
602
                }
603

604
                template<typename error_category = error::rsa_error>
605
                std::string write_bio_to_string(std::unique_ptr<BIO, decltype(&BIO_free_all)>& bio_out, std::error_code& ec) {
30✔
606
                        char* ptr = nullptr;
30✔
607
                        auto len = BIO_get_mem_data(bio_out.get(), &ptr);
30✔
608
                        if (len <= 0 || ptr == nullptr) {
30✔
609
                                ec = error_category::convert_to_pem_failed;
13✔
610
                                return {};
13✔
611
                        }
612
                        return {ptr, static_cast<size_t>(len)};
51✔
613
                }
614

615
                inline std::unique_ptr<EVP_MD_CTX, void (*)(EVP_MD_CTX*)> make_evp_md_ctx() {
94✔
616
                        return
617
#ifdef JWT_OPENSSL_1_0_0
618
                                std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)>(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy);
619
#else
620
                                std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
94✔
621
#endif
622
                }
623

624
                /**
625
                 * \brief Extract the public key of a pem certificate
626
                 *
627
                 * \tparam error_category        jwt::error enum category to match with the keys being used
628
                 * \param certstr                        String containing the certificate encoded as pem
629
                 * \param pw                                Password used to decrypt certificate (leave empty if not encrypted)
630
                 * \param ec                                error_code for error_detection (gets cleared if no error occurred)
631
                 */
632
                template<typename error_category = error::rsa_error>
633
                std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw, std::error_code& ec) {
33✔
634
                        ec.clear();
33✔
635
                        auto certbio = make_mem_buf_bio(certstr);
33✔
636
                        auto keybio = make_mem_buf_bio();
33✔
637
                        if (!certbio || !keybio) {
33✔
638
                                ec = error_category::create_mem_bio_failed;
4✔
639
                                return {};
4✔
640
                        }
641

642
                        std::unique_ptr<X509, decltype(&X509_free)> cert(
29✔
643
                                PEM_read_bio_X509(certbio.get(), nullptr, nullptr, const_cast<char*>(pw.c_str())), X509_free);
29✔
644
                        if (!cert) {
29✔
645
                                ec = error_category::cert_load_failed;
4✔
646
                                return {};
4✔
647
                        }
648
                        std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> key(X509_get_pubkey(cert.get()), EVP_PKEY_free);
25✔
649
                        if (!key) {
25✔
650
                                ec = error_category::get_key_failed;
4✔
651
                                return {};
4✔
652
                        }
653
                        if (PEM_write_bio_PUBKEY(keybio.get(), key.get()) == 0) {
21✔
654
                                ec = error_category::write_key_failed;
4✔
655
                                return {};
4✔
656
                        }
657

658
                        return write_bio_to_string<error_category>(keybio, ec);
17✔
659
                }
33✔
660

661
                /**
662
                 * \brief Extract the public key of a pem certificate
663
                 *
664
                 * \tparam error_category        jwt::error enum category to match with the keys being used
665
                 * \param certstr                        String containing the certificate encoded as pem
666
                 * \param pw                                Password used to decrypt certificate (leave empty if not encrypted)
667
                 * \throw                                        templated error_category's type exception if an error occurred
668
                 */
669
                template<typename error_category = error::rsa_error>
670
                std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw = "") {
6✔
671
                        std::error_code ec;
6✔
672
                        auto res = extract_pubkey_from_cert<error_category>(certstr, pw, ec);
6✔
673
                        error::throw_if_error(ec);
6✔
674
                        return res;
2✔
675
                }
5✔
676

677
                /**
678
                 * \brief Convert the certificate provided as DER to PEM.
679
                 *
680
                 * \param cert_der_str         String containing the certificate encoded as base64 DER
681
                 * \param ec                        error_code for error_detection (gets cleared if no error occurs)
682
                 */
683
                inline std::string convert_der_to_pem(const std::string& cert_der_str, std::error_code& ec) {
13✔
684
                        ec.clear();
13✔
685

686
                        auto c_str = reinterpret_cast<const unsigned char*>(cert_der_str.c_str());
13✔
687

688
                        std::unique_ptr<X509, decltype(&X509_free)> cert(
689
                                d2i_X509(NULL, &c_str, static_cast<int>(cert_der_str.size())), X509_free);
13✔
690
                        auto certbio = make_mem_buf_bio();
13✔
691
                        if (!cert || !certbio) {
13✔
692
                                ec = error::rsa_error::create_mem_bio_failed;
3✔
693
                                return {};
3✔
694
                        }
695

696
                        if (!PEM_write_bio_X509(certbio.get(), cert.get())) {
10✔
697
                                ec = error::rsa_error::write_cert_failed;
3✔
698
                                return {};
3✔
699
                        }
700

701
                        return write_bio_to_string(certbio, ec);
7✔
702
                }
13✔
703

704
                /**
705
                 * \brief Convert the certificate provided as base64 DER to PEM.
706
                 *
707
                 * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
708
                 * [here](https://tools.ietf.org/html/rfc7517#section-4.7).
709
                 *
710
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
711
                 * It should ensure the padding of the input and then base64 decode and return
712
                 * the results.
713
                 *
714
                 * \param cert_base64_der_str         String containing the certificate encoded as base64 DER
715
                 * \param decode                                 The function to decode the cert
716
                 * \param ec                                        error_code for error_detection (gets cleared if no error occurs)
717
                 */
718
                template<typename Decode>
719
                std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode,
12✔
720
                                                                                          std::error_code& ec) {
721
                        ec.clear();
12✔
722
                        const auto decoded_str = decode(cert_base64_der_str);
12✔
723
                        return convert_der_to_pem(decoded_str, ec);
24✔
724
                }
12✔
725

726
                /**
727
                 * \brief Convert the certificate provided as base64 DER to PEM.
728
                 *
729
                 * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
730
                 * [here](https://tools.ietf.org/html/rfc7517#section-4.7)
731
                 *
732
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
733
                 * It should ensure the padding of the input and then base64 decode and return
734
                 * the results.
735
                 *
736
                 * \param cert_base64_der_str         String containing the certificate encoded as base64 DER
737
                 * \param decode                                 The function to decode the cert
738
                 * \throw                                                rsa_exception if an error occurred
739
                 */
740
                template<typename Decode>
741
                std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode) {
742
                        std::error_code ec;
743
                        auto res = convert_base64_der_to_pem(cert_base64_der_str, std::move(decode), ec);
744
                        error::throw_if_error(ec);
745
                        return res;
746
                }
747

748
                /**
749
                 * \brief Convert the certificate provided as DER to PEM.
750
                 *
751
                 * \param cert_der_str         String containing the DER certificate
752
                 * \throw                                rsa_exception if an error occurred
753
                 */
754
                inline std::string convert_der_to_pem(const std::string& cert_der_str) {
1✔
755
                        std::error_code ec;
1✔
756
                        auto res = convert_der_to_pem(cert_der_str, ec);
1✔
757
                        error::throw_if_error(ec);
1✔
758
                        return res;
2✔
UNCOV
759
                }
×
760

761
#ifndef JWT_DISABLE_BASE64
762
                /**
763
                 * \brief Convert the certificate provided as base64 DER to PEM.
764
                 *
765
                 * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
766
                 * [here](https://tools.ietf.org/html/rfc7517#section-4.7)
767
                 *
768
                 * \param cert_base64_der_str         String containing the certificate encoded as base64 DER
769
                 * \param ec                                        error_code for error_detection (gets cleared if no error occurs)
770
                 */
771
                inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, std::error_code& ec) {
12✔
772
                        auto decode = [](const std::string& token) {
12✔
773
                                return base::decode<alphabet::base64>(base::pad<alphabet::base64>(token));
12✔
774
                        };
775
                        return convert_base64_der_to_pem(cert_base64_der_str, std::move(decode), ec);
24✔
776
                }
777

778
                /**
779
                 * \brief Convert the certificate provided as base64 DER to PEM.
780
                 *
781
                 * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
782
                 * [here](https://tools.ietf.org/html/rfc7517#section-4.7)
783
                 *
784
                 * \param cert_base64_der_str         String containing the certificate encoded as base64 DER
785
                 * \throw                                                rsa_exception if an error occurred
786
                 */
787
                inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str) {
7✔
788
                        std::error_code ec;
7✔
789
                        auto res = convert_base64_der_to_pem(cert_base64_der_str, ec);
7✔
790
                        error::throw_if_error(ec);
7✔
791
                        return res;
2✔
792
                }
6✔
793
#endif
794
                /**
795
                 * \brief Load a public key from a string.
796
                 *
797
                 * The string should contain a pem encoded certificate or public key
798
                 *
799
                 * \tparam error_category        jwt::error enum category to match with the keys being used
800
                 * \param key                String containing the certificate encoded as pem
801
                 * \param password        Password used to decrypt certificate (leave empty if not encrypted)
802
                 * \param ec                error_code for error_detection (gets cleared if no error occurs)
803
                 */
804
                template<typename error_category = error::rsa_error>
805
                evp_pkey_handle load_public_key_from_string(const std::string& key, const std::string& password,
83✔
806
                                                                                                        std::error_code& ec) {
807
                        ec.clear();
83✔
808
                        auto pubkey_bio = make_mem_buf_bio();
83✔
809
                        if (!pubkey_bio) {
83✔
810
                                ec = error_category::create_mem_bio_failed;
8✔
811
                                return {};
8✔
812
                        }
813
                        if (key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") {
75✔
814
                                auto epkey = helper::extract_pubkey_from_cert<error_category>(key, password, ec);
21✔
815
                                if (ec) return {};
21✔
816
                                // Ensure the size fits into an int before casting
817
                                if (epkey.size() > static_cast<std::size_t>((std::numeric_limits<int>::max)())) {
9✔
UNCOV
818
                                        ec = error_category::load_key_bio_write; // Add an appropriate error here
×
UNCOV
819
                                        return {};
×
820
                                }
821
                                int len = static_cast<int>(epkey.size());
9✔
822
                                if (BIO_write(pubkey_bio.get(), epkey.data(), len) != len) {
9✔
823
                                        ec = error_category::load_key_bio_write;
4✔
824
                                        return {};
4✔
825
                                }
826
                        } else {
21✔
827
                                // Ensure the size fits into an int before casting
828
                                if (key.size() > static_cast<std::size_t>((std::numeric_limits<int>::max)())) {
54✔
UNCOV
829
                                        ec = error_category::load_key_bio_write; // Add an appropriate error here
×
UNCOV
830
                                        return {};
×
831
                                }
832
                                int len = static_cast<int>(key.size());
54✔
833
                                if (BIO_write(pubkey_bio.get(), key.data(), len) != len) {
54✔
834
                                        ec = error_category::load_key_bio_write;
4✔
835
                                        return {};
4✔
836
                                }
837
                        }
838

839
                        evp_pkey_handle pkey(PEM_read_bio_PUBKEY(
55✔
840
                                pubkey_bio.get(), nullptr, nullptr,
841
                                (void*)password.data())); // NOLINT(google-readability-casting) requires `const_cast`
55✔
842
                        if (!pkey) ec = error_category::load_key_bio_read;
55✔
843
                        return pkey;
55✔
844
                }
83✔
845

846
                /**
847
                 * \brief Load a public key from a string.
848
                 *
849
                 * The string should contain a pem encoded certificate or public key
850
                 *
851
                 * \tparam error_category        jwt::error enum category to match with the keys being used
852
                 * \param key                                String containing the certificate encoded as pem
853
                 * \param password                        Password used to decrypt certificate (leave empty if not encrypted)
854
                 * \throw                                        Templated error_category's type exception if an error occurred
855
                 */
856
                template<typename error_category = error::rsa_error>
857
                inline evp_pkey_handle load_public_key_from_string(const std::string& key, const std::string& password = "") {
38✔
858
                        std::error_code ec;
38✔
859
                        auto res = load_public_key_from_string<error_category>(key, password, ec);
38✔
860
                        error::throw_if_error(ec);
38✔
861
                        return res;
40✔
862
                }
18✔
863

864
                /**
865
                 * \brief Load a private key from a string.
866
                 *
867
                 * \tparam error_category        jwt::error enum category to match with the keys being used
868
                 * \param key                                String containing a private key as pem
869
                 * \param password                        Password used to decrypt key (leave empty if not encrypted)
870
                 * \param ec                                error_code for error_detection (gets cleared if no error occurs)
871
                 */
872
                template<typename error_category = error::rsa_error>
873
                inline evp_pkey_handle load_private_key_from_string(const std::string& key, const std::string& password,
69✔
874
                                                                                                                        std::error_code& ec) {
875
                        ec.clear();
69✔
876
                        auto private_key_bio = make_mem_buf_bio();
69✔
877
                        if (!private_key_bio) {
69✔
878
                                ec = error_category::create_mem_bio_failed;
5✔
879
                                return {};
5✔
880
                        }
881
                        const int len = static_cast<int>(key.size());
64✔
882
                        if (BIO_write(private_key_bio.get(), key.data(), len) != len) {
64✔
883
                                ec = error_category::load_key_bio_write;
5✔
884
                                return {};
5✔
885
                        }
886
                        evp_pkey_handle pkey(
59✔
887
                                PEM_read_bio_PrivateKey(private_key_bio.get(), nullptr, nullptr, const_cast<char*>(password.c_str())));
59✔
888
                        if (!pkey) ec = error_category::load_key_bio_read;
59✔
889
                        return pkey;
59✔
890
                }
69✔
891

892
                /**
893
                 * \brief Load a private key from a string.
894
                 *
895
                 * \tparam error_category        jwt::error enum category to match with the keys being used
896
                 * \param key                                String containing a private key as pem
897
                 * \param password                        Password used to decrypt key (leave empty if not encrypted)
898
                 * \throw                                        Templated error_category's type exception if an error occurred
899
                 */
900
                template<typename error_category = error::rsa_error>
901
                inline evp_pkey_handle load_private_key_from_string(const std::string& key, const std::string& password = "") {
33✔
902
                        std::error_code ec;
33✔
903
                        auto res = load_private_key_from_string<error_category>(key, password, ec);
33✔
904
                        error::throw_if_error(ec);
33✔
905
                        return res;
50✔
906
                }
8✔
907

908
                /**
909
                 * \brief Load a public key from a string.
910
                 *
911
                 * The string should contain a pem encoded certificate or public key
912
                 *
913
                 * \deprecated Use the templated version helper::load_private_key_from_string with error::ecdsa_error
914
                 *
915
                 * \param key                String containing the certificate encoded as pem
916
                 * \param password        Password used to decrypt certificate (leave empty if not encrypted)
917
                 * \param ec                error_code for error_detection (gets cleared if no error occurs)
918
                 */
919
                inline evp_pkey_handle load_public_ec_key_from_string(const std::string& key, const std::string& password,
920
                                                                                                                          std::error_code& ec) {
921
                        return load_public_key_from_string<error::ecdsa_error>(key, password, ec);
922
                }
923

924
                /**
925
                 * Convert a OpenSSL BIGNUM to a std::string
926
                 * \param bn BIGNUM to convert
927
                 * \return bignum as string
928
                 */
929
                inline
930
#ifdef JWT_OPENSSL_1_0_0
931
                        std::string
932
                        bn2raw(BIGNUM* bn)
933
#else
934
                        std::string
935
                        bn2raw(const BIGNUM* bn)
10✔
936
#endif
937
                {
938
                        std::string res(BN_num_bytes(bn), '\0');
10✔
939
                        BN_bn2bin(bn, (unsigned char*)res.data()); // NOLINT(google-readability-casting) requires `const_cast`
10✔
940
                        return res;
10✔
UNCOV
941
                }
×
942
                /**
943
                 * Convert an std::string to a OpenSSL BIGNUM
944
                 * \param raw String to convert
945
                 * \param ec  error_code for error_detection (gets cleared if no error occurs)
946
                 * \return BIGNUM representation
947
                 */
948
                inline bn_handle raw2bn(const std::string& raw, std::error_code& ec) {
129✔
949
                        auto bn =
950
                                BN_bin2bn(reinterpret_cast<const unsigned char*>(raw.data()), static_cast<int>(raw.size()), nullptr);
129✔
951
                        // https://www.openssl.org/docs/man1.1.1/man3/BN_bin2bn.html#RETURN-VALUES
952
                        if (!bn) {
129✔
UNCOV
953
                                ec = error::rsa_error::set_rsa_failed;
×
NEW
954
                                return bn_handle(nullptr);
×
955
                        }
956
                        return bn_handle(bn);
129✔
957
                }
958
                /**
959
                 * Convert an std::string to a OpenSSL BIGNUM
960
                 * \param raw String to convert
961
                 * \return BIGNUM representation
962
                 */
963
                inline bn_handle raw2bn(const std::string& raw) {
45✔
964
                        std::error_code ec;
45✔
965
                        auto res = raw2bn(raw, ec);
45✔
966
                        error::throw_if_error(ec);
45✔
967
                        return res;
90✔
UNCOV
968
                }
×
969

970
                /**
971
                 * \brief Load a public key from a string.
972
                 *
973
                 * The string should contain a pem encoded certificate or public key
974
                 *
975
                 * \deprecated Use the templated version helper::load_private_key_from_string with error::ecdsa_error
976
                 *
977
                 * \param key                String containing the certificate or key encoded as pem
978
                 * \param password        Password used to decrypt certificate or key (leave empty if not encrypted)
979
                 * \throw                        ecdsa_exception if an error occurred
980
                 */
981
                inline evp_pkey_handle load_public_ec_key_from_string(const std::string& key,
38✔
982
                                                                                                                          const std::string& password = "") {
983
                        std::error_code ec;
38✔
984
                        auto res = load_public_key_from_string<error::ecdsa_error>(key, password, ec);
38✔
985
                        error::throw_if_error(ec);
38✔
986
                        return res;
54✔
987
                }
11✔
988

989
                /**
990
                 * \brief Load a private key from a string.
991
                 *
992
                 * \deprecated Use the templated version helper::load_private_key_from_string with error::ecdsa_error
993
                 *
994
                 * \param key                String containing a private key as pem
995
                 * \param password        Password used to decrypt key (leave empty if not encrypted)
996
                 * \param ec                error_code for error_detection (gets cleared if no error occurs)
997
                 */
998
                inline evp_pkey_handle load_private_ec_key_from_string(const std::string& key, const std::string& password,
999
                                                                                                                           std::error_code& ec) {
1000
                        return load_private_key_from_string<error::ecdsa_error>(key, password, ec);
1001
                }
1002

1003
                /**
1004
                * \brief create public key from modulus and exponent. This is defined in
1005
                * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3)
1006
                * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter.
1007
                *
1008
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
1009
                 * It should ensure the padding of the input and then base64url decode and
1010
                 * return the results.
1011
                * \param modulus        string containing base64url encoded modulus
1012
                * \param exponent        string containing base64url encoded exponent
1013
                * \param decode         The function to decode the RSA parameters
1014
                * \param ec                        error_code for error_detection (gets cleared if no error occur
1015
                * \return                         public key in PEM format
1016
                */
1017
                template<typename Decode>
1018
                std::string create_public_key_from_rsa_components(const std::string& modulus, const std::string& exponent,
19✔
1019
                                                                                                                  Decode decode, std::error_code& ec) {
1020
                        ec.clear();
19✔
1021
                        auto decoded_modulus = decode(modulus);
19✔
1022
                        auto decoded_exponent = decode(exponent);
19✔
1023

1024
                        auto n = helper::raw2bn(decoded_modulus, ec);
19✔
1025
                        if (ec) return {};
19✔
1026
                        auto e = helper::raw2bn(decoded_exponent, ec);
19✔
1027
                        if (ec) return {};
19✔
1028

1029
#if defined(JWT_OPENSSL_3_0)
1030
                        // OpenSSL deprecated mutable keys and there is a new way for making them
1031
                        // https://mta.openssl.org/pipermail/openssl-users/2021-July/013994.html
1032
                        // https://www.openssl.org/docs/man3.1/man3/OSSL_PARAM_BLD_new.html#Example-2
1033
                        std::unique_ptr<OSSL_PARAM_BLD, decltype(&OSSL_PARAM_BLD_free)> param_bld(OSSL_PARAM_BLD_new(),
19✔
1034
                                                                                                                                                                          OSSL_PARAM_BLD_free);
19✔
1035
                        if (!param_bld) {
19✔
1036
                                ec = error::rsa_error::create_context_failed;
2✔
1037
                                return {};
2✔
1038
                        }
1039

1040
                        if (OSSL_PARAM_BLD_push_BN(param_bld.get(), "n", n.get()) != 1 ||
32✔
1041
                                OSSL_PARAM_BLD_push_BN(param_bld.get(), "e", e.get()) != 1) {
15✔
1042
                                ec = error::rsa_error::set_rsa_failed;
2✔
1043
                                return {};
2✔
1044
                        }
1045

1046
                        std::unique_ptr<OSSL_PARAM, decltype(&OSSL_PARAM_free)> params(OSSL_PARAM_BLD_to_param(param_bld.get()),
15✔
1047
                                                                                                                                                   OSSL_PARAM_free);
15✔
1048
                        if (!params) {
15✔
1049
                                ec = error::rsa_error::set_rsa_failed;
2✔
1050
                                return {};
2✔
1051
                        }
1052

1053
                        std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
13✔
1054
                                EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr), EVP_PKEY_CTX_free);
13✔
1055
                        if (!ctx) {
13✔
1056
                                ec = error::rsa_error::create_context_failed;
2✔
1057
                                return {};
2✔
1058
                        }
1059

1060
                        // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html#EXAMPLES
1061
                        // Error codes based on https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_fromdata_init.html#RETURN-VALUES
1062
                        EVP_PKEY* pkey = NULL;
11✔
1063
                        if (EVP_PKEY_fromdata_init(ctx.get()) <= 0 ||
20✔
1064
                                EVP_PKEY_fromdata(ctx.get(), &pkey, EVP_PKEY_KEYPAIR, params.get()) <= 0) {
9✔
1065
                                // It's unclear if this can fail after allocating but free it anyways
1066
                                // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html
1067
                                EVP_PKEY_free(pkey);
4✔
1068

1069
                                ec = error::rsa_error::cert_load_failed;
4✔
1070
                                return {};
4✔
1071
                        }
1072

1073
                        // Transfer ownership so we get ref counter and cleanup
1074
                        evp_pkey_handle rsa(pkey);
7✔
1075

1076
#else
1077
                        std::unique_ptr<RSA, decltype(&RSA_free)> rsa(RSA_new(), RSA_free);
1078

1079
#if defined(JWT_OPENSSL_1_1_1) || defined(JWT_OPENSSL_1_1_0)
1080
                        // After this RSA_free will also free the n and e big numbers
1081
                        // See https://github.com/Thalhammer/jwt-cpp/pull/298#discussion_r1282619186
1082
                        if (RSA_set0_key(rsa.get(), n.get(), e.get(), nullptr) == 1) {
1083
                                // This can only fail we passed in NULL for `n` or `e`
1084
                                // https://github.com/openssl/openssl/blob/d6e4056805f54bb1a0ef41fa3a6a35b70c94edba/crypto/rsa/rsa_lib.c#L396
1085
                                // So to make sure there is no memory leak, we hold the references
1086
                                n.release();
1087
                                e.release();
1088
                        } else {
1089
                                ec = error::rsa_error::set_rsa_failed;
1090
                                return {};
1091
                        }
1092
#elif defined(JWT_OPENSSL_1_0_0)
1093
                        rsa->e = e.release();
1094
                        rsa->n = n.release();
1095
                        rsa->d = nullptr;
1096
#endif
1097
#endif
1098

1099
                        auto pub_key_bio = make_mem_buf_bio();
7✔
1100
                        if (!pub_key_bio) {
7✔
1101
                                ec = error::rsa_error::create_mem_bio_failed;
2✔
1102
                                return {};
2✔
1103
                        }
1104

1105
                        auto write_pem_to_bio =
5✔
1106
#if defined(JWT_OPENSSL_3_0)
1107
                                // https://www.openssl.org/docs/man3.1/man3/PEM_write_bio_RSA_PUBKEY.html
1108
                                &PEM_write_bio_PUBKEY;
1109
#else
1110
                                &PEM_write_bio_RSA_PUBKEY;
1111
#endif
1112
                        if (write_pem_to_bio(pub_key_bio.get(), rsa.get()) != 1) {
5✔
1113
                                ec = error::rsa_error::load_key_bio_write;
2✔
1114
                                return {};
2✔
1115
                        }
1116

1117
                        return write_bio_to_string<error::rsa_error>(pub_key_bio, ec);
3✔
1118
                }
19✔
1119

1120
                /**
1121
                * Create public key from modulus and exponent. This is defined in
1122
                * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3)
1123
                * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter.
1124
                *
1125
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
1126
                 * It should ensure the padding of the input and then base64url decode and
1127
                 * return the results.
1128
                * \param modulus        string containing base64url encoded modulus
1129
                * \param exponent        string containing base64url encoded exponent
1130
                * \param decode         The function to decode the RSA parameters
1131
                * \return public key in PEM format
1132
                */
1133
                template<typename Decode>
1134
                std::string create_public_key_from_rsa_components(const std::string& modulus, const std::string& exponent,
1135
                                                                                                                  Decode decode) {
1136
                        std::error_code ec;
1137
                        auto res = create_public_key_from_rsa_components(modulus, exponent, decode, ec);
1138
                        error::throw_if_error(ec);
1139
                        return res;
1140
                }
1141

1142
#ifndef JWT_DISABLE_BASE64
1143
                /**
1144
                * Create public key from modulus and exponent. This is defined in
1145
                * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3)
1146
                * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter.
1147
                *
1148
                * \param modulus        string containing base64 encoded modulus
1149
                * \param exponent        string containing base64 encoded exponent
1150
                * \param ec                        error_code for error_detection (gets cleared if no error occur
1151
                * \return public key in PEM format
1152
                */
1153
                inline std::string create_public_key_from_rsa_components(const std::string& modulus,
19✔
1154
                                                                                                                                 const std::string& exponent, std::error_code& ec) {
1155
                        auto decode = [](const std::string& token) {
38✔
1156
                                return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(token));
38✔
1157
                        };
1158
                        return create_public_key_from_rsa_components(modulus, exponent, std::move(decode), ec);
38✔
1159
                }
1160
                /**
1161
                * Create public key from modulus and exponent. This is defined in
1162
                * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3)
1163
                * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter.
1164
                *
1165
                * \param modulus        string containing base64url encoded modulus
1166
                * \param exponent        string containing base64url encoded exponent
1167
                * \return public key in PEM format
1168
                */
1169
                inline std::string create_public_key_from_rsa_components(const std::string& modulus,
10✔
1170
                                                                                                                                 const std::string& exponent) {
1171
                        std::error_code ec;
10✔
1172
                        auto res = create_public_key_from_rsa_components(modulus, exponent, ec);
10✔
1173
                        error::throw_if_error(ec);
10✔
1174
                        return res;
2✔
1175
                }
9✔
1176
#endif
1177
                /**
1178
                 * \brief Load a private key from a string.
1179
                 *
1180
                 * \deprecated Use the templated version helper::load_private_key_from_string with error::ecdsa_error
1181
                 *
1182
                 * \param key                String containing a private key as pem
1183
                 * \param password        Password used to decrypt key (leave empty if not encrypted)
1184
                 * \throw                        ecdsa_exception if an error occurred
1185
                 */
1186
                inline evp_pkey_handle load_private_ec_key_from_string(const std::string& key,
33✔
1187
                                                                                                                           const std::string& password = "") {
1188
                        std::error_code ec;
33✔
1189
                        auto res = load_private_key_from_string<error::ecdsa_error>(key, password, ec);
33✔
1190
                        error::throw_if_error(ec);
33✔
1191
                        return res;
60✔
1192
                }
3✔
1193

1194
#if defined(JWT_OPENSSL_3_0)
1195

1196
                /**
1197
                 * \brief Convert a curve name to a group name.
1198
                 *
1199
                 * \param curve        string containing curve name
1200
                 * \param ec        error_code for error_detection
1201
                 * \return                 group name
1202
                 */
1203
                inline std::string curve2group(const std::string curve, std::error_code& ec) {
19✔
1204
                        if (curve == "P-256") {
19✔
UNCOV
1205
                                return "prime256v1";
×
1206
                        } else if (curve == "P-384") {
19✔
1207
                                return "secp384r1";
38✔
UNCOV
1208
                        } else if (curve == "P-521") {
×
1209
                                return "secp521r1";
×
1210
                        } else {
UNCOV
1211
                                ec = jwt::error::ecdsa_error::unknown_curve;
×
UNCOV
1212
                                return {};
×
1213
                        }
1214
                }
1215

1216
#else
1217

1218
                /**
1219
                 * \brief Convert a curve name to an ID.
1220
                 *
1221
                 * \param curve        string containing curve name
1222
                 * \param ec        error_code for error_detection
1223
                 * \return                 ID
1224
                 */
1225
                inline int curve2nid(const std::string curve, std::error_code& ec) {
1226
                        if (curve == "P-256") {
1227
                                return NID_X9_62_prime256v1;
1228
                        } else if (curve == "P-384") {
1229
                                return NID_secp384r1;
1230
                        } else if (curve == "P-521") {
1231
                                return NID_secp521r1;
1232
                        } else {
1233
                                ec = jwt::error::ecdsa_error::unknown_curve;
1234
                                return {};
1235
                        }
1236
                }
1237

1238
#endif
1239

1240
                /**
1241
                 * Create public key from curve name and coordinates. This is defined in
1242
                 * [RFC 7518 Section 6.2](https://www.rfc-editor.org/rfc/rfc7518#section-6.2)
1243
                 * Using the required "crv" (Curve), "x" (X Coordinate) and "y" (Y Coordinate) Parameters.
1244
                 *
1245
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
1246
                 * It should ensure the padding of the input and then base64url decode and
1247
                 * return the results.
1248
                 * \param curve        string containing curve name
1249
                 * \param x                string containing base64url encoded x coordinate
1250
                 * \param y                string containing base64url encoded y coordinate
1251
                 * \param decode        The function to decode the RSA parameters
1252
                 * \param ec                error_code for error_detection (gets cleared if no error occur
1253
                 * \return                 public key in PEM format
1254
                 */
1255
                template<typename Decode>
1256
                std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
21✔
1257
                                                                                                                 const std::string& y, Decode decode, std::error_code& ec) {
1258
                        ec.clear();
21✔
1259
                        auto decoded_x = decode(x);
21✔
1260
                        auto decoded_y = decode(y);
21✔
1261

1262
#if defined(JWT_OPENSSL_3_0)
1263
                        // OpenSSL deprecated mutable keys and there is a new way for making them
1264
                        // https://mta.openssl.org/pipermail/openssl-users/2021-July/013994.html
1265
                        // https://www.openssl.org/docs/man3.1/man3/OSSL_PARAM_BLD_new.html#Example-2
1266
                        std::unique_ptr<OSSL_PARAM_BLD, decltype(&OSSL_PARAM_BLD_free)> param_bld(OSSL_PARAM_BLD_new(),
21✔
1267
                                                                                                                                                                          OSSL_PARAM_BLD_free);
21✔
1268
                        if (!param_bld) {
21✔
1269
                                ec = error::ecdsa_error::create_context_failed;
2✔
1270
                                return {};
2✔
1271
                        }
1272

1273
                        std::string group = helper::curve2group(curve, ec);
19✔
1274
                        if (ec) return {};
19✔
1275

1276
                        // https://github.com/openssl/openssl/issues/16270#issuecomment-895734092
1277
                        std::string pub = std::string("\x04").append(decoded_x).append(decoded_y);
19✔
1278

1279
                        if (OSSL_PARAM_BLD_push_utf8_string(param_bld.get(), "group", group.data(), group.size()) != 1 ||
36✔
1280
                                OSSL_PARAM_BLD_push_octet_string(param_bld.get(), "pub", pub.data(), pub.size()) != 1) {
17✔
1281
                                ec = error::ecdsa_error::set_ecdsa_failed;
4✔
1282
                                return {};
4✔
1283
                        }
1284

1285
                        std::unique_ptr<OSSL_PARAM, decltype(&OSSL_PARAM_free)> params(OSSL_PARAM_BLD_to_param(param_bld.get()),
15✔
1286
                                                                                                                                                   OSSL_PARAM_free);
15✔
1287
                        if (!params) {
15✔
1288
                                ec = error::ecdsa_error::set_ecdsa_failed;
2✔
1289
                                return {};
2✔
1290
                        }
1291

1292
                        std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
13✔
1293
                                EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr), EVP_PKEY_CTX_free);
13✔
1294
                        if (!ctx) {
13✔
1295
                                ec = error::ecdsa_error::create_context_failed;
2✔
1296
                                return {};
2✔
1297
                        }
1298

1299
                        // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html#EXAMPLES
1300
                        // Error codes based on https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_fromdata_init.html#RETURN-VALUES
1301
                        EVP_PKEY* pkey = NULL;
11✔
1302
                        if (EVP_PKEY_fromdata_init(ctx.get()) <= 0 ||
20✔
1303
                                EVP_PKEY_fromdata(ctx.get(), &pkey, EVP_PKEY_KEYPAIR, params.get()) <= 0) {
9✔
1304
                                // It's unclear if this can fail after allocating but free it anyways
1305
                                // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html
1306
                                EVP_PKEY_free(pkey);
4✔
1307

1308
                                ec = error::ecdsa_error::cert_load_failed;
4✔
1309
                                return {};
4✔
1310
                        }
1311

1312
                        // Transfer ownership so we get ref counter and cleanup
1313
                        evp_pkey_handle ecdsa(pkey);
7✔
1314

1315
#else
1316
                        int nid = helper::curve2nid(curve, ec);
1317
                        if (ec) return {};
1318

1319
                        auto qx = helper::raw2bn(decoded_x, ec);
1320
                        if (ec) return {};
1321
                        auto qy = helper::raw2bn(decoded_y, ec);
1322
                        if (ec) return {};
1323

1324
                        std::unique_ptr<EC_GROUP, decltype(&EC_GROUP_free)> ecgroup(EC_GROUP_new_by_curve_name(nid), EC_GROUP_free);
1325
                        if (!ecgroup) {
1326
                                ec = error::ecdsa_error::set_ecdsa_failed;
1327
                                return {};
1328
                        }
1329

1330
                        EC_GROUP_set_asn1_flag(ecgroup.get(), OPENSSL_EC_NAMED_CURVE);
1331

1332
                        std::unique_ptr<EC_POINT, decltype(&EC_POINT_free)> ecpoint(EC_POINT_new(ecgroup.get()), EC_POINT_free);
1333
                        if (!ecpoint ||
1334
                                EC_POINT_set_affine_coordinates_GFp(ecgroup.get(), ecpoint.get(), qx.get(), qy.get(), nullptr) != 1) {
1335
                                ec = error::ecdsa_error::set_ecdsa_failed;
1336
                                return {};
1337
                        }
1338

1339
                        std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> ecdsa(EC_KEY_new(), EC_KEY_free);
1340
                        if (!ecdsa || EC_KEY_set_group(ecdsa.get(), ecgroup.get()) != 1 ||
1341
                                EC_KEY_set_public_key(ecdsa.get(), ecpoint.get()) != 1) {
1342
                                ec = error::ecdsa_error::set_ecdsa_failed;
1343
                                return {};
1344
                        }
1345

1346
#endif
1347

1348
                        auto pub_key_bio = make_mem_buf_bio();
7✔
1349
                        if (!pub_key_bio) {
7✔
1350
                                ec = error::ecdsa_error::create_mem_bio_failed;
2✔
1351
                                return {};
2✔
1352
                        }
1353

1354
                        auto write_pem_to_bio =
5✔
1355
#if defined(JWT_OPENSSL_3_0)
1356
                                // https://www.openssl.org/docs/man3.1/man3/PEM_write_bio_EC_PUBKEY.html
1357
                                &PEM_write_bio_PUBKEY;
1358
#else
1359
                                &PEM_write_bio_EC_PUBKEY;
1360
#endif
1361
                        if (write_pem_to_bio(pub_key_bio.get(), ecdsa.get()) != 1) {
5✔
1362
                                ec = error::ecdsa_error::load_key_bio_write;
2✔
1363
                                return {};
2✔
1364
                        }
1365

1366
                        return write_bio_to_string<error::ecdsa_error>(pub_key_bio, ec);
3✔
1367
                }
21✔
1368

1369
                /**
1370
                * Create public key from curve name and coordinates. This is defined in
1371
                * [RFC 7518 Section 6.2](https://www.rfc-editor.org/rfc/rfc7518#section-6.2)
1372
                * Using the required "crv" (Curve), "x" (X Coordinate) and "y" (Y Coordinate) Parameters.
1373
                *
1374
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
1375
                 * It should ensure the padding of the input and then base64url decode and
1376
                 * return the results.
1377
                * \param curve        string containing curve name
1378
                * \param x                string containing base64url encoded x coordinate
1379
                * \param y                string containing base64url encoded y coordinate
1380
                * \param decode The function to decode the RSA parameters
1381
                * \return public key in PEM format
1382
                */
1383
                template<typename Decode>
1384
                std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
1385
                                                                                                                 const std::string& y, Decode decode) {
1386
                        std::error_code ec;
1387
                        auto res = create_public_key_from_ec_components(curve, x, y, decode, ec);
1388
                        error::throw_if_error(ec);
1389
                        return res;
1390
                }
1391

1392
#ifndef JWT_DISABLE_BASE64
1393
                /**
1394
                * Create public key from curve name and coordinates. This is defined in
1395
                * [RFC 7518 Section 6.2](https://www.rfc-editor.org/rfc/rfc7518#section-6.2)
1396
                * Using the required "crv" (Curve), "x" (X Coordinate) and "y" (Y Coordinate) Parameters.
1397
                *
1398
                * \param curve        string containing curve name
1399
                * \param x                string containing base64url encoded x coordinate
1400
                * \param y                string containing base64url encoded y coordinate
1401
                * \param ec                error_code for error_detection (gets cleared if no error occur
1402
                * \return public key in PEM format
1403
                */
1404
                inline std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
21✔
1405
                                                                                                                                const std::string& y, std::error_code& ec) {
1406
                        auto decode = [](const std::string& token) {
42✔
1407
                                return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(token));
42✔
1408
                        };
1409
                        return create_public_key_from_ec_components(curve, x, y, std::move(decode), ec);
42✔
1410
                }
1411
                /**
1412
                * Create public key from curve name and coordinates. This is defined in
1413
                * [RFC 7518 Section 6.2](https://www.rfc-editor.org/rfc/rfc7518#section-6.2)
1414
                * Using the required "crv" (Curve), "x" (X Coordinate) and "y" (Y Coordinate) Parameters.
1415
                *
1416
                * \param curve        string containing curve name
1417
                * \param x                string containing base64url encoded x coordinate
1418
                * \param y                string containing base64url encoded y coordinate
1419
                * \return public key in PEM format
1420
                */
1421
                inline std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
11✔
1422
                                                                                                                                const std::string& y) {
1423
                        std::error_code ec;
11✔
1424
                        auto res = create_public_key_from_ec_components(curve, x, y, ec);
11✔
1425
                        error::throw_if_error(ec);
11✔
1426
                        return res;
2✔
1427
                }
10✔
1428
#endif
1429
        } // namespace helper
1430

1431
        /**
1432
         * \brief Various cryptographic algorithms when working with JWT
1433
         *
1434
         * JWT (JSON Web Tokens) signatures are typically used as the payload for a JWS (JSON Web Signature) or
1435
         * JWE (JSON Web Encryption). Both of these use various cryptographic as specified by
1436
         * [RFC7518](https://tools.ietf.org/html/rfc7518) and are exposed through the a [JOSE
1437
         * Header](https://tools.ietf.org/html/rfc7515#section-4) which points to one of the JWA [JSON Web
1438
         * Algorithms](https://tools.ietf.org/html/rfc7518#section-3.1)
1439
         */
1440
        namespace algorithm {
1441
                /**
1442
                 * \brief "none" algorithm.
1443
                 *
1444
                 * Returns and empty signature and checks if the given signature is empty.
1445
                 * See [RFC 7518 Section 3.6](https://datatracker.ietf.org/doc/html/rfc7518#section-3.6)
1446
                 * for more information.
1447
                 */
1448
                struct none {
1449
                        /**
1450
                         * \brief Return an empty string
1451
                         */
1452
                        std::string sign(const std::string& /*unused*/, std::error_code& ec) const {
17✔
1453
                                ec.clear();
17✔
1454
                                return {};
17✔
1455
                        }
1456
                        /**
1457
                         * \brief Check if the given signature is empty.
1458
                         *
1459
                         * JWT's with "none" algorithm should not contain a signature.
1460
                         * \param signature Signature data to verify
1461
                         * \param ec                error_code filled with details about the error
1462
                         */
1463
                        void verify(const std::string& /*unused*/, const std::string& signature, std::error_code& ec) const {
28✔
1464
                                ec.clear();
28✔
1465
                                if (!signature.empty()) { ec = error::signature_verification_error::invalid_signature; }
28✔
1466
                        }
28✔
1467
                        /// Get algorithm name
1468
                        std::string name() const { return "none"; }
114✔
1469
                };
1470
                /**
1471
                 * \brief Base class for HMAC family of algorithms
1472
                 */
1473
                struct hmacsha {
1474
                        /**
1475
                         * Construct new hmac algorithm
1476
                         *
1477
                         * \deprecated Using a character is not recommended and hardened applications should use BIGNUM
1478
                         * \param key Key to use for HMAC
1479
                         * \param md Pointer to hash function
1480
                         * \param name Name of the algorithm
1481
                         */
1482
                        hmacsha(std::string key, const EVP_MD* (*md)(), std::string name)
43✔
1483
                                : secret(helper::raw2bn(key)), md(md), alg_name(std::move(name)) {}
43✔
1484
                        /**
1485
                         * Construct new hmac algorithm
1486
                         *
1487
                         * \param key Key to use for HMAC
1488
                         * \param md Pointer to hash function
1489
                         * \param name Name of the algorithm
1490
                         */
1491
                        hmacsha(const BIGNUM* key, const EVP_MD* (*md)(), std::string name)
3✔
1492
                                : secret(key), md(md), alg_name(std::move(name)) {}
3✔
1493

1494
                        // Explicitly defaulted copy/move constructors (bn_handle provides RAII)
1495
                        hmacsha(const hmacsha&) = default;
50✔
1496
                        hmacsha(hmacsha&&) noexcept = default;
1497

1498
                        // Assignment operators deleted to maintain immutability
1499
                        hmacsha& operator=(const hmacsha&) = delete;
1500
                        hmacsha& operator=(hmacsha&&) = delete;
1501
                        std::string sign(const std::string& data, std::error_code& ec) const {
50✔
1502
                                ec.clear();
50✔
1503
                                std::string res(static_cast<size_t>(EVP_MAX_MD_SIZE), '\0');
50✔
1504
                                auto len = static_cast<unsigned int>(res.size());
50✔
1505

1506
                                std::vector<unsigned char> buffer(BN_num_bytes(secret.get()), '\0');
50✔
1507
                                const auto buffer_size = BN_bn2bin(secret.get(), buffer.data());
50✔
1508
                                buffer.resize(buffer_size);
50✔
1509

1510
                                if (HMAC(md(), buffer.data(), buffer_size, reinterpret_cast<const unsigned char*>(data.data()),
50✔
1511
                                                 static_cast<int>(data.size()),
50✔
1512
                                                 (unsigned char*)res.data(), // NOLINT(google-readability-casting) requires `const_cast`
50✔
1513
                                                 &len) == nullptr) {
50✔
1514
                                        ec = error::signature_generation_error::hmac_failed;
1✔
1515
                                        return {};
1✔
1516
                                }
1517
                                res.resize(len);
49✔
1518
                                return res;
49✔
1519
                        }
50✔
1520
                        /**
1521
                         * Check if signature is valid
1522
                         *
1523
                         * \param data The data to check signature against
1524
                         * \param signature Signature provided by the jwt
1525
                         * \param ec Filled with details about failure.
1526
                         */
1527
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
29✔
1528
                                ec.clear();
29✔
1529
                                auto res = sign(data, ec);
29✔
1530
                                if (ec) return;
29✔
1531

1532
                                bool matched = true;
28✔
1533
                                for (size_t i = 0; i < std::min<size_t>(res.size(), signature.size()); i++)
923✔
1534
                                        if (res[i] != signature[i]) matched = false;
895✔
1535
                                if (res.size() != signature.size()) matched = false;
28✔
1536
                                if (!matched) {
28✔
1537
                                        ec = error::signature_verification_error::invalid_signature;
2✔
1538
                                        return;
2✔
1539
                                }
1540
                        }
29✔
1541
                        /**
1542
                         * Returns the algorithm name provided to the constructor
1543
                         *
1544
                         * \return algorithm's name
1545
                         */
1546
                        std::string name() const { return alg_name; }
46✔
1547

1548
                private:
1549
                        /// HMAC secret
1550
                        helper::bn_handle secret;
1551
                        /// HMAC hash generator
1552
                        const EVP_MD* (*md)();
1553
                        /// algorithm's name
1554
                        const std::string alg_name;
1555
                };
1556

1557
                /**
1558
                 * \brief Base class for RSA family of algorithms
1559
                 */
1560
                struct rsa {
1561
                        /**
1562
                         * Construct new rsa algorithm
1563
                         *
1564
                         * \param public_key RSA public key in PEM format
1565
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
1566
                         * \param public_key_password Password to decrypt public key pem.
1567
                         * \param private_key_password Password to decrypt private key pem.
1568
                         * \param md Pointer to hash function
1569
                         * \param name Name of the algorithm
1570
                         */
1571
                        rsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
16✔
1572
                                const std::string& private_key_password, const EVP_MD* (*md)(), std::string name)
1573
                                : md(md), alg_name(std::move(name)) {
16✔
1574
                                if (!private_key.empty()) {
16✔
1575
                                        pkey = helper::load_private_key_from_string(private_key, private_key_password);
10✔
1576
                                } else if (!public_key.empty()) {
6✔
1577
                                        pkey = helper::load_public_key_from_string(public_key, public_key_password);
5✔
1578
                                } else
1579
                                        throw error::rsa_exception(error::rsa_error::no_key_provided);
1✔
1580
                        }
17✔
1581
                        /**
1582
                         * Construct new rsa algorithm
1583
                         *
1584
                         * \param key_pair openssl EVP_PKEY structure containing RSA key pair. The private part is optional.
1585
                         * \param md Pointer to hash function
1586
                         * \param name Name of the algorithm
1587
                         */
1588
                        rsa(helper::evp_pkey_handle key_pair, const EVP_MD* (*md)(), std::string name)
3✔
1589
                                : pkey(std::move(key_pair)), md(md), alg_name(std::move(name)) {
3✔
1590
                                if (!pkey) { throw error::rsa_exception(error::rsa_error::no_key_provided); }
3✔
1591
                        }
3✔
1592
                        /**
1593
                         * Sign jwt data
1594
                         * \param data The data to sign
1595
                         * \param ec error_code filled with details on error
1596
                         * \return RSA signature for the given data
1597
                         */
1598
                        std::string sign(const std::string& data, std::error_code& ec) const {
9✔
1599
                                ec.clear();
9✔
1600
                                auto ctx = helper::make_evp_md_ctx();
9✔
1601
                                if (!ctx) {
9✔
1602
                                        ec = error::signature_generation_error::create_context_failed;
1✔
1603
                                        return {};
1✔
1604
                                }
1605
                                if (!EVP_SignInit(ctx.get(), md())) {
8✔
1606
                                        ec = error::signature_generation_error::signinit_failed;
1✔
1607
                                        return {};
1✔
1608
                                }
1609

1610
                                std::string res(EVP_PKEY_size(pkey.get()), '\0');
7✔
1611
                                unsigned int len = 0;
7✔
1612

1613
                                if (!EVP_SignUpdate(ctx.get(), data.data(), data.size())) {
7✔
1614
                                        ec = error::signature_generation_error::signupdate_failed;
1✔
1615
                                        return {};
1✔
1616
                                }
1617
                                if (EVP_SignFinal(ctx.get(), (unsigned char*)res.data(), &len, pkey.get()) == 0) {
6✔
1618
                                        ec = error::signature_generation_error::signfinal_failed;
1✔
1619
                                        return {};
1✔
1620
                                }
1621

1622
                                res.resize(len);
5✔
1623
                                return res;
5✔
1624
                        }
9✔
1625
                        /**
1626
                         * Check if signature is valid
1627
                         *
1628
                         * \param data The data to check signature against
1629
                         * \param signature Signature provided by the jwt
1630
                         * \param ec Filled with details on failure
1631
                         */
1632
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
16✔
1633
                                ec.clear();
16✔
1634
                                auto ctx = helper::make_evp_md_ctx();
16✔
1635
                                if (!ctx) {
16✔
1636
                                        ec = error::signature_verification_error::create_context_failed;
1✔
1637
                                        return;
1✔
1638
                                }
1639
                                if (!EVP_VerifyInit(ctx.get(), md())) {
15✔
1640
                                        ec = error::signature_verification_error::verifyinit_failed;
1✔
1641
                                        return;
1✔
1642
                                }
1643
                                if (!EVP_VerifyUpdate(ctx.get(), data.data(), data.size())) {
14✔
1644
                                        ec = error::signature_verification_error::verifyupdate_failed;
1✔
1645
                                        return;
1✔
1646
                                }
1647
                                auto res = EVP_VerifyFinal(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
26✔
1648
                                                                                   static_cast<unsigned int>(signature.size()), pkey.get());
13✔
1649
                                if (res != 1) {
13✔
1650
                                        ec = error::signature_verification_error::verifyfinal_failed;
3✔
1651
                                        return;
3✔
1652
                                }
1653
                        }
16✔
1654
                        /**
1655
                         * Returns the algorithm name provided to the constructor
1656
                         * \return algorithm's name
1657
                         */
1658
                        std::string name() const { return alg_name; }
15✔
1659

1660
                private:
1661
                        /// OpenSSL structure containing converted keys
1662
                        helper::evp_pkey_handle pkey;
1663
                        /// Hash generator
1664
                        const EVP_MD* (*md)();
1665
                        /// algorithm's name
1666
                        const std::string alg_name;
1667
                };
1668
                /**
1669
                 * \brief Base class for ECDSA family of algorithms
1670
                 */
1671
                struct ecdsa {
1672
                        /**
1673
                         * Construct new ecdsa algorithm
1674
                         *
1675
                         * \param public_key ECDSA public key in PEM format
1676
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail
1677
                         * \param public_key_password Password to decrypt public key pem
1678
                         * \param private_key_password Password to decrypt private key pem
1679
                         * \param md Pointer to hash function
1680
                         * \param name Name of the algorithm
1681
                         * \param siglen The bit length of the signature
1682
                         */
1683
                        ecdsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
69✔
1684
                                  const std::string& private_key_password, const EVP_MD* (*md)(), std::string name, size_t siglen)
1685
                                : md(md), alg_name(std::move(name)), signature_length(siglen) {
69✔
1686
                                if (!private_key.empty()) {
69✔
1687
                                        pkey = helper::load_private_ec_key_from_string(private_key, private_key_password);
32✔
1688
                                        check_private_key(pkey.get());
29✔
1689
                                } else if (!public_key.empty()) {
37✔
1690
                                        pkey = helper::load_public_ec_key_from_string(public_key, public_key_password);
36✔
1691
                                        check_public_key(pkey.get());
25✔
1692
                                } else {
1693
                                        throw error::ecdsa_exception(error::ecdsa_error::no_key_provided);
1✔
1694
                                }
1695
                                if (!pkey) throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
50✔
1696

1697
                                size_t keysize = EVP_PKEY_bits(pkey.get());
50✔
1698
                                if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521))
50✔
1699
                                        throw error::ecdsa_exception(error::ecdsa_error::invalid_key_size);
24✔
1700
                        }
112✔
1701

1702
                        /**
1703
                         * Construct new ecdsa algorithm
1704
                         *
1705
                         * \param key_pair openssl EVP_PKEY structure containing ECDSA key pair. The private part is optional.
1706
                         * \param md Pointer to hash function
1707
                         * \param name Name of the algorithm
1708
                         * \param siglen The bit length of the signature
1709
                         */
1710
                        ecdsa(helper::evp_pkey_handle key_pair, const EVP_MD* (*md)(), std::string name, size_t siglen)
4✔
1711
                                : pkey(std::move(key_pair)), md(md), alg_name(std::move(name)), signature_length(siglen) {
4✔
1712
                                if (!pkey) { throw error::ecdsa_exception(error::ecdsa_error::no_key_provided); }
4✔
1713
                                size_t keysize = EVP_PKEY_bits(pkey.get());
3✔
1714
                                if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521))
3✔
UNCOV
1715
                                        throw error::ecdsa_exception(error::ecdsa_error::invalid_key_size);
×
1716
                        }
5✔
1717

1718
                        /**
1719
                         * Sign jwt data
1720
                         * \param data The data to sign
1721
                         * \param ec error_code filled with details on error
1722
                         * \return ECDSA signature for the given data
1723
                         */
1724
                        std::string sign(const std::string& data, std::error_code& ec) const {
15✔
1725
                                ec.clear();
15✔
1726
                                auto ctx = helper::make_evp_md_ctx();
15✔
1727
                                if (!ctx) {
15✔
1728
                                        ec = error::signature_generation_error::create_context_failed;
1✔
1729
                                        return {};
1✔
1730
                                }
1731
                                if (!EVP_DigestSignInit(ctx.get(), nullptr, md(), nullptr, pkey.get())) {
14✔
1732
                                        ec = error::signature_generation_error::signinit_failed;
1✔
1733
                                        return {};
1✔
1734
                                }
1735
                                if (!EVP_DigestUpdate(ctx.get(), data.data(), static_cast<unsigned int>(data.size()))) {
13✔
1736
                                        ec = error::signature_generation_error::digestupdate_failed;
1✔
1737
                                        return {};
1✔
1738
                                }
1739

1740
                                size_t len = 0;
12✔
1741
                                if (!EVP_DigestSignFinal(ctx.get(), nullptr, &len)) {
12✔
1742
                                        ec = error::signature_generation_error::signfinal_failed;
1✔
1743
                                        return {};
1✔
1744
                                }
1745
                                std::string res(len, '\0');
11✔
1746
                                if (!EVP_DigestSignFinal(ctx.get(), (unsigned char*)res.data(), &len)) {
11✔
1747
                                        ec = error::signature_generation_error::signfinal_failed;
5✔
1748
                                        return {};
5✔
1749
                                }
1750

1751
                                res.resize(len);
6✔
1752
                                return der_to_p1363_signature(res, ec);
6✔
1753
                        }
15✔
1754

1755
                        /**
1756
                         * Check if signature is valid
1757
                         * \param data The data to check signature against
1758
                         * \param signature Signature provided by the jwt
1759
                         * \param ec Filled with details on error
1760
                         */
1761
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
23✔
1762
                                ec.clear();
23✔
1763
                                std::string der_signature = p1363_to_der_signature(signature, ec);
23✔
1764
                                if (ec) { return; }
23✔
1765

1766
                                auto ctx = helper::make_evp_md_ctx();
20✔
1767
                                if (!ctx) {
20✔
1768
                                        ec = error::signature_verification_error::create_context_failed;
1✔
1769
                                        return;
1✔
1770
                                }
1771
                                if (!EVP_DigestVerifyInit(ctx.get(), nullptr, md(), nullptr, pkey.get())) {
19✔
1772
                                        ec = error::signature_verification_error::verifyinit_failed;
1✔
1773
                                        return;
1✔
1774
                                }
1775
                                if (!EVP_DigestUpdate(ctx.get(), data.data(), static_cast<unsigned int>(data.size()))) {
18✔
1776
                                        ec = error::signature_verification_error::verifyupdate_failed;
1✔
1777
                                        return;
1✔
1778
                                }
1779

1780
#if OPENSSL_VERSION_NUMBER < 0x10002000L
1781
                                unsigned char* der_sig_data = reinterpret_cast<unsigned char*>(const_cast<char*>(der_signature.data()));
1782
#else
1783
                                const unsigned char* der_sig_data = reinterpret_cast<const unsigned char*>(der_signature.data());
17✔
1784
#endif
1785
                                auto res =
1786
                                        EVP_DigestVerifyFinal(ctx.get(), der_sig_data, static_cast<unsigned int>(der_signature.length()));
17✔
1787
                                if (res == 0) {
17✔
1788
                                        ec = error::signature_verification_error::invalid_signature;
8✔
1789
                                        return;
8✔
1790
                                }
1791
                                if (res == -1) {
9✔
UNCOV
1792
                                        ec = error::signature_verification_error::verifyfinal_failed;
×
UNCOV
1793
                                        return;
×
1794
                                }
1795
                        }
34✔
1796
                        /**
1797
                         * Returns the algorithm name provided to the constructor
1798
                         * \return algorithm's name
1799
                         */
1800
                        std::string name() const { return alg_name; }
23✔
1801

1802
                private:
1803
                        static void check_public_key(EVP_PKEY* pkey) {
25✔
1804
#ifdef JWT_OPENSSL_3_0
1805
                                std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
1806
                                        EVP_PKEY_CTX_new_from_pkey(nullptr, pkey, nullptr), EVP_PKEY_CTX_free);
25✔
1807
                                if (!ctx) { throw error::ecdsa_exception(error::ecdsa_error::create_context_failed); }
25✔
1808
                                if (EVP_PKEY_public_check(ctx.get()) != 1) {
24✔
1809
                                        throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1✔
1810
                                }
1811
#else
1812
                                std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> eckey(EVP_PKEY_get1_EC_KEY(pkey), EC_KEY_free);
1813
                                if (!eckey) { throw error::ecdsa_exception(error::ecdsa_error::invalid_key); }
1814
                                if (EC_KEY_check_key(eckey.get()) == 0) throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1815
#endif
1816
                        }
25✔
1817

1818
                        static void check_private_key(EVP_PKEY* pkey) {
29✔
1819
#ifdef JWT_OPENSSL_3_0
1820
                                std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
1821
                                        EVP_PKEY_CTX_new_from_pkey(nullptr, pkey, nullptr), EVP_PKEY_CTX_free);
29✔
1822
                                if (!ctx) { throw error::ecdsa_exception(error::ecdsa_error::create_context_failed); }
29✔
1823
                                if (EVP_PKEY_private_check(ctx.get()) != 1) {
28✔
1824
                                        throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1✔
1825
                                }
1826
#else
1827
                                std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> eckey(EVP_PKEY_get1_EC_KEY(pkey), EC_KEY_free);
1828
                                if (!eckey) { throw error::ecdsa_exception(error::ecdsa_error::invalid_key); }
1829
                                if (EC_KEY_check_key(eckey.get()) == 0) throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1830
#endif
1831
                        }
29✔
1832

1833
                        std::string der_to_p1363_signature(const std::string& der_signature, std::error_code& ec) const {
6✔
1834
                                const unsigned char* possl_signature = reinterpret_cast<const unsigned char*>(der_signature.data());
6✔
1835
                                std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(
1836
                                        d2i_ECDSA_SIG(nullptr, &possl_signature, static_cast<long>(der_signature.length())),
6✔
1837
                                        ECDSA_SIG_free);
6✔
1838
                                if (!sig) {
6✔
1839
                                        ec = error::signature_generation_error::signature_decoding_failed;
1✔
1840
                                        return {};
1✔
1841
                                }
1842

1843
#ifdef JWT_OPENSSL_1_0_0
1844
                                auto rr = helper::bn2raw(sig->r);
1845
                                auto rs = helper::bn2raw(sig->s);
1846
#else
1847
                                const BIGNUM* r;
1848
                                const BIGNUM* s;
1849
                                ECDSA_SIG_get0(sig.get(), &r, &s);
5✔
1850
                                auto rr = helper::bn2raw(r);
5✔
1851
                                auto rs = helper::bn2raw(s);
5✔
1852
#endif
1853
                                if (rr.size() > signature_length / 2 || rs.size() > signature_length / 2)
5✔
UNCOV
1854
                                        throw std::logic_error("bignum size exceeded expected length");
×
1855
                                rr.insert(0, signature_length / 2 - rr.size(), '\0');
5✔
1856
                                rs.insert(0, signature_length / 2 - rs.size(), '\0');
5✔
1857
                                return rr + rs;
5✔
1858
                        }
6✔
1859

1860
                        std::string p1363_to_der_signature(const std::string& signature, std::error_code& ec) const {
23✔
1861
                                ec.clear();
23✔
1862
                                auto r = helper::raw2bn(signature.substr(0, signature.size() / 2), ec);
23✔
1863
                                if (ec) return {};
23✔
1864
                                auto s = helper::raw2bn(signature.substr(signature.size() / 2), ec);
23✔
1865
                                if (ec) return {};
23✔
1866

1867
                                ECDSA_SIG* psig;
1868
#ifdef JWT_OPENSSL_1_0_0
1869
                                ECDSA_SIG sig;
1870
                                sig.r = r.get();
1871
                                sig.s = s.get();
1872
                                psig = &sig;
1873
#else
1874
                                std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(ECDSA_SIG_new(), ECDSA_SIG_free);
23✔
1875
                                if (!sig) {
23✔
1876
                                        ec = error::signature_verification_error::create_context_failed;
1✔
1877
                                        return {};
1✔
1878
                                }
1879
                                ECDSA_SIG_set0(sig.get(), r.release(), s.release());
22✔
1880
                                psig = sig.get();
22✔
1881
#endif
1882

1883
                                int length = i2d_ECDSA_SIG(psig, nullptr);
22✔
1884
                                if (length < 0) {
22✔
1885
                                        ec = error::signature_verification_error::signature_encoding_failed;
1✔
1886
                                        return {};
1✔
1887
                                }
1888
                                std::string der_signature(length, '\0');
21✔
1889
                                unsigned char* psbuffer = (unsigned char*)der_signature.data();
21✔
1890
                                length = i2d_ECDSA_SIG(psig, &psbuffer);
21✔
1891
                                if (length < 0) {
21✔
1892
                                        ec = error::signature_verification_error::signature_encoding_failed;
1✔
1893
                                        return {};
1✔
1894
                                }
1895
                                der_signature.resize(length);
20✔
1896
                                return der_signature;
20✔
1897
                        }
23✔
1898

1899
                        /// OpenSSL struct containing keys
1900
                        helper::evp_pkey_handle pkey;
1901
                        /// Hash generator function
1902
                        const EVP_MD* (*md)();
1903
                        /// algorithm's name
1904
                        const std::string alg_name;
1905
                        /// Length of the resulting signature
1906
                        const size_t signature_length;
1907
                };
1908

1909
#if !defined(JWT_OPENSSL_1_0_0) && !defined(JWT_OPENSSL_1_1_0)
1910
                /**
1911
                 * \brief Base class for EdDSA family of algorithms
1912
                 *
1913
                 * https://tools.ietf.org/html/rfc8032
1914
                 *
1915
                 * The EdDSA algorithms were introduced in [OpenSSL v1.1.1](https://www.openssl.org/news/openssl-1.1.1-notes.html),
1916
                 * so these algorithms are only available when building against this version or higher.
1917
                 * LibreSSL added EdDSA (Ed25519) functionality in [LibreSSL 3.7.1](https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-3.7.1-relnotes.txt)
1918
                 */
1919
                struct eddsa {
1920
                        /**
1921
                         * Construct new eddsa algorithm
1922
                         * \param public_key EdDSA public key in PEM format
1923
                         * \param private_key EdDSA private key or empty string if not available. If empty, signing will always
1924
                         * fail.
1925
                         * \param public_key_password Password to decrypt public key pem.
1926
                         * \param private_key_password Password
1927
                         * to decrypt private key pem.
1928
                         * \param name Name of the algorithm
1929
                         */
1930
                        eddsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
27✔
1931
                                  const std::string& private_key_password, std::string name)
1932
                                : alg_name(std::move(name)) {
27✔
1933
                                if (!private_key.empty()) {
27✔
1934
                                        pkey = helper::load_private_key_from_string(private_key, private_key_password);
10✔
1935
                                } else if (!public_key.empty()) {
17✔
1936
                                        pkey = helper::load_public_key_from_string(public_key, public_key_password);
16✔
1937
                                } else
1938
                                        throw error::ecdsa_exception(error::ecdsa_error::load_key_bio_read);
1✔
1939
                        }
41✔
1940
                        /**
1941
                         * Sign jwt data
1942
                         * \param data The data to sign
1943
                         * \param ec error_code filled with details on error
1944
                         * \return EdDSA signature for the given data
1945
                         */
1946
                        std::string sign(const std::string& data, std::error_code& ec) const {
6✔
1947
                                ec.clear();
6✔
1948
                                auto ctx = helper::make_evp_md_ctx();
6✔
1949
                                if (!ctx) {
6✔
1950
                                        ec = error::signature_generation_error::create_context_failed;
1✔
1951
                                        return {};
1✔
1952
                                }
1953
                                if (!EVP_DigestSignInit(ctx.get(), nullptr, nullptr, nullptr, pkey.get())) {
5✔
1954
                                        ec = error::signature_generation_error::signinit_failed;
1✔
1955
                                        return {};
1✔
1956
                                }
1957

1958
                                size_t len = EVP_PKEY_size(pkey.get());
4✔
1959
                                std::string res(len, '\0');
4✔
1960

1961
// LibreSSL and OpenSSL, require the oneshot EVP_DigestSign API.
1962
// wolfSSL uses the Update/Final pattern.
1963
#if defined(LIBWOLFSSL_VERSION_HEX)
1964
                                ERR_clear_error();
1965
                                if (EVP_DigestSignUpdate(ctx.get(), reinterpret_cast<const unsigned char*>(data.data()), data.size()) !=
1966
                                        1) {
1967
                                        std::cout << ERR_error_string(ERR_get_error(), NULL) << '\n';
1968
                                        ec = error::signature_generation_error::signupdate_failed;
1969
                                        return {};
1970
                                }
1971
                                if (EVP_DigestSignFinal(ctx.get(), reinterpret_cast<unsigned char*>(&res[0]), &len) != 1) {
1972
                                        ec = error::signature_generation_error::signfinal_failed;
1973
                                        return {};
1974
                                }
1975
#else
1976
                                if (EVP_DigestSign(ctx.get(), reinterpret_cast<unsigned char*>(&res[0]), &len,
8✔
1977
                                                                   reinterpret_cast<const unsigned char*>(data.data()), data.size()) != 1) {
8✔
1978
                                        ec = error::signature_generation_error::signfinal_failed;
1✔
1979
                                        return {};
1✔
1980
                                }
1981
#endif
1982

1983
                                res.resize(len);
3✔
1984
                                return res;
3✔
1985
                        }
6✔
1986

1987
                        /**
1988
                         * Check if signature is valid
1989
                         * \param data The data to check signature against
1990
                         * \param signature Signature provided by the jwt
1991
                         * \param ec Filled with details on error
1992
                         */
1993
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
12✔
1994
                                ec.clear();
12✔
1995
                                auto ctx = helper::make_evp_md_ctx();
12✔
1996
                                if (!ctx) {
12✔
1997
                                        ec = error::signature_verification_error::create_context_failed;
1✔
1998
                                        return;
1✔
1999
                                }
2000
                                if (!EVP_DigestVerifyInit(ctx.get(), nullptr, nullptr, nullptr, pkey.get())) {
11✔
2001
                                        ec = error::signature_verification_error::verifyinit_failed;
1✔
2002
                                        return;
1✔
2003
                                }
2004
// LibreSSL and OpenSSL, require the oneshot EVP_DigestVerify API.
2005
// wolfSSL uses the Update/Final pattern.
2006
#if defined(LIBWOLFSSL_VERSION_HEX)
2007
                                if (EVP_DigestVerifyUpdate(ctx.get(), reinterpret_cast<const unsigned char*>(data.data()),
2008
                                                                                   data.size()) != 1) {
2009
                                        ec = error::signature_verification_error::verifyupdate_failed;
2010
                                        return;
2011
                                }
2012
                                if (EVP_DigestVerifyFinal(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
2013
                                                                                  signature.size()) != 1) {
2014
                                        ec = error::signature_verification_error::verifyfinal_failed;
2015
                                        return;
2016
                                }
2017
#else
2018
                                auto res = EVP_DigestVerify(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
20✔
2019
                                                                                        signature.size(), reinterpret_cast<const unsigned char*>(data.data()),
10✔
2020
                                                                                        data.size());
2021
                                if (res != 1) {
10✔
2022
                                        ec = error::signature_verification_error::verifyfinal_failed;
5✔
2023
                                        return;
5✔
2024
                                }
2025
#endif
2026
                        }
12✔
2027
                        /**
2028
                         * Returns the algorithm name provided to the constructor
2029
                         * \return algorithm's name
2030
                         */
2031
                        std::string name() const { return alg_name; }
10✔
2032

2033
                private:
2034
                        /// OpenSSL struct containing keys
2035
                        helper::evp_pkey_handle pkey;
2036
                        /// algorithm's name
2037
                        const std::string alg_name;
2038
                };
2039
#endif
2040
                /**
2041
                 * \brief Base class for PSS-RSA family of algorithms
2042
                 */
2043
                struct pss {
2044
                        /**
2045
                         * Construct new pss algorithm
2046
                         * \param public_key RSA public key in PEM format
2047
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2048
                         * \param public_key_password Password to decrypt public key pem.
2049
                         * \param private_key_password Password to decrypt private key pem.
2050
                         * \param md Pointer to hash function
2051
                         * \param name Name of the algorithm
2052
                         */
2053
                        pss(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
10✔
2054
                                const std::string& private_key_password, const EVP_MD* (*md)(), std::string name)
2055
                                : md(md), alg_name(std::move(name)) {
10✔
2056
                                if (!private_key.empty()) {
10✔
2057
                                        pkey = helper::load_private_key_from_string(private_key, private_key_password);
7✔
2058
                                } else if (!public_key.empty()) {
3✔
2059
                                        pkey = helper::load_public_key_from_string(public_key, public_key_password);
2✔
2060
                                } else
2061
                                        throw error::rsa_exception(error::rsa_error::no_key_provided);
1✔
2062
                        }
11✔
2063

2064
                        /**
2065
                         * Sign jwt data
2066
                         * \param data The data to sign
2067
                         * \param ec error_code filled with details on error
2068
                         * \return ECDSA signature for the given data
2069
                         */
2070
                        std::string sign(const std::string& data, std::error_code& ec) const {
8✔
2071
                                ec.clear();
8✔
2072
                                auto md_ctx = helper::make_evp_md_ctx();
8✔
2073
                                if (!md_ctx) {
8✔
2074
                                        ec = error::signature_generation_error::create_context_failed;
1✔
2075
                                        return {};
1✔
2076
                                }
2077
                                EVP_PKEY_CTX* ctx = nullptr;
7✔
2078
                                if (EVP_DigestSignInit(md_ctx.get(), &ctx, md(), nullptr, pkey.get()) != 1) {
7✔
2079
                                        ec = error::signature_generation_error::signinit_failed;
1✔
2080
                                        return {};
1✔
2081
                                }
2082
                                if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
6✔
2083
                                        ec = error::signature_generation_error::rsa_padding_failed;
×
UNCOV
2084
                                        return {};
×
2085
                                }
2086
// wolfSSL does not require EVP_PKEY_CTX_set_rsa_pss_saltlen. The default behavior
2087
// sets the salt length to the hash length. Unlike OpenSSL which exposes this functionality.
2088
#ifndef LIBWOLFSSL_VERSION_HEX
2089
                                if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
6✔
2090
                                        ec = error::signature_generation_error::set_rsa_pss_saltlen_failed;
×
UNCOV
2091
                                        return {};
×
2092
                                }
2093
#endif
2094
                                if (EVP_DigestUpdate(md_ctx.get(), data.data(), static_cast<unsigned int>(data.size())) != 1) {
6✔
2095
                                        ec = error::signature_generation_error::digestupdate_failed;
1✔
2096
                                        return {};
1✔
2097
                                }
2098

2099
                                size_t size = EVP_PKEY_size(pkey.get());
5✔
2100
                                std::string res(size, 0x00);
5✔
2101
                                if (EVP_DigestSignFinal(
5✔
2102
                                                md_ctx.get(),
2103
                                                (unsigned char*)res.data(), // NOLINT(google-readability-casting) requires `const_cast`
5✔
2104
                                                &size) <= 0) {
5✔
2105
                                        ec = error::signature_generation_error::signfinal_failed;
1✔
2106
                                        return {};
1✔
2107
                                }
2108

2109
                                return res;
4✔
2110
                        }
8✔
2111

2112
                        /**
2113
                         * Check if signature is valid
2114
                         * \param data The data to check signature against
2115
                         * \param signature Signature provided by the jwt
2116
                         * \param ec Filled with error details
2117
                         */
2118
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
8✔
2119
                                ec.clear();
8✔
2120

2121
                                auto md_ctx = helper::make_evp_md_ctx();
8✔
2122
                                if (!md_ctx) {
8✔
2123
                                        ec = error::signature_verification_error::create_context_failed;
1✔
2124
                                        return;
1✔
2125
                                }
2126
                                EVP_PKEY_CTX* ctx = nullptr;
7✔
2127
                                if (EVP_DigestVerifyInit(md_ctx.get(), &ctx, md(), nullptr, pkey.get()) != 1) {
7✔
2128
                                        ec = error::signature_verification_error::verifyinit_failed;
1✔
2129
                                        return;
1✔
2130
                                }
2131
                                if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
6✔
2132
                                        ec = error::signature_generation_error::rsa_padding_failed;
×
UNCOV
2133
                                        return;
×
2134
                                }
2135
// wolfSSL does not require EVP_PKEY_CTX_set_rsa_pss_saltlen. The default behavior
2136
// sets the salt length to the hash length. Unlike OpenSSL which exposes this functionality.
2137
#ifndef LIBWOLFSSL_VERSION_HEX
2138
                                if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
6✔
2139
                                        ec = error::signature_verification_error::set_rsa_pss_saltlen_failed;
×
UNCOV
2140
                                        return;
×
2141
                                }
2142
#endif
2143
                                if (EVP_DigestUpdate(md_ctx.get(), data.data(), static_cast<unsigned int>(data.size())) != 1) {
6✔
2144
                                        ec = error::signature_verification_error::verifyupdate_failed;
1✔
2145
                                        return;
1✔
2146
                                }
2147

2148
                                if (EVP_DigestVerifyFinal(md_ctx.get(), (unsigned char*)signature.data(), signature.size()) <= 0) {
5✔
2149
                                        ec = error::signature_verification_error::verifyfinal_failed;
2✔
2150
                                        return;
2✔
2151
                                }
2152
                        }
8✔
2153
                        /**
2154
                         * Returns the algorithm name provided to the constructor
2155
                         * \return algorithm's name
2156
                         */
2157
                        std::string name() const { return alg_name; }
6✔
2158

2159
                private:
2160
                        /// OpenSSL structure containing keys
2161
                        helper::evp_pkey_handle pkey;
2162
                        /// Hash generator function
2163
                        const EVP_MD* (*md)();
2164
                        /// algorithm's name
2165
                        const std::string alg_name;
2166
                };
2167

2168
                /**
2169
                 * HS256 algorithm
2170
                 */
2171
                struct hs256 : public hmacsha {
2172
                        /**
2173
                         * Construct new instance of algorithm
2174
                         * \deprecated Using a character is not recommended and hardened applications should use BIGNUM
2175
                         * \param key HMAC signing key
2176
                         */
2177
                        explicit hs256(std::string key) : hmacsha(std::move(key), EVP_sha256, "HS256") {}
129✔
2178
                        /**
2179
                         * Construct new instance of algorithm
2180
                         * \param key HMAC signing key
2181
                         */
2182
                        explicit hs256(const BIGNUM* key) : hmacsha(key, EVP_sha256, "HS256") {}
9✔
2183
                };
2184
                /**
2185
                 * HS384 algorithm
2186
                 */
2187
                struct hs384 : public hmacsha {
2188
                        /**
2189
                         * Construct new instance of algorithm
2190
                         * \deprecated Using a character is not recommended and hardened applications should use BIGNUM
2191
                         * \param key HMAC signing key
2192
                         */
2193
                        explicit hs384(std::string key) : hmacsha(std::move(key), EVP_sha384, "HS384") {}
2194
                        /**
2195
                         * Construct new instance of algorithm
2196
                         * \param key HMAC signing key
2197
                         */
2198
                        explicit hs384(const BIGNUM* key) : hmacsha(key, EVP_sha384, "HS384") {}
2199
                };
2200
                /**
2201
                 * HS512 algorithm
2202
                 */
2203
                struct hs512 : public hmacsha {
2204
                        /**
2205
                         * Construct new instance of algorithm
2206
                         * \deprecated Using a character is not recommended and hardened applications should use BIGNUM
2207
                         * \param key HMAC signing key
2208
                         */
2209
                        explicit hs512(std::string key) : hmacsha(std::move(key), EVP_sha512, "HS512") {}
2210
                        /**
2211
                         * Construct new instance of algorithm
2212
                         *
2213
                         * This can be used to sign and verify tokens.
2214
                          * \snippet{trimleft} hs512.cpp use HMAC algo with BIGNUM
2215
                         *
2216
                         * \param key HMAC signing key
2217
                         */
2218
                        explicit hs512(const BIGNUM* key) : hmacsha(key, EVP_sha512, "HS512") {}
2219
                };
2220
                /**
2221
                 * RS256 algorithm.
2222
                 *
2223
                 * This data structure is used to describe the RSA256 and can be used to verify JWTs
2224
                 */
2225
                struct rs256 : public rsa {
2226
                        /**
2227
                         * \brief Construct new instance of algorithm
2228
                         *
2229
                         * \param public_key RSA public key in PEM format
2230
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2231
                         * \param public_key_password Password to decrypt public key pem.
2232
                         * \param private_key_password Password to decrypt private key pem.
2233
                         */
2234
                        explicit rs256(const std::string& public_key, const std::string& private_key = "",
11✔
2235
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2236
                                : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "RS256") {}
33✔
2237
                };
2238
                /**
2239
                 * RS384 algorithm
2240
                 */
2241
                struct rs384 : public rsa {
2242
                        /**
2243
                         * Construct new instance of algorithm
2244
                         * \param public_key RSA public key in PEM format
2245
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2246
                         * \param public_key_password Password to decrypt public key pem.
2247
                         * \param private_key_password Password to decrypt private key pem.
2248
                         */
2249
                        explicit rs384(const std::string& public_key, const std::string& private_key = "",
2250
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2251
                                : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "RS384") {}
2252
                };
2253
                /**
2254
                 * RS512 algorithm
2255
                 */
2256
                struct rs512 : public rsa {
2257
                        /**
2258
                         * Construct new instance of algorithm
2259
                         * \param public_key RSA public key in PEM format
2260
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2261
                         * \param public_key_password Password to decrypt public key pem.
2262
                         * \param private_key_password Password to decrypt private key pem.
2263
                         */
2264
                        explicit rs512(const std::string& public_key, const std::string& private_key = "",
5✔
2265
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2266
                                : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "RS512") {}
15✔
2267
                };
2268
                /**
2269
                 * ES256 algorithm
2270
                 */
2271
                struct es256 : public ecdsa {
2272
                        /**
2273
                         * Construct new instance of algorithm
2274
                         * \param public_key ECDSA public key in PEM format
2275
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always
2276
                         * fail.
2277
                         * \param public_key_password Password to decrypt public key pem.
2278
                         * \param private_key_password Password
2279
                         * to decrypt private key pem.
2280
                         */
2281
                        explicit es256(const std::string& public_key, const std::string& private_key = "",
39✔
2282
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2283
                                : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256", 64) {}
117✔
2284
                };
2285
                /**
2286
                 * ES384 algorithm
2287
                 */
2288
                struct es384 : public ecdsa {
2289
                        /**
2290
                         * Construct new instance of algorithm
2291
                         * \param public_key ECDSA public key in PEM format
2292
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always
2293
                         * fail.
2294
                         * \param public_key_password Password to decrypt public key pem.
2295
                         * \param private_key_password Password
2296
                         * to decrypt private key pem.
2297
                         */
2298
                        explicit es384(const std::string& public_key, const std::string& private_key = "",
15✔
2299
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2300
                                : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "ES384", 96) {}
45✔
2301
                };
2302
                /**
2303
                 * ES512 algorithm
2304
                 */
2305
                struct es512 : public ecdsa {
2306
                        /**
2307
                         * Construct new instance of algorithm
2308
                         * \param public_key ECDSA public key in PEM format
2309
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always
2310
                         * fail.
2311
                         * \param public_key_password Password to decrypt public key pem.
2312
                         * \param private_key_password Password
2313
                         * to decrypt private key pem.
2314
                         */
2315
                        explicit es512(const std::string& public_key, const std::string& private_key = "",
15✔
2316
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2317
                                : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "ES512", 132) {}
45✔
2318
                };
2319
                /**
2320
                 * ES256K algorithm
2321
                 */
2322
                struct es256k : public ecdsa {
2323
                        /**
2324
                         * Construct new instance of algorithm
2325
                         * \param public_key ECDSA public key in PEM format
2326
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always
2327
                         * fail.
2328
                         * \param public_key_password Password to decrypt public key pem.
2329
                         * \param private_key_password Password to decrypt private key pem.
2330
                         */
2331
                        explicit es256k(const std::string& public_key, const std::string& private_key = "",
2332
                                                        const std::string& public_key_password = "", const std::string& private_key_password = "")
2333
                                : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256K", 64) {}
2334
                };
2335

2336
#if !defined(JWT_OPENSSL_1_0_0) && !defined(JWT_OPENSSL_1_1_0)
2337
                /**
2338
                 * Ed25519 algorithm
2339
                 *
2340
                 * https://en.wikipedia.org/wiki/EdDSA#Ed25519
2341
                 *
2342
                 * Requires at least OpenSSL 1.1.1 or LibreSSL 3.7.1.
2343
                 */
2344
                struct ed25519 : public eddsa {
2345
                        /**
2346
                         * Construct new instance of algorithm
2347
                         * \param public_key Ed25519 public key in PEM format
2348
                         * \param private_key Ed25519 private key or empty string if not available. If empty, signing will always
2349
                         * fail.
2350
                         * \param public_key_password Password to decrypt public key pem.
2351
                         * \param private_key_password Password
2352
                         * to decrypt private key pem.
2353
                         */
2354
                        explicit ed25519(const std::string& public_key, const std::string& private_key = "",
22✔
2355
                                                         const std::string& public_key_password = "", const std::string& private_key_password = "")
2356
                                : eddsa(public_key, private_key, public_key_password, private_key_password, "EdDSA") {}
66✔
2357
                };
2358

2359
#if !defined(LIBRESSL_VERSION_NUMBER)
2360
                /**
2361
                 * Ed448 algorithm
2362
                 *
2363
                 * https://en.wikipedia.org/wiki/EdDSA#Ed448
2364
                 *
2365
                 * Requires at least OpenSSL 1.1.1. Note: Not supported by LibreSSL.
2366
                 */
2367
                struct ed448 : public eddsa {
2368
                        /**
2369
                         * Construct new instance of algorithm
2370
                         * \param public_key Ed448 public key in PEM format
2371
                         * \param private_key Ed448 private key or empty string if not available. If empty, signing will always
2372
                         * fail.
2373
                         * \param public_key_password Password to decrypt public key pem.
2374
                         * \param private_key_password Password
2375
                         * to decrypt private key pem.
2376
                         */
2377
                        explicit ed448(const std::string& public_key, const std::string& private_key = "",
5✔
2378
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2379
                                : eddsa(public_key, private_key, public_key_password, private_key_password, "EdDSA") {}
15✔
2380
                };
2381
#endif // !LIBRESSL_VERSION_NUMBER
2382
#endif // !JWT_OPENSSL_1_0_0 && !JWT_OPENSSL_1_1_0
2383

2384
                /**
2385
                 * PS256 algorithm
2386
                 */
2387
                struct ps256 : public pss {
2388
                        /**
2389
                         * Construct new instance of algorithm
2390
                         * \param public_key RSA public key in PEM format
2391
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2392
                         * \param public_key_password Password to decrypt public key pem.
2393
                         * \param private_key_password Password to decrypt private key pem.
2394
                         */
2395
                        explicit ps256(const std::string& public_key, const std::string& private_key = "",
8✔
2396
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2397
                                : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "PS256") {}
24✔
2398
                };
2399
                /**
2400
                 * PS384 algorithm
2401
                 */
2402
                struct ps384 : public pss {
2403
                        /**
2404
                         * Construct new instance of algorithm
2405
                         * \param public_key RSA public key in PEM format
2406
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2407
                         * \param public_key_password Password to decrypt public key pem.
2408
                         * \param private_key_password Password to decrypt private key pem.
2409
                         */
2410
                        explicit ps384(const std::string& public_key, const std::string& private_key = "",
1✔
2411
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2412
                                : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "PS384") {}
3✔
2413
                };
2414
                /**
2415
                 * PS512 algorithm
2416
                 */
2417
                struct ps512 : public pss {
2418
                        /**
2419
                         * Construct new instance of algorithm
2420
                         * \param public_key RSA public key in PEM format
2421
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2422
                         * \param public_key_password Password to decrypt public key pem.
2423
                         * \param private_key_password Password to decrypt private key pem.
2424
                         */
2425
                        explicit ps512(const std::string& public_key, const std::string& private_key = "",
1✔
2426
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2427
                                : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "PS512") {}
3✔
2428
                };
2429
        } // namespace algorithm
2430

2431
        /**
2432
         * \brief JSON Abstractions for working with any library
2433
         */
2434
        namespace json {
2435
                /**
2436
                 * \brief Categories for the various JSON types used in JWTs
2437
                 *
2438
                 * This enum is to abstract the third party underlying types and allows the library
2439
                 * to identify the different structures and reason about them without needing a "concept"
2440
                 * to capture that defintion to compare against a concrete type.
2441
                 */
2442
                enum class type { boolean, integer, number, string, array, object };
2443
        } // namespace json
2444

2445
        namespace details {
2446
#ifdef __cpp_lib_void_t
2447
                template<typename... Ts>
2448
                using void_t = std::void_t<Ts...>;
2449
#else
2450
                // https://en.cppreference.com/w/cpp/types/void_t
2451
                template<typename... Ts>
2452
                struct make_void {
2453
                        using type = void;
2454
                };
2455

2456
                template<typename... Ts>
2457
                using void_t = typename make_void<Ts...>::type;
2458
#endif
2459

2460
#ifdef __cpp_lib_experimental_detect
2461
                template<template<typename...> class _Op, typename... _Args>
2462
                using is_detected = std::experimental::is_detected<_Op, _Args...>;
2463
#else
2464
                struct nonesuch {
2465
                        nonesuch() = delete;
2466
                        ~nonesuch() = delete;
2467
                        nonesuch(nonesuch const&) = delete;
2468
                        nonesuch(nonesuch const&&) = delete;
2469
                        void operator=(nonesuch const&) = delete;
2470
                        void operator=(nonesuch&&) = delete;
2471
                };
2472

2473
                // https://en.cppreference.com/w/cpp/experimental/is_detected
2474
                template<class Default, class AlwaysVoid, template<class...> class Op, class... Args>
2475
                struct detector {
2476
                        using value = std::false_type;
2477
                        using type = Default;
2478
                };
2479

2480
                template<class Default, template<class...> class Op, class... Args>
2481
                struct detector<Default, void_t<Op<Args...>>, Op, Args...> {
2482
                        using value = std::true_type;
2483
                        using type = Op<Args...>;
2484
                };
2485

2486
                template<template<class...> class Op, class... Args>
2487
                using is_detected = typename detector<nonesuch, void, Op, Args...>::value;
2488
#endif
2489

2490
                template<typename T, typename Signature>
2491
                using is_signature = typename std::is_same<T, Signature>;
2492

2493
                template<typename traits_type, template<typename...> class Op, typename Signature>
2494
                struct is_function_signature_detected {
2495
                        using type = Op<traits_type>;
2496
                        static constexpr auto value = is_detected<Op, traits_type>::value && std::is_function<type>::value &&
2497
                                                                                  is_signature<type, Signature>::value;
2498
                };
2499

2500
                template<typename traits_type, typename value_type>
2501
                struct supports_get_type {
2502
                        template<typename T>
2503
                        using get_type_t = decltype(T::get_type);
2504

2505
                        static constexpr auto value =
2506
                                is_function_signature_detected<traits_type, get_type_t, json::type(const value_type&)>::value;
2507

2508
                        // Internal assertions for better feedback
2509
                        static_assert(value, "traits implementation must provide `jwt::json::type get_type(const value_type&)`");
2510
                };
2511

2512
#define JWT_CPP_JSON_TYPE_TYPE(TYPE) json_##TYPE_type
2513
#define JWT_CPP_AS_TYPE_T(TYPE) as_##TYPE_t
2514
#define JWT_CPP_SUPPORTS_AS(TYPE)                                                                                      \
2515
        template<typename traits_type, typename value_type, typename JWT_CPP_JSON_TYPE_TYPE(TYPE)>                         \
2516
        struct supports_as_##TYPE {                                                                                        \
2517
                template<typename T>                                                                                           \
2518
                using JWT_CPP_AS_TYPE_T(TYPE) = decltype(T::as_##TYPE);                                                        \
2519
                                                                                                                       \
2520
                static constexpr auto value =                                                                                  \
2521
                        is_function_signature_detected<traits_type, JWT_CPP_AS_TYPE_T(TYPE),                                       \
2522
                                                                                   JWT_CPP_JSON_TYPE_TYPE(TYPE)(const value_type&)>::value;                    \
2523
                                                                                                                       \
2524
                static_assert(value, "traits implementation must provide `" #TYPE "_type as_" #TYPE "(const value_type&)`");   \
2525
        }
2526

2527
                JWT_CPP_SUPPORTS_AS(object);
2528
                JWT_CPP_SUPPORTS_AS(array);
2529
                JWT_CPP_SUPPORTS_AS(string);
2530
                JWT_CPP_SUPPORTS_AS(number);
2531
                JWT_CPP_SUPPORTS_AS(integer);
2532
                JWT_CPP_SUPPORTS_AS(boolean);
2533

2534
#undef JWT_CPP_JSON_TYPE_TYPE
2535
#undef JWT_CPP_AS_TYPE_T
2536
#undef JWT_CPP_SUPPORTS_AS
2537

2538
                template<typename traits>
2539
                struct is_valid_traits {
2540
                        static constexpr auto value =
2541
                                supports_get_type<traits, typename traits::value_type>::value &&
2542
                                supports_as_object<traits, typename traits::value_type, typename traits::object_type>::value &&
2543
                                supports_as_array<traits, typename traits::value_type, typename traits::array_type>::value &&
2544
                                supports_as_string<traits, typename traits::value_type, typename traits::string_type>::value &&
2545
                                supports_as_number<traits, typename traits::value_type, typename traits::number_type>::value &&
2546
                                supports_as_integer<traits, typename traits::value_type, typename traits::integer_type>::value &&
2547
                                supports_as_boolean<traits, typename traits::value_type, typename traits::boolean_type>::value;
2548
                };
2549

2550
                template<typename value_type>
2551
                struct is_valid_json_value {
2552
                        static constexpr auto value =
2553
                                std::is_default_constructible<value_type>::value &&
2554
                                std::is_constructible<value_type, const value_type&>::value && // a more generic is_copy_constructible
2555
                                std::is_move_constructible<value_type>::value && std::is_assignable<value_type, value_type>::value &&
2556
                                std::is_copy_assignable<value_type>::value && std::is_move_assignable<value_type>::value;
2557
                        // TODO(prince-chrismc): Stream operators
2558
                };
2559

2560
                // https://stackoverflow.com/a/53967057/8480874
2561
                template<typename T, typename = void>
2562
                struct is_iterable : std::false_type {};
2563

2564
                template<typename T>
2565
                struct is_iterable<T, void_t<decltype(std::begin(std::declval<T>())), decltype(std::end(std::declval<T>())),
2566
#if __cplusplus > 201402L
2567
                                                                         decltype(std::cbegin(std::declval<T>())), decltype(std::cend(std::declval<T>()))
2568
#else
2569
                                                                         decltype(std::begin(std::declval<const T>())),
2570
                                                                         decltype(std::end(std::declval<const T>()))
2571
#endif
2572
                                                                         >> : std::true_type {
2573
                };
2574

2575
#if __cplusplus > 201703L
2576
                template<typename T>
2577
                inline constexpr bool is_iterable_v = is_iterable<T>::value;
2578
#endif
2579

2580
                template<typename object_type, typename string_type>
2581
                using is_count_signature = typename std::is_integral<decltype(std::declval<const object_type>().count(
2582
                        std::declval<const string_type>()))>;
2583

2584
                template<typename object_type, typename string_type, typename = void>
2585
                struct is_subcription_operator_signature : std::false_type {};
2586

2587
                template<typename object_type, typename string_type>
2588
                struct is_subcription_operator_signature<
2589
                        object_type, string_type,
2590
                        void_t<decltype(std::declval<object_type>().operator[](std::declval<string_type>()))>> : std::true_type {
2591
                        // TODO(prince-chrismc): I am not convienced this is meaningful anymore
2592
                        static_assert(
2593
                                value,
2594
                                "object_type must implementate the subscription operator '[]' taking string_type as an argument");
2595
                };
2596

2597
                template<typename object_type, typename value_type, typename string_type>
2598
                using is_at_const_signature =
2599
                        typename std::is_same<decltype(std::declval<const object_type>().at(std::declval<const string_type>())),
2600
                                                                  const value_type&>;
2601

2602
                template<typename value_type, typename string_type, typename object_type>
2603
                struct is_valid_json_object {
2604
                        template<typename T>
2605
                        using mapped_type_t = typename T::mapped_type;
2606
                        template<typename T>
2607
                        using key_type_t = typename T::key_type;
2608
                        template<typename T>
2609
                        using iterator_t = typename T::iterator;
2610
                        template<typename T>
2611
                        using const_iterator_t = typename T::const_iterator;
2612

2613
                        static constexpr auto value =
2614
                                std::is_constructible<value_type, object_type>::value &&
2615
                                is_detected<mapped_type_t, object_type>::value &&
2616
                                std::is_same<typename object_type::mapped_type, value_type>::value &&
2617
                                is_detected<key_type_t, object_type>::value &&
2618
                                (std::is_same<typename object_type::key_type, string_type>::value ||
2619
                                 std::is_constructible<typename object_type::key_type, string_type>::value) &&
2620
                                is_detected<iterator_t, object_type>::value && is_detected<const_iterator_t, object_type>::value &&
2621
                                is_iterable<object_type>::value && is_count_signature<object_type, string_type>::value &&
2622
                                is_subcription_operator_signature<object_type, string_type>::value &&
2623
                                is_at_const_signature<object_type, value_type, string_type>::value;
2624
                };
2625

2626
                template<typename value_type, typename array_type>
2627
                struct is_valid_json_array {
2628
                        template<typename T>
2629
                        using value_type_t = typename T::value_type;
2630
                        using front_base_type = typename std::decay<decltype(std::declval<array_type>().front())>::type;
2631

2632
                        static constexpr auto value = std::is_constructible<value_type, array_type>::value &&
2633
                                                                                  is_iterable<array_type>::value &&
2634
                                                                                  is_detected<value_type_t, array_type>::value &&
2635
                                                                                  std::is_same<typename array_type::value_type, value_type>::value &&
2636
                                                                                  std::is_same<front_base_type, value_type>::value;
2637
                };
2638

2639
                template<typename string_type, typename integer_type>
2640
                using is_substr_start_end_index_signature =
2641
                        typename std::is_same<decltype(std::declval<string_type>().substr(
2642
                                                                          static_cast<size_t>(std::declval<integer_type>()),
2643
                                                                          static_cast<size_t>(std::declval<integer_type>()))),
2644
                                                                  string_type>;
2645

2646
                template<typename string_type, typename integer_type>
2647
                using is_substr_start_index_signature =
2648
                        typename std::is_same<decltype(std::declval<string_type>().substr(
2649
                                                                          static_cast<size_t>(std::declval<integer_type>()))),
2650
                                                                  string_type>;
2651

2652
                template<typename string_type>
2653
                using is_std_operate_plus_signature =
2654
                        typename std::is_same<decltype(std::operator+(std::declval<string_type>(), std::declval<string_type>())),
2655
                                                                  string_type>;
2656

2657
                template<typename value_type, typename string_type, typename integer_type>
2658
                struct is_valid_json_string {
2659
                        static constexpr auto substr = is_substr_start_end_index_signature<string_type, integer_type>::value &&
2660
                                                                                   is_substr_start_index_signature<string_type, integer_type>::value;
2661
                        static_assert(substr, "string_type must have a substr method taking only a start index and an overload "
2662
                                                                  "taking a start and end index, both must return a string_type");
2663

2664
                        static constexpr auto operator_plus = is_std_operate_plus_signature<string_type>::value;
2665
                        static_assert(operator_plus,
2666
                                                  "string_type must have a '+' operator implemented which returns the concatenated string");
2667

2668
                        static constexpr auto value =
2669
                                std::is_constructible<value_type, string_type>::value && substr && operator_plus;
2670
                };
2671

2672
                template<typename value_type, typename number_type>
2673
                struct is_valid_json_number {
2674
                        static constexpr auto value =
2675
                                std::is_floating_point<number_type>::value && std::is_constructible<value_type, number_type>::value;
2676
                };
2677

2678
                template<typename value_type, typename integer_type>
2679
                struct is_valid_json_integer {
2680
                        static constexpr auto value = std::is_signed<integer_type>::value &&
2681
                                                                                  !std::is_floating_point<integer_type>::value &&
2682
                                                                                  std::is_constructible<value_type, integer_type>::value;
2683
                };
2684
                template<typename value_type, typename boolean_type>
2685
                struct is_valid_json_boolean {
2686
                        static constexpr auto value = std::is_convertible<boolean_type, bool>::value &&
2687
                                                                                  std::is_constructible<value_type, boolean_type>::value;
2688
                };
2689

2690
                template<typename value_type, typename object_type, typename array_type, typename string_type,
2691
                                 typename number_type, typename integer_type, typename boolean_type>
2692
                struct is_valid_json_types {
2693
                        // Internal assertions for better feedback
2694
                        static_assert(is_valid_json_value<value_type>::value,
2695
                                                  "value_type must meet basic requirements, default constructor, copyable, moveable");
2696
                        static_assert(is_valid_json_object<value_type, string_type, object_type>::value,
2697
                                                  "object_type must be a string_type to value_type container");
2698
                        static_assert(is_valid_json_array<value_type, array_type>::value,
2699
                                                  "array_type must be a container of value_type");
2700

2701
                        static constexpr auto value = is_valid_json_value<value_type>::value &&
2702
                                                                                  is_valid_json_object<value_type, string_type, object_type>::value &&
2703
                                                                                  is_valid_json_array<value_type, array_type>::value &&
2704
                                                                                  is_valid_json_string<value_type, string_type, integer_type>::value &&
2705
                                                                                  is_valid_json_number<value_type, number_type>::value &&
2706
                                                                                  is_valid_json_integer<value_type, integer_type>::value &&
2707
                                                                                  is_valid_json_boolean<value_type, boolean_type>::value;
2708
                };
2709
        } // namespace details
2710

2711
        /**
2712
         * \brief a class to store a generic JSON value as claim
2713
         *
2714
         * \tparam json_traits : JSON implementation traits
2715
         *
2716
         * \see [RFC 7519: JSON Web Token (JWT)](https://tools.ietf.org/html/rfc7519)
2717
         */
2718
        template<typename json_traits>
2719
        class basic_claim {
2720
                /**
2721
                 * The reason behind this is to provide an expressive abstraction without
2722
                 * over complicating the API. For more information take the time to read
2723
                 * https://github.com/nlohmann/json/issues/774. It maybe be expanded to
2724
                 * support custom string types.
2725
                 */
2726
                static_assert(std::is_same<typename json_traits::string_type, std::string>::value ||
2727
                                                  std::is_convertible<typename json_traits::string_type, std::string>::value ||
2728
                                                  std::is_constructible<typename json_traits::string_type, std::string>::value,
2729
                                          "string_type must be a std::string, convertible to a std::string, or construct a std::string.");
2730

2731
                static_assert(
2732
                        details::is_valid_json_types<typename json_traits::value_type, typename json_traits::object_type,
2733
                                                                                 typename json_traits::array_type, typename json_traits::string_type,
2734
                                                                                 typename json_traits::number_type, typename json_traits::integer_type,
2735
                                                                                 typename json_traits::boolean_type>::value,
2736
                        "must satisfy json container requirements");
2737
                static_assert(details::is_valid_traits<json_traits>::value, "traits must satisfy requirements");
2738

2739
                typename json_traits::value_type val;
2740

2741
        public:
2742
                /**
2743
                 * Order list of strings
2744
                 */
2745
                using set_t = std::set<typename json_traits::string_type>;
2746

2747
                basic_claim() = default;
16✔
2748
                basic_claim(const basic_claim&) = default;
238✔
2749
                basic_claim(basic_claim&&) = default;
47✔
2750
                basic_claim& operator=(const basic_claim&) = default;
2751
                basic_claim& operator=(basic_claim&&) = default;
2752
                ~basic_claim() = default;
652✔
2753

2754
                JWT_CLAIM_EXPLICIT basic_claim(typename json_traits::string_type s) : val(std::move(s)) {}
50✔
2755
                JWT_CLAIM_EXPLICIT basic_claim(const date& d)
30✔
2756
                        : val(typename json_traits::integer_type(
36✔
2757
                                  std::chrono::duration_cast<std::chrono::seconds>(d.time_since_epoch()).count())) {}
60✔
2758
                JWT_CLAIM_EXPLICIT basic_claim(typename json_traits::array_type a) : val(std::move(a)) {}
2759
                JWT_CLAIM_EXPLICIT basic_claim(typename json_traits::value_type v) : val(std::move(v)) {}
258✔
2760
                JWT_CLAIM_EXPLICIT basic_claim(const set_t& s) : val(typename json_traits::array_type(s.begin(), s.end())) {}
6✔
2761
                template<typename Iterator>
2762
                basic_claim(Iterator begin, Iterator end) : val(typename json_traits::array_type(begin, end)) {}
15✔
2763

2764
                /**
2765
                 * Get wrapped JSON value
2766
                 * \return Wrapped JSON value
2767
                 */
2768
                typename json_traits::value_type to_json() const { return val; }
56✔
2769

2770
                /**
2771
                 * Parse input stream into underlying JSON value
2772
                 * \return input stream
2773
                 */
2774
                std::istream& operator>>(std::istream& is) { return is >> val; }
8✔
2775

2776
                /**
2777
                 * Serialize claim to output stream from wrapped JSON value
2778
                 * \return output stream
2779
                 */
2780
                std::ostream& operator<<(std::ostream& os) { return os << val; }
2781

2782
                /**
2783
                 * Get type of contained JSON value
2784
                 * \return Type
2785
                 * \throw std::logic_error An internal error occurred
2786
                 */
2787
                json::type get_type() const { return json_traits::get_type(val); }
211✔
2788

2789
                /**
2790
                 * Get the contained JSON value as a string
2791
                 * \return content as string
2792
                 * \throw std::bad_cast Content was not a string
2793
                 */
2794
                typename json_traits::string_type as_string() const { return json_traits::as_string(val); }
220✔
2795

2796
                /**
2797
                 * \brief Get the contained JSON value as a date
2798
                 *
2799
                 * If the value is a decimal, it is rounded to the closest integer
2800
                 *
2801
                 * \return content as date
2802
                 * \throw std::bad_cast Content was not a date
2803
                 */
2804
                date as_date() const {
45✔
2805
                        using std::chrono::system_clock;
2806
                        if (get_type() == json::type::number)
45✔
UNCOV
2807
                                return date(std::chrono::seconds(static_cast<int64_t>(std::llround(as_number()))));
×
2808
                        return date(std::chrono::seconds(as_integer()));
45✔
2809
                }
2810

2811
                /**
2812
                 * Get the contained JSON value as an array
2813
                 * \return content as array
2814
                 * \throw std::bad_cast Content was not an array
2815
                 */
2816
                typename json_traits::array_type as_array() const { return json_traits::as_array(val); }
8✔
2817

2818
                /**
2819
                 * Get the contained JSON value as a set of strings
2820
                 * \return content as set of strings
2821
                 * \throw std::bad_cast Content was not an array of string
2822
                 */
2823
                set_t as_set() const {
1✔
2824
                        set_t res;
1✔
2825
                        for (const auto& e : json_traits::as_array(val)) {
3✔
2826
                                res.insert(json_traits::as_string(e));
2✔
2827
                        }
2828
                        return res;
1✔
UNCOV
2829
                }
×
2830

2831
                /**
2832
                 * Get the contained JSON value as an integer
2833
                 * \return content as int
2834
                 * \throw std::bad_cast Content was not an int
2835
                 */
2836
                typename json_traits::integer_type as_integer() const { return json_traits::as_integer(val); }
47✔
2837

2838
                /**
2839
                 * Get the contained JSON value as a bool
2840
                 * \return content as bool
2841
                 * \throw std::bad_cast Content was not a bool
2842
                 */
2843
                typename json_traits::boolean_type as_boolean() const { return json_traits::as_boolean(val); }
1✔
2844

2845
                /**
2846
                 * Get the contained JSON value as a number
2847
                 * \return content as double
2848
                 * \throw std::bad_cast Content was not a number
2849
                 */
2850
                typename json_traits::number_type as_number() const { return json_traits::as_number(val); }
1✔
2851
        };
2852

2853
        namespace error {
2854
                /**
2855
                 * Attempt to parse JSON was unsuccessful
2856
                 */
2857
                struct invalid_json_exception : public std::runtime_error {
2858
                        invalid_json_exception() : runtime_error("invalid json") {}
3✔
2859
                };
2860
                /**
2861
                 * Attempt to access claim was unsuccessful
2862
                 */
2863
                struct claim_not_present_exception : public std::out_of_range {
2864
                        claim_not_present_exception() : out_of_range("claim not found") {}
6✔
2865
                };
2866
        } // namespace error
2867

2868
        namespace details {
2869
                template<typename json_traits>
2870
                struct map_of_claims {
2871
                        typename json_traits::object_type claims;
2872
                        using basic_claim_t = basic_claim<json_traits>;
2873
                        using iterator = typename json_traits::object_type::iterator;
2874
                        using const_iterator = typename json_traits::object_type::const_iterator;
2875

2876
                        map_of_claims() = default;
176✔
2877
                        map_of_claims(const map_of_claims&) = default;
22✔
2878
                        map_of_claims(map_of_claims&&) = default;
2879
                        map_of_claims& operator=(const map_of_claims&) = default;
2880
                        map_of_claims& operator=(map_of_claims&&) = default;
168✔
2881

2882
                        map_of_claims(typename json_traits::object_type json) : claims(std::move(json)) {}
178✔
2883

2884
                        iterator begin() { return claims.begin(); }
2885
                        iterator end() { return claims.end(); }
2886
                        const_iterator cbegin() const { return claims.begin(); }
2887
                        const_iterator cend() const { return claims.end(); }
2888
                        const_iterator begin() const { return claims.begin(); }
2889
                        const_iterator end() const { return claims.end(); }
2890

2891
                        /**
2892
                         * \brief Parse a JSON string into a map of claims
2893
                         *
2894
                         * The implication is that a "map of claims" is identic to a JSON object
2895
                         *
2896
                         * \param str JSON data to be parse as an object
2897
                         * \return content as JSON object
2898
                         */
2899
                        static typename json_traits::object_type parse_claims(const typename json_traits::string_type& str) {
172✔
2900
                                typename json_traits::value_type val;
172✔
2901
                                if (!json_traits::parse(val, str)) throw error::invalid_json_exception();
172✔
2902

2903
                                return json_traits::as_object(val);
337✔
2904
                        };
172✔
2905

2906
                        /**
2907
                         * Check if a claim is present in the map
2908
                         * \return true if claim was present, false otherwise
2909
                         */
2910
                        bool has_claim(const typename json_traits::string_type& name) const noexcept {
625✔
2911
                                return claims.count(name) != 0;
625✔
2912
                        }
2913

2914
                        /**
2915
                         * Get a claim by name
2916
                         *
2917
                         * \param name the name of the desired claim
2918
                         * \return Requested claim
2919
                         * \throw jwt::error::claim_not_present_exception if the claim was not present
2920
                         */
2921
                        basic_claim_t get_claim(const typename json_traits::string_type& name) const {
252✔
2922
                                if (!has_claim(name)) throw error::claim_not_present_exception();
252✔
2923
                                return basic_claim_t{claims.at(name)};
248✔
2924
                        }
2925
                };
2926
        } // namespace details
2927

2928
        /**
2929
         * Base class that represents a token payload.
2930
         * Contains Convenience accessors for common claims.
2931
         */
2932
        template<typename json_traits>
2933
        class payload {
2934
        protected:
2935
                details::map_of_claims<json_traits> payload_claims;
2936

2937
        public:
2938
                using basic_claim_t = basic_claim<json_traits>;
2939

2940
                /**
2941
                 * Check if issuer is present ("iss")
2942
                 * \return true if present, false otherwise
2943
                 */
2944
                bool has_issuer() const noexcept { return has_payload_claim("iss"); }
27✔
2945
                /**
2946
                 * Check if subject is present ("sub")
2947
                 * \return true if present, false otherwise
2948
                 */
2949
                bool has_subject() const noexcept { return has_payload_claim("sub"); }
27✔
2950
                /**
2951
                 * Check if audience is present ("aud")
2952
                 * \return true if present, false otherwise
2953
                 */
2954
                bool has_audience() const noexcept { return has_payload_claim("aud"); }
24✔
2955
                /**
2956
                 * Check if expires is present ("exp")
2957
                 * \return true if present, false otherwise
2958
                 */
2959
                bool has_expires_at() const noexcept { return has_payload_claim("exp"); }
213✔
2960
                /**
2961
                 * Check if not before is present ("nbf")
2962
                 * \return true if present, false otherwise
2963
                 */
2964
                bool has_not_before() const noexcept { return has_payload_claim("nbf"); }
231✔
2965
                /**
2966
                 * Check if issued at is present ("iat")
2967
                 * \return true if present, false otherwise
2968
                 */
2969
                bool has_issued_at() const noexcept { return has_payload_claim("iat"); }
219✔
2970
                /**
2971
                 * Check if token id is present ("jti")
2972
                 * \return true if present, false otherwise
2973
                 */
2974
                bool has_id() const noexcept { return has_payload_claim("jti"); }
24✔
2975
                /**
2976
                 * Get issuer claim
2977
                 * \return issuer as string
2978
                 * \throw std::runtime_error If claim was not present
2979
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
2980
                 */
2981
                typename json_traits::string_type get_issuer() const { return get_payload_claim("iss").as_string(); }
9✔
2982
                /**
2983
                 * Get subject claim
2984
                 * \return subject as string
2985
                 * \throw std::runtime_error If claim was not present
2986
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
2987
                 */
2988
                typename json_traits::string_type get_subject() const { return get_payload_claim("sub").as_string(); }
3✔
2989
                /**
2990
                 * Get audience claim
2991
                 * \return audience as a set of strings
2992
                 * \throw std::runtime_error If claim was not present
2993
                 * \throw std::bad_cast Claim was present but not a set (Should not happen in a valid token)
2994
                 */
2995
                typename basic_claim_t::set_t get_audience() const {
6✔
2996
                        auto aud = get_payload_claim("aud");
6✔
2997
                        if (aud.get_type() == json::type::string) return {aud.as_string()};
21✔
2998

2999
                        return aud.as_set();
1✔
3000
                }
11✔
3001
                /**
3002
                 * Get expires claim
3003
                 * \return expires as a date in utc
3004
                 * \throw std::runtime_error If claim was not present
3005
                 * \throw std::bad_cast Claim was present but not a date (Should not happen in a valid token)
3006
                 */
3007
                date get_expires_at() const { return get_payload_claim("exp").as_date(); }
60✔
3008
                /**
3009
                 * Get not valid before claim
3010
                 * \return nbf date in utc
3011
                 * \throw std::runtime_error If claim was not present
3012
                 * \throw std::bad_cast Claim was present but not a date (Should not happen in a valid token)
3013
                 */
3014
                date get_not_before() const { return get_payload_claim("nbf").as_date(); }
12✔
3015
                /**
3016
                 * Get issued at claim
3017
                 * \return issued at as date in utc
3018
                 * \throw std::runtime_error If claim was not present
3019
                 * \throw std::bad_cast Claim was present but not a date (Should not happen in a valid token)
3020
                 */
3021
                date get_issued_at() const { return get_payload_claim("iat").as_date(); }
60✔
3022
                /**
3023
                 * Get id claim
3024
                 * \return id as string
3025
                 * \throw std::runtime_error If claim was not present
3026
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3027
                 */
3028
                typename json_traits::string_type get_id() const { return get_payload_claim("jti").as_string(); }
3029
                /**
3030
                 * Check if a payload claim is present
3031
                 * \return true if claim was present, false otherwise
3032
                 */
3033
                bool has_payload_claim(const typename json_traits::string_type& name) const noexcept {
306✔
3034
                        return payload_claims.has_claim(name);
306✔
3035
                }
3036
                /**
3037
                 * Get payload claim
3038
                 * \return Requested claim
3039
                 * \throw std::runtime_error If claim was not present
3040
                 */
3041
                basic_claim_t get_payload_claim(const typename json_traits::string_type& name) const {
54✔
3042
                        return payload_claims.get_claim(name);
54✔
3043
                }
3044
        };
3045

3046
        /**
3047
         * Base class that represents a token header.
3048
         * Contains Convenience accessors for common claims.
3049
         */
3050
        template<typename json_traits>
3051
        class header {
3052
        protected:
3053
                details::map_of_claims<json_traits> header_claims;
3054

3055
        public:
3056
                using basic_claim_t = basic_claim<json_traits>;
3057
                /**
3058
                 * Check if algorithm is present ("alg")
3059
                 * \return true if present, false otherwise
3060
                 */
3061
                bool has_algorithm() const noexcept { return has_header_claim("alg"); }
27✔
3062
                /**
3063
                 * Check if type is present ("typ")
3064
                 * \return true if present, false otherwise
3065
                 */
3066
                bool has_type() const noexcept { return has_header_claim("typ"); }
27✔
3067
                /**
3068
                 * Check if content type is present ("cty")
3069
                 * \return true if present, false otherwise
3070
                 */
3071
                bool has_content_type() const noexcept { return has_header_claim("cty"); }
24✔
3072
                /**
3073
                 * Check if key id is present ("kid")
3074
                 * \return true if present, false otherwise
3075
                 */
3076
                bool has_key_id() const noexcept { return has_header_claim("kid"); }
24✔
3077
                /**
3078
                 * Get algorithm claim
3079
                 * \return algorithm as string
3080
                 * \throw std::runtime_error If claim was not present
3081
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3082
                 */
3083
                typename json_traits::string_type get_algorithm() const { return get_header_claim("alg").as_string(); }
315✔
3084
                /**
3085
                 * Get type claim
3086
                 * \return type as a string
3087
                 * \throw std::runtime_error If claim was not present
3088
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3089
                 */
3090
                typename json_traits::string_type get_type() const { return get_header_claim("typ").as_string(); }
27✔
3091
                /**
3092
                 * Get content type claim
3093
                 * \return content type as string
3094
                 * \throw std::runtime_error If claim was not present
3095
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3096
                 */
3097
                typename json_traits::string_type get_content_type() const { return get_header_claim("cty").as_string(); }
3098
                /**
3099
                 * Get key id claim
3100
                 * \return key id as string
3101
                 * \throw std::runtime_error If claim was not present
3102
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3103
                 */
3104
                typename json_traits::string_type get_key_id() const { return get_header_claim("kid").as_string(); }
3105
                /**
3106
                 * Check if a header claim is present
3107
                 * \return true if claim was present, false otherwise
3108
                 */
3109
                bool has_header_claim(const typename json_traits::string_type& name) const noexcept {
37✔
3110
                        return header_claims.has_claim(name);
37✔
3111
                }
3112
                /**
3113
                 * Get header claim
3114
                 * \return Requested claim
3115
                 * \throw std::runtime_error If claim was not present
3116
                 */
3117
                basic_claim_t get_header_claim(const typename json_traits::string_type& name) const {
114✔
3118
                        return header_claims.get_claim(name);
114✔
3119
                }
3120
        };
3121

3122
        /**
3123
         * Class containing all information about a decoded token
3124
         */
3125
        template<typename json_traits>
3126
        class decoded_jwt : public header<json_traits>, public payload<json_traits> {
3127
        protected:
3128
                /// Unmodified token, as passed to constructor
3129
                typename json_traits::string_type token;
3130
                /// Header part decoded from base64
3131
                typename json_traits::string_type header;
3132
                /// Unmodified header part in base64
3133
                typename json_traits::string_type header_base64;
3134
                /// Payload part decoded from base64
3135
                typename json_traits::string_type payload;
3136
                /// Unmodified payload part in base64
3137
                typename json_traits::string_type payload_base64;
3138
                /// Signature part decoded from base64
3139
                typename json_traits::string_type signature;
3140
                /// Unmodified signature part in base64
3141
                typename json_traits::string_type signature_base64;
3142

3143
        public:
3144
                using basic_claim_t = basic_claim<json_traits>;
3145
#ifndef JWT_DISABLE_BASE64
3146
                /**
3147
                 * \brief Parses a given token
3148
                 *
3149
                 * \note Decodes using the jwt::base64url which supports an std::string
3150
                 *
3151
                 * \param token The token to parse
3152
                 * \throw std::invalid_argument Token is not in correct format
3153
                 * \throw std::runtime_error Base64 decoding failed or invalid json
3154
                 */
3155
                JWT_CLAIM_EXPLICIT decoded_jwt(const typename json_traits::string_type& token)
88✔
3156
                        : decoded_jwt(token, [](const typename json_traits::string_type& str) {
253✔
3157
                                  return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(str));
253✔
3158
                          }) {}
88✔
3159
#endif
3160
                /**
3161
                 * \brief Parses a given token
3162
                 *
3163
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
3164
                 * It should ensure the padding of the input and then base64url decode and
3165
                 * return the results.
3166
                 * \param token The token to parse
3167
                 * \param decode The function to decode the token
3168
                 * \throw std::invalid_argument Token is not in correct format
3169
                 * \throw std::runtime_error Base64 decoding failed or invalid json
3170
                 */
3171
                template<typename Decode>
3172
                decoded_jwt(const typename json_traits::string_type& token, Decode decode) : token(token) {
88✔
3173
                        auto hdr_end = token.find('.');
88✔
3174
                        if (hdr_end == json_traits::string_type::npos) throw std::invalid_argument("invalid token supplied");
88✔
3175
                        auto payload_end = token.find('.', hdr_end + 1);
87✔
3176
                        if (payload_end == json_traits::string_type::npos) throw std::invalid_argument("invalid token supplied");
87✔
3177
                        header_base64 = token.substr(0, hdr_end);
85✔
3178
                        payload_base64 = token.substr(hdr_end + 1, payload_end - hdr_end - 1);
85✔
3179
                        signature_base64 = token.substr(payload_end + 1);
85✔
3180

3181
                        header = decode(header_base64);
85✔
3182
                        payload = decode(payload_base64);
84✔
3183
                        signature = decode(signature_base64);
84✔
3184

3185
                        this->header_claims = details::map_of_claims<json_traits>::parse_claims(header);
84✔
3186
                        this->payload_claims = details::map_of_claims<json_traits>::parse_claims(payload);
83✔
3187
                }
128✔
3188

3189
                /**
3190
                 * Get token string, as passed to constructor
3191
                 * \return token as passed to constructor
3192
                 */
3193
                const typename json_traits::string_type& get_token() const noexcept { return token; }
1✔
3194
                /**
3195
                 * Get header part as json string
3196
                 * \return header part after base64 decoding
3197
                 */
3198
                const typename json_traits::string_type& get_header() const noexcept { return header; }
3199
                /**
3200
                 * Get payload part as json string
3201
                 * \return payload part after base64 decoding
3202
                 */
3203
                const typename json_traits::string_type& get_payload() const noexcept { return payload; }
3204
                /**
3205
                 * Get signature part as json string
3206
                 * \return signature part after base64 decoding
3207
                 */
3208
                const typename json_traits::string_type& get_signature() const noexcept { return signature; }
95✔
3209
                /**
3210
                 * Get header part as base64 string
3211
                 * \return header part before base64 decoding
3212
                 */
3213
                const typename json_traits::string_type& get_header_base64() const noexcept { return header_base64; }
95✔
3214
                /**
3215
                 * Get payload part as base64 string
3216
                 * \return payload part before base64 decoding
3217
                 */
3218
                const typename json_traits::string_type& get_payload_base64() const noexcept { return payload_base64; }
95✔
3219
                /**
3220
                 * Get signature part as base64 string
3221
                 * \return signature part before base64 decoding
3222
                 */
3223
                const typename json_traits::string_type& get_signature_base64() const noexcept { return signature_base64; }
3224
                /**
3225
                 * Get all payload as JSON object
3226
                 * \return map of claims
3227
                 */
3228
                typename json_traits::object_type get_payload_json() const { return this->payload_claims.claims; }
3229
                /**
3230
                 * Get all header as JSON object
3231
                 * \return map of claims
3232
                 */
3233
                typename json_traits::object_type get_header_json() const { return this->header_claims.claims; }
3234
                /**
3235
                 * Get a payload claim by name
3236
                 *
3237
                 * \param name the name of the desired claim
3238
                 * \return Requested claim
3239
                 * \throw jwt::error::claim_not_present_exception if the claim was not present
3240
                 */
3241
                basic_claim_t get_payload_claim(const typename json_traits::string_type& name) const {
48✔
3242
                        return this->payload_claims.get_claim(name);
48✔
3243
                }
3244
                /**
3245
                 * Get a header claim by name
3246
                 *
3247
                 * \param name the name of the desired claim
3248
                 * \return Requested claim
3249
                 * \throw jwt::error::claim_not_present_exception if the claim was not present
3250
                 */
3251
                basic_claim_t get_header_claim(const typename json_traits::string_type& name) const {
4✔
3252
                        return this->header_claims.get_claim(name);
4✔
3253
                }
3254
        };
3255

3256
        /**
3257
         * Builder class to build and sign a new token
3258
         * Use jwt::create() to get an instance of this class.
3259
         */
3260
        template<typename Clock, typename json_traits>
3261
        class builder {
3262
                typename json_traits::object_type header_claims;
3263
                typename json_traits::object_type payload_claims;
3264

3265
                /// Instance of clock type
3266
                Clock clock;
3267

3268
        public:
3269
                /**
3270
                 * Constructor for building a new builder instance
3271
                 * \param c Clock instance
3272
                 */
3273
                JWT_CLAIM_EXPLICIT builder(Clock c) : clock(c) {}
55✔
3274
                /**
3275
                 * Set a header claim.
3276
                 * \param id Name of the claim
3277
                 * \param c Claim to add
3278
                 * \return *this to allow for method chaining
3279
                 */
3280
                builder& set_header_claim(const typename json_traits::string_type& id, typename json_traits::value_type c) {
27✔
3281
                        header_claims[id] = std::move(c);
27✔
3282
                        return *this;
27✔
3283
                }
3284

3285
                /**
3286
                 * Set a header claim.
3287
                 * \param id Name of the claim
3288
                 * \param c Claim to add
3289
                 * \return *this to allow for method chaining
3290
                 */
3291
                builder& set_header_claim(const typename json_traits::string_type& id, basic_claim<json_traits> c) {
3292
                        header_claims[id] = c.to_json();
3293
                        return *this;
3294
                }
3295
                /**
3296
                 * Set a payload claim.
3297
                 * \param id Name of the claim
3298
                 * \param c Claim to add
3299
                 * \return *this to allow for method chaining
3300
                 */
3301
                builder& set_payload_claim(const typename json_traits::string_type& id, typename json_traits::value_type c) {
39✔
3302
                        payload_claims[id] = std::move(c);
39✔
3303
                        return *this;
39✔
3304
                }
3305
                /**
3306
                 * Set a payload claim.
3307
                 * \param id Name of the claim
3308
                 * \param c Claim to add
3309
                 * \return *this to allow for method chaining
3310
                 */
3311
                builder& set_payload_claim(const typename json_traits::string_type& id, basic_claim<json_traits> c) {
40✔
3312
                        payload_claims[id] = c.to_json();
40✔
3313
                        return *this;
40✔
3314
                }
3315
                /**
3316
                 * \brief Set algorithm claim
3317
                 * You normally don't need to do this, as the algorithm is automatically set if you don't change it.
3318
                 *
3319
                 * \param str Name of algorithm
3320
                 * \return *this to allow for method chaining
3321
                 */
3322
                builder& set_algorithm(typename json_traits::string_type str) {
1✔
3323
                        return set_header_claim("alg", typename json_traits::value_type(str));
3✔
3324
                }
3325
                /**
3326
                 * Set type claim
3327
                 * \param str Type to set
3328
                 * \return *this to allow for method chaining
3329
                 */
3330
                builder& set_type(typename json_traits::string_type str) {
26✔
3331
                        return set_header_claim("typ", typename json_traits::value_type(str));
78✔
3332
                }
3333
                /**
3334
                 * Set content type claim
3335
                 * \param str Type to set
3336
                 * \return *this to allow for method chaining
3337
                 */
3338
                builder& set_content_type(typename json_traits::string_type str) {
3339
                        return set_header_claim("cty", typename json_traits::value_type(str));
3340
                }
3341
                /**
3342
                 * \brief Set key id claim
3343
                 *
3344
                 * \param str Key id to set
3345
                 * \return *this to allow for method chaining
3346
                 */
3347
                builder& set_key_id(typename json_traits::string_type str) {
3348
                        return set_header_claim("kid", typename json_traits::value_type(str));
3349
                }
3350
                /**
3351
                 * Set issuer claim
3352
                 * \param str Issuer to set
3353
                 * \return *this to allow for method chaining
3354
                 */
3355
                builder& set_issuer(typename json_traits::string_type str) {
34✔
3356
                        return set_payload_claim("iss", typename json_traits::value_type(str));
102✔
3357
                }
3358
                /**
3359
                 * Set subject claim
3360
                 * \param str Subject to set
3361
                 * \return *this to allow for method chaining
3362
                 */
3363
                builder& set_subject(typename json_traits::string_type str) {
3364
                        return set_payload_claim("sub", typename json_traits::value_type(str));
3365
                }
3366
                /**
3367
                 * Set audience claim
3368
                 * \param a Audience set
3369
                 * \return *this to allow for method chaining
3370
                 */
3371
                builder& set_audience(typename json_traits::array_type a) {
1✔
3372
                        return set_payload_claim("aud", typename json_traits::value_type(a));
3✔
3373
                }
3374
                /**
3375
                 * Set audience claim
3376
                 * \param aud Single audience
3377
                 * \return *this to allow for method chaining
3378
                 */
3379
                builder& set_audience(typename json_traits::string_type aud) {
3✔
3380
                        return set_payload_claim("aud", typename json_traits::value_type(aud));
9✔
3381
                }
3382
                /**
3383
                 * Set expires at claim
3384
                 * \param d Expires time
3385
                 * \return *this to allow for method chaining
3386
                 */
3387
                builder& set_expires_at(const date& d) { return set_payload_claim("exp", basic_claim<json_traits>(d)); }
30✔
3388
                /**
3389
                 * Set expires at claim to @p d from the current moment
3390
                 * \param d token expiration timeout
3391
                 * \return *this to allow for method chaining
3392
                 */
3393
                template<class Rep, class Period>
3394
                builder& set_expires_in(const std::chrono::duration<Rep, Period>& d) {
4✔
3395
                        return set_payload_claim("exp", basic_claim<json_traits>(clock.now() + d));
12✔
3396
                }
3397
                /**
3398
                 * Set not before claim
3399
                 * \param d First valid time
3400
                 * \return *this to allow for method chaining
3401
                 */
3402
                builder& set_not_before(const date& d) { return set_payload_claim("nbf", basic_claim<json_traits>(d)); }
6✔
3403
                /**
3404
                 * Set issued at claim
3405
                 * \param d Issued at time, should be current time
3406
                 * \return *this to allow for method chaining
3407
                 */
3408
                builder& set_issued_at(const date& d) { return set_payload_claim("iat", basic_claim<json_traits>(d)); }
42✔
3409
                /**
3410
                 * Set issued at claim to the current moment
3411
                 * \return *this to allow for method chaining
3412
                 */
3413
                builder& set_issued_now() { return set_issued_at(clock.now()); }
4✔
3414
                /**
3415
                 * Set id claim
3416
                 * \param str ID to set
3417
                 * \return *this to allow for method chaining
3418
                 */
3419
                builder& set_id(const typename json_traits::string_type& str) {
3420
                        return set_payload_claim("jti", typename json_traits::value_type(str));
3421
                }
3422

3423
                /**
3424
                 * Sign token and return result
3425
                 * \tparam Algo Callable method which takes a string_type and return the signed input as a string_type
3426
                 * \tparam Encode Callable method which takes a string_type and base64url safe encodes it,
3427
                 * MUST return the result with no padding; trim the result.
3428
                 * \param algo Instance of an algorithm to sign the token with
3429
                 * \param encode Callable to transform the serialized json to base64 with no padding
3430
                 * \return Final token as a string
3431
                 *
3432
                 * \note If the 'alg' header in not set in the token it will be set to `algo.name()`
3433
                 */
3434
                template<typename Algo, typename Encode>
3435
                typename json_traits::string_type sign(const Algo& algo, Encode encode) const {
3436
                        std::error_code ec;
3437
                        auto res = sign(algo, encode, ec);
3438
                        error::throw_if_error(ec);
3439
                        return res;
3440
                }
3441
#ifndef JWT_DISABLE_BASE64
3442
                /**
3443
                 * Sign token and return result
3444
                 *
3445
                 * using the `jwt::base` functions provided
3446
                 *
3447
                 * \param algo Instance of an algorithm to sign the token with
3448
                 * \return Final token as a string
3449
                 */
3450
                template<typename Algo>
3451
                typename json_traits::string_type sign(const Algo& algo) const {
55✔
3452
                        std::error_code ec;
55✔
3453
                        auto res = sign(algo, ec);
55✔
3454
                        error::throw_if_error(ec);
55✔
3455
                        return res;
102✔
3456
                }
4✔
3457
#endif
3458

3459
                /**
3460
                 * Sign token and return result
3461
                 * \tparam Algo Callable method which takes a string_type and return the signed input as a string_type
3462
                 * \tparam Encode Callable method which takes a string_type and base64url safe encodes it,
3463
                 * MUST return the result with no padding; trim the result.
3464
                 * \param algo Instance of an algorithm to sign the token with
3465
                 * \param encode Callable to transform the serialized json to base64 with no padding
3466
                 * \param ec error_code filled with details on error
3467
                 * \return Final token as a string
3468
                 *
3469
                 * \note If the 'alg' header in not set in the token it will be set to `algo.name()`
3470
                 */
3471
                template<typename Algo, typename Encode>
3472
                typename json_traits::string_type sign(const Algo& algo, Encode encode, std::error_code& ec) const {
55✔
3473
                        // make a copy such that a builder can be re-used
3474
                        typename json_traits::object_type obj_header = header_claims;
55✔
3475
                        if (header_claims.count("alg") == 0) obj_header["alg"] = typename json_traits::value_type(algo.name());
233✔
3476

3477
                        const auto header = encode(json_traits::serialize(typename json_traits::value_type(obj_header)));
55✔
3478
                        const auto payload = encode(json_traits::serialize(typename json_traits::value_type(payload_claims)));
55✔
3479
                        const auto token = header + "." + payload;
55✔
3480

3481
                        auto signature = algo.sign(token, ec);
55✔
3482
                        if (ec) return {};
55✔
3483

3484
                        return token + "." + encode(signature);
51✔
3485
                }
55✔
3486
#ifndef JWT_DISABLE_BASE64
3487
                /**
3488
                 * Sign token and return result
3489
                 *
3490
                 * using the `jwt::base` functions provided
3491
                 *
3492
                 * \param algo Instance of an algorithm to sign the token with
3493
                 * \param ec error_code filled with details on error
3494
                 * \return Final token as a string
3495
                 */
3496
                template<typename Algo>
3497
                typename json_traits::string_type sign(const Algo& algo, std::error_code& ec) const {
55✔
3498
                        return sign(
3499
                                algo,
3500
                                [](const typename json_traits::string_type& data) {
161✔
3501
                                        return base::trim<alphabet::base64url>(base::encode<alphabet::base64url>(data));
161✔
3502
                                },
3503
                                ec);
55✔
3504
                }
3505
#endif
3506
        };
3507

3508
        namespace verify_ops {
3509
                /**
3510
                 * This is the base container which holds the token that need to be verified
3511
                 */
3512
                template<typename json_traits>
3513
                struct verify_context {
3514
                        verify_context(date ctime, const decoded_jwt<json_traits>& j, size_t l)
76✔
3515
                                : current_time(ctime), jwt(j), default_leeway(l) {}
76✔
3516
                        /// Current time, retrieved from the verifiers clock and cached for performance and consistency
3517
                        date current_time;
3518
                        /// The jwt passed to the verifier
3519
                        const decoded_jwt<json_traits>& jwt;
3520
                        /// The configured default leeway for this verification
3521
                        size_t default_leeway{0};
3522

3523
                        /// The claim key to apply this comparison on
3524
                        typename json_traits::string_type claim_key{};
3525

3526
                        /**
3527
                         * \brief Helper method to get a claim from the jwt in this context
3528
                         * \param in_header check JWT header or payload sections
3529
                         * \param ec std::error_code which will indicate if any error occure
3530
                         * \return basic_claim if it was present otherwise empty
3531
                         */
3532
                        basic_claim<json_traits> get_claim(bool in_header, std::error_code& ec) const {
54✔
3533
                                if (in_header) {
54✔
3534
                                        if (!jwt.has_header_claim(claim_key)) {
3✔
UNCOV
3535
                                                ec = error::token_verification_error::missing_claim;
×
UNCOV
3536
                                                return {};
×
3537
                                        }
3538
                                        return jwt.get_header_claim(claim_key);
3✔
3539
                                } else {
3540
                                        if (!jwt.has_payload_claim(claim_key)) {
51✔
3541
                                                ec = error::token_verification_error::missing_claim;
4✔
3542
                                                return {};
4✔
3543
                                        }
3544
                                        return jwt.get_payload_claim(claim_key);
47✔
3545
                                }
3546
                        }
3547
                        /**
3548
                         * Helper method to get a claim of a specific type from the jwt in this context
3549
                         * \param in_header check JWT header or payload sections
3550
                         * \param t the expected type of the claim
3551
                         * \param ec std::error_code which will indicate if any error occure
3552
                         * \return basic_claim if it was present otherwise empty
3553
                          */
3554
                        basic_claim<json_traits> get_claim(bool in_header, json::type t, std::error_code& ec) const {
51✔
3555
                                auto c = get_claim(in_header, ec);
51✔
3556
                                if (ec) return {};
51✔
3557
                                if (c.get_type() != t) {
48✔
3558
                                        ec = error::token_verification_error::claim_type_missmatch;
1✔
3559
                                        return {};
1✔
3560
                                }
3561
                                return c;
47✔
3562
                        }
51✔
3563
                        /**
3564
                         * \brief Helper method to get a payload claim from the jwt
3565
                         * \param ec std::error_code which will indicate if any error occure
3566
                         * \return basic_claim if it was present otherwise empty
3567
                          */
3568
                        basic_claim<json_traits> get_claim(std::error_code& ec) const { return get_claim(false, ec); }
3569
                        /**
3570
                         * \brief Helper method to get a payload claim of a specific type from the jwt
3571
                         * \param t the expected type of the claim
3572
                         * \param ec std::error_code which will indicate if any error occure
3573
                         * \return basic_claim if it was present otherwise empty
3574
                          */
3575
                        basic_claim<json_traits> get_claim(json::type t, std::error_code& ec) const {
3576
                                return get_claim(false, t, ec);
3577
                        }
3578
                };
3579

3580
                /**
3581
                 * This is the default operation and does case sensitive matching
3582
                 */
3583
                template<typename json_traits, bool in_header = false>
3584
                struct equals_claim {
3585
                        const basic_claim<json_traits> expected;
3586
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
48✔
3587
                                auto jc = ctx.get_claim(in_header, expected.get_type(), ec);
48✔
3588
                                if (ec) return;
48✔
3589
                                const bool matches = [&]() {
×
3590
                                        switch (expected.get_type()) {
44✔
UNCOV
3591
                                        case json::type::boolean: return expected.as_boolean() == jc.as_boolean();
×
UNCOV
3592
                                        case json::type::integer: return expected.as_integer() == jc.as_integer();
×
UNCOV
3593
                                        case json::type::number: return expected.as_number() == jc.as_number();
×
3594
                                        case json::type::string: return expected.as_string() == jc.as_string();
36✔
3595
                                        case json::type::array:
8✔
3596
                                        case json::type::object:
3597
                                                return json_traits::serialize(expected.to_json()) == json_traits::serialize(jc.to_json());
8✔
UNCOV
3598
                                        default: throw std::logic_error("internal error, should be unreachable");
×
3599
                                        }
3600
                                }();
44✔
3601
                                if (!matches) {
44✔
3602
                                        ec = error::token_verification_error::claim_value_missmatch;
1✔
3603
                                        return;
1✔
3604
                                }
3605
                        }
48✔
3606
                };
3607

3608
                /**
3609
                 * Checks that the current time is before the time specified in the given
3610
                 * claim. This is identical to how the "exp" check works.
3611
                 */
3612
                template<typename json_traits, bool in_header = false>
3613
                struct date_before_claim {
3614
                        const size_t leeway;
3615
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3616
                                auto jc = ctx.get_claim(in_header, json::type::integer, ec);
3617
                                if (ec) return;
3618
                                auto c = jc.as_date();
3619
                                if (ctx.current_time > c + std::chrono::seconds(leeway)) {
3620
                                        ec = error::token_verification_error::token_expired;
3621
                                }
3622
                        }
3623
                };
3624

3625
                /**
3626
                 * Checks that the current time is after the time specified in the given
3627
                 * claim. This is identical to how the "nbf" and "iat" check works.
3628
                 */
3629
                template<typename json_traits, bool in_header = false>
3630
                struct date_after_claim {
3631
                        const size_t leeway;
3632
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3633
                                auto jc = ctx.get_claim(in_header, json::type::integer, ec);
3634
                                if (ec) return;
3635
                                auto c = jc.as_date();
3636
                                if (ctx.current_time < c - std::chrono::seconds(leeway)) {
3637
                                        ec = error::token_verification_error::token_expired;
3638
                                }
3639
                        }
3640
                };
3641

3642
                /**
3643
                 * Checks if the given set is a subset of the set inside the token.
3644
                 * If the token value is a string it is treated as a set with a single element.
3645
                 * The comparison is case sensitive.
3646
                 */
3647
                template<typename json_traits, bool in_header = false>
3648
                struct is_subset_claim {
3649
                        const typename basic_claim<json_traits>::set_t expected;
3650
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3✔
3651
                                auto c = ctx.get_claim(in_header, ec);
3✔
3652
                                if (ec) return;
3✔
3653
                                if (c.get_type() == json::type::string) {
2✔
3654
                                        if (expected.size() != 1 || *expected.begin() != c.as_string()) {
2✔
3655
                                                ec = error::token_verification_error::audience_missmatch;
2✔
3656
                                                return;
2✔
3657
                                        }
3658
                                } else if (c.get_type() == json::type::array) {
×
3659
                                        auto jc = c.as_set();
×
3660
                                        for (auto& e : expected) {
×
UNCOV
3661
                                                if (jc.find(e) == jc.end()) {
×
UNCOV
3662
                                                        ec = error::token_verification_error::audience_missmatch;
×
3663
                                                        return;
×
3664
                                                }
3665
                                        }
UNCOV
3666
                                } else {
×
UNCOV
3667
                                        ec = error::token_verification_error::claim_type_missmatch;
×
UNCOV
3668
                                        return;
×
3669
                                }
3670
                        }
3✔
3671
                };
3672

3673
                /**
3674
                 * Checks if the claim is a string and does an case insensitive comparison.
3675
                 */
3676
                template<typename json_traits, bool in_header = false>
3677
                struct insensitive_string_claim {
3678
                        const typename json_traits::string_type expected;
3679
                        std::locale locale;
3680
                        insensitive_string_claim(const typename json_traits::string_type& e, std::locale loc)
2✔
3681
                                : expected(to_lower_unicode(e, loc)), locale(loc) {}
2✔
3682

3683
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3✔
3684
                                const auto c = ctx.get_claim(in_header, json::type::string, ec);
3✔
3685
                                if (ec) return;
3✔
3686
                                if (to_lower_unicode(c.as_string(), locale) != expected) {
3✔
3687
                                        ec = error::token_verification_error::claim_value_missmatch;
1✔
3688
                                }
3689
                        }
3✔
3690

3691
                        static std::string to_lower_unicode(const std::string& str, const std::locale& loc) {
5✔
3692
                                std::mbstate_t state = std::mbstate_t();
5✔
3693
                                const char* in_next = str.data();
5✔
3694
                                const char* in_end = str.data() + str.size();
5✔
3695
                                std::wstring wide;
5✔
3696
                                wide.reserve(str.size());
5✔
3697

3698
                                while (in_next != in_end) {
20✔
3699
                                        wchar_t wc;
3700
                                        std::size_t result = std::mbrtowc(&wc, in_next, in_end - in_next, &state);
15✔
3701
                                        if (result == static_cast<std::size_t>(-1)) {
15✔
UNCOV
3702
                                                throw std::runtime_error("encoding error: " + std::string(std::strerror(errno)));
×
3703
                                        } else if (result == static_cast<std::size_t>(-2)) {
15✔
UNCOV
3704
                                                throw std::runtime_error("conversion error: next bytes constitute an incomplete, but so far "
×
3705
                                                                                                 "valid, multibyte character.");
3706
                                        }
3707
                                        in_next += result;
15✔
3708
                                        wide.push_back(wc);
15✔
3709
                                }
3710

3711
                                auto& f = std::use_facet<std::ctype<wchar_t>>(loc);
5✔
3712
                                f.tolower(&wide[0], &wide[0] + wide.size());
5✔
3713

3714
                                std::string out;
5✔
3715
                                out.reserve(wide.size());
5✔
3716
                                for (wchar_t wc : wide) {
20✔
3717
                                        char mb[MB_LEN_MAX];
3718
                                        std::size_t n = std::wcrtomb(mb, wc, &state);
15✔
3719
                                        if (n != static_cast<std::size_t>(-1)) out.append(mb, n);
15✔
3720
                                }
3721

3722
                                return out;
10✔
3723
                        }
5✔
3724
                };
3725
        } // namespace verify_ops
3726

3727
        /**
3728
         * Verifier class used to check if a decoded token contains all claims required by your application and has a valid
3729
         * signature.
3730
         */
3731
        template<typename Clock, typename json_traits>
3732
        class verifier {
3733
        public:
3734
                using basic_claim_t = basic_claim<json_traits>;
3735
                /**
3736
                 * \brief Verification function data structure.
3737
                 *
3738
                 * This gets passed the current verifier, a reference to the decoded jwt, a reference to the key of this claim,
3739
                 * as well as a reference to an error_code.
3740
                 * The function checks if the actual value matches certain rules (e.g. equality to value x) and sets the error_code if
3741
                 * it does not. Once a non zero error_code is encountered the verification stops and this error_code becomes the result
3742
                 * returned from verify
3743
                 */
3744
                using verify_check_fn_t =
3745
                        std::function<void(const verify_ops::verify_context<json_traits>&, std::error_code& ec)>;
3746

3747
        private:
3748
                struct algo_base {
3749
                        virtual ~algo_base() = default;
84✔
3750
                        virtual void verify(const std::string& data, const std::string& sig, std::error_code& ec) = 0;
3751
                };
3752
                template<typename T>
3753
                struct algo : public algo_base {
3754
                        T alg;
3755
                        explicit algo(T a) : alg(a) {}
84✔
3756
                        void verify(const std::string& data, const std::string& sig, std::error_code& ec) override {
94✔
3757
                                alg.verify(data, sig, ec);
94✔
3758
                        }
94✔
3759
                };
3760
                /// Required claims
3761
                std::unordered_map<typename json_traits::string_type, verify_check_fn_t> claims;
3762
                /// Leeway time for exp, nbf and iat
3763
                size_t default_leeway = 0;
3764
                /// Instance of clock type
3765
                Clock clock;
3766
                /// Supported algorithms
3767
                std::unordered_map<std::string, std::shared_ptr<algo_base>> algs;
3768

3769
        public:
3770
                /**
3771
                 * Constructor for building a new verifier instance
3772
                 * \param c Clock instance
3773
                 */
3774
                explicit verifier(Clock c) : clock(c) {
88✔
3775
                        claims["exp"] = [](const verify_ops::verify_context<json_traits>& ctx, std::error_code& ec) {
211✔
3776
                                if (!ctx.jwt.has_expires_at()) return;
63✔
3777
                                auto exp = ctx.jwt.get_expires_at();
20✔
3778
                                if (ctx.current_time > exp + std::chrono::seconds(ctx.default_leeway)) {
20✔
3779
                                        ec = error::token_verification_error::token_expired;
10✔
3780
                                }
3781
                        };
3782
                        claims["iat"] = [](const verify_ops::verify_context<json_traits>& ctx, std::error_code& ec) {
213✔
3783
                                if (!ctx.jwt.has_issued_at()) return;
65✔
3784
                                auto iat = ctx.jwt.get_issued_at();
20✔
3785
                                if (ctx.current_time < iat - std::chrono::seconds(ctx.default_leeway)) {
20✔
3786
                                        ec = error::token_verification_error::token_expired;
2✔
3787
                                }
3788
                        };
3789
                        claims["nbf"] = [](const verify_ops::verify_context<json_traits>& ctx, std::error_code& ec) {
217✔
3790
                                if (!ctx.jwt.has_not_before()) return;
69✔
3791
                                auto nbf = ctx.jwt.get_not_before();
4✔
3792
                                if (ctx.current_time < nbf - std::chrono::seconds(ctx.default_leeway)) {
4✔
3793
                                        ec = error::token_verification_error::token_expired;
2✔
3794
                                }
3795
                        };
3796
                }
88✔
3797

3798
                /**
3799
                 * Set default leeway to use.
3800
                 * \param leeway Default leeway to use if not specified otherwise
3801
                 * \return *this to allow chaining
3802
                 */
3803
                verifier& leeway(size_t leeway) {
3804
                        default_leeway = leeway;
3805
                        return *this;
3806
                }
3807
                /**
3808
                 * Set leeway for expires at.
3809
                 * If not specified the default leeway will be used.
3810
                 * \param leeway Set leeway to use for expires at.
3811
                 * \return *this to allow chaining
3812
                 */
3813
                verifier& expires_at_leeway(size_t leeway) {
3814
                        claims["exp"] = verify_ops::date_before_claim<json_traits>{leeway};
3815
                        return *this;
3816
                }
3817
                /**
3818
                 * Set leeway for not before.
3819
                 * If not specified the default leeway will be used.
3820
                 * \param leeway Set leeway to use for not before.
3821
                 * \return *this to allow chaining
3822
                 */
3823
                verifier& not_before_leeway(size_t leeway) {
3824
                        claims["nbf"] = verify_ops::date_after_claim<json_traits>{leeway};
3825
                        return *this;
3826
                }
3827
                /**
3828
                 * Set leeway for issued at.
3829
                 * If not specified the default leeway will be used.
3830
                 * \param leeway Set leeway to use for issued at.
3831
                 * \return *this to allow chaining
3832
                 */
3833
                verifier& issued_at_leeway(size_t leeway) {
3834
                        claims["iat"] = verify_ops::date_after_claim<json_traits>{leeway};
3835
                        return *this;
3836
                }
3837

3838
                /**
3839
                 * Set an type to check for.
3840
                 *
3841
                 * According to [RFC 7519 Section 5.1](https://datatracker.ietf.org/doc/html/rfc7519#section-5.1),
3842
                 * This parameter is ignored by JWT implementations; any processing of this parameter is performed by the JWT application.
3843
                 * Check is case sensitive.
3844
                 *
3845
                 * \param type Type Header Parameter to check for.
3846
                 * \param locale Localization functionality to use when comparing
3847
                 * \return *this to allow chaining
3848
                 */
3849
                verifier& with_type(const typename json_traits::string_type& type, std::locale locale = std::locale{}) {
2✔
3850
                        return with_claim("typ", verify_ops::insensitive_string_claim<json_traits, true>{type, std::move(locale)});
6✔
3851
                }
3852

3853
                /**
3854
                 * Set an issuer to check for.
3855
                 * Check is case sensitive.
3856
                 * \param iss Issuer to check for.
3857
                 * \return *this to allow chaining
3858
                 */
3859
                verifier& with_issuer(const typename json_traits::string_type& iss) {
44✔
3860
                        return with_claim("iss", basic_claim_t(iss));
132✔
3861
                }
3862

3863
                /**
3864
                 * Set a subject to check for.
3865
                 * Check is case sensitive.
3866
                 * \param sub Subject to check for.
3867
                 * \return *this to allow chaining
3868
                 */
3869
                verifier& with_subject(const typename json_traits::string_type& sub) {
1✔
3870
                        return with_claim("sub", basic_claim_t(sub));
3✔
3871
                }
3872
                /**
3873
                 * Set an audience to check for.
3874
                 * If any of the specified audiences is not present in the token the check fails.
3875
                 * \param aud Audience to check for.
3876
                 * \return *this to allow chaining
3877
                 */
3878
                verifier& with_audience(const typename basic_claim_t::set_t& aud) {
3✔
3879
                        claims["aud"] = verify_ops::is_subset_claim<json_traits>{aud};
9✔
3880
                        return *this;
3✔
3881
                }
3✔
3882
                /**
3883
                 * Set an audience to check for.
3884
                 * If the specified audiences is not present in the token the check fails.
3885
                 * \param aud Audience to check for.
3886
                 * \return *this to allow chaining
3887
                 */
3888
                verifier& with_audience(const typename json_traits::string_type& aud) {
2✔
3889
                        typename basic_claim_t::set_t s;
2✔
3890
                        s.insert(aud);
2✔
3891
                        return with_audience(s);
4✔
3892
                }
2✔
3893
                /**
3894
                 * Set an id to check for.
3895
                 * Check is case sensitive.
3896
                 * \param id ID to check for.
3897
                 * \return *this to allow chaining
3898
                 */
3899
                verifier& with_id(const typename json_traits::string_type& id) { return with_claim("jti", basic_claim_t(id)); }
3900

3901
                /**
3902
                 * Specify a claim to check for using the specified operation.
3903
                 * This is helpful for implementating application specific authentication checks
3904
                 * such as the one seen in partial-claim-verifier.cpp
3905
                 *
3906
                 * \snippet{trimleft} partial-claim-verifier.cpp verifier check custom claim
3907
                 *
3908
                 * \param name Name of the claim to check for
3909
                 * \param fn Function to use for verifying the claim
3910
                 * \return *this to allow chaining
3911
                 */
3912
                verifier& with_claim(const typename json_traits::string_type& name, verify_check_fn_t fn) {
58✔
3913
                        claims[name] = fn;
58✔
3914
                        return *this;
58✔
3915
                }
3916

3917
                /**
3918
                 * Specify a claim to check for equality (both type & value).
3919
                 * See the private-claims.cpp example.
3920
                 *
3921
                 * \snippet{trimleft} private-claims.cpp verify exact claim
3922
                 *
3923
                 * \param name Name of the claim to check for
3924
                 * \param c Claim to check for
3925
                 * \return *this to allow chaining
3926
                 */
3927
                verifier& with_claim(const typename json_traits::string_type& name, basic_claim_t c) {
56✔
3928
                        return with_claim(name, verify_ops::equals_claim<json_traits>{c});
56✔
3929
                }
56✔
3930

3931
                /**
3932
                 * \brief Add an algorithm available for checking.
3933
                 *
3934
                 * This is used to handle incomming tokens for predefined algorithms
3935
                 * which the authorization server is provided. For example a small system
3936
                 * where only a single RSA key-pair is used to sign tokens
3937
                 *
3938
                 * \snippet{trimleft} example/rsa-verify.cpp allow rsa algorithm
3939
                 *
3940
                 * \tparam Algorithm any algorithm such as those provided by jwt::algorithm
3941
                 * \param alg Algorithm to allow
3942
                 * \return *this to allow chaining
3943
                 */
3944
                template<typename Algorithm>
3945
                verifier& allow_algorithm(Algorithm alg) {
84✔
3946
                        algs[alg.name()] = std::make_shared<algo<Algorithm>>(alg);
84✔
3947
                        return *this;
84✔
3948
                }
3949

3950
                /**
3951
                 * Verify the given token.
3952
                 * \param jwt Token to check
3953
                 * \throw token_verification_exception Verification failed
3954
                 */
3955
                void verify(const decoded_jwt<json_traits>& jwt) const {
83✔
3956
                        std::error_code ec;
83✔
3957
                        verify(jwt, ec);
83✔
3958
                        error::throw_if_error(ec);
83✔
3959
                }
49✔
3960
                /**
3961
                 * Verify the given token.
3962
                 * \param jwt Token to check
3963
                 * \param ec error_code filled with details on error
3964
                 */
3965
                void verify(const decoded_jwt<json_traits>& jwt, std::error_code& ec) const {
95✔
3966
                        ec.clear();
95✔
3967
                        const typename json_traits::string_type data = jwt.get_header_base64() + "." + jwt.get_payload_base64();
95✔
3968
                        const typename json_traits::string_type sig = jwt.get_signature();
95✔
3969
                        const std::string algo = jwt.get_algorithm();
95✔
3970
                        if (algs.count(algo) == 0) {
95✔
3971
                                ec = error::token_verification_error::wrong_algorithm;
1✔
3972
                                return;
1✔
3973
                        }
3974
                        algs.at(algo)->verify(data, sig, ec);
94✔
3975
                        if (ec) return;
94✔
3976

3977
                        verify_ops::verify_context<json_traits> ctx{clock.now(), jwt, default_leeway};
76✔
3978
                        for (auto& c : claims) {
304✔
3979
                                ctx.claim_key = c.first;
251✔
3980
                                c.second(ctx, ec);
251✔
3981
                                if (ec) return;
251✔
3982
                        }
3983
                }
202✔
3984
        };
3985

3986
        /**
3987
         * \brief JSON Web Key
3988
         *
3989
         * https://tools.ietf.org/html/rfc7517
3990
         *
3991
         * A JSON object that represents a cryptographic key.  The members of
3992
         * the object represent properties of the key, including its value.
3993
         */
3994
        template<typename json_traits>
3995
        class jwk {
3996
                using basic_claim_t = basic_claim<json_traits>;
3997
                const details::map_of_claims<json_traits> jwk_claims;
3998

3999
        public:
4000
                JWT_CLAIM_EXPLICIT jwk(const typename json_traits::string_type& str)
3✔
4001
                        : jwk_claims(details::map_of_claims<json_traits>::parse_claims(str)) {}
3✔
4002

4003
                JWT_CLAIM_EXPLICIT jwk(const typename json_traits::value_type& json)
7✔
4004
                        : jwk_claims(json_traits::as_object(json)) {}
7✔
4005

4006
                /**
4007
                 * Get key type claim
4008
                 *
4009
                 * This returns the general type (e.g. RSA or EC), not a specific algorithm value.
4010
                 * \return key type as string
4011
                 * \throw std::runtime_error If claim was not present
4012
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4013
                 */
4014
                typename json_traits::string_type get_key_type() const { return get_jwk_claim("kty").as_string(); }
4015

4016
                /**
4017
                 * Get public key usage claim
4018
                 * \return usage parameter as string
4019
                 * \throw std::runtime_error If claim was not present
4020
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4021
                 */
4022
                typename json_traits::string_type get_use() const { return get_jwk_claim("use").as_string(); }
4023

4024
                /**
4025
                 * Get key operation types claim
4026
                 * \return key operation types as a set of strings
4027
                 * \throw std::runtime_error If claim was not present
4028
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4029
                 */
4030
                typename basic_claim_t::set_t get_key_operations() const { return get_jwk_claim("key_ops").as_set(); }
4031

4032
                /**
4033
                 * Get algorithm claim
4034
                 * \return algorithm as string
4035
                 * \throw std::runtime_error If claim was not present
4036
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4037
                 */
4038
                typename json_traits::string_type get_algorithm() const { return get_jwk_claim("alg").as_string(); }
6✔
4039

4040
                /**
4041
                 * Get key id claim
4042
                 * \return key id as string
4043
                 * \throw std::runtime_error If claim was not present
4044
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4045
                 */
4046
                typename json_traits::string_type get_key_id() const { return get_jwk_claim("kid").as_string(); }
51✔
4047

4048
                /**
4049
                 * \brief Get curve claim
4050
                 *
4051
                 * https://www.rfc-editor.org/rfc/rfc7518.html#section-6.2.1.1
4052
                 * https://www.iana.org/assignments/jose/jose.xhtml#table-web-key-elliptic-curve
4053
                 *
4054
                 * \return curve as string
4055
                 * \throw std::runtime_error If claim was not present
4056
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4057
                 */
4058
                typename json_traits::string_type get_curve() const { return get_jwk_claim("crv").as_string(); }
4059

4060
                /**
4061
                 * Get x5c claim
4062
                 * \return x5c as an array
4063
                 * \throw std::runtime_error If claim was not present
4064
                 * \throw std::bad_cast Claim was present but not a array (Should not happen in a valid token)
4065
                 */
4066
                typename json_traits::array_type get_x5c() const { return get_jwk_claim("x5c").as_array(); };
9✔
4067

4068
                /**
4069
                 * Get X509 URL claim
4070
                 * \return x5u as string
4071
                 * \throw std::runtime_error If claim was not present
4072
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4073
                 */
4074
                typename json_traits::string_type get_x5u() const { return get_jwk_claim("x5u").as_string(); };
4075

4076
                /**
4077
                 * Get X509 thumbprint claim
4078
                 * \return x5t as string
4079
                 * \throw std::runtime_error If claim was not present
4080
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4081
                 */
4082
                typename json_traits::string_type get_x5t() const { return get_jwk_claim("x5t").as_string(); };
4083

4084
                /**
4085
                 * Get X509 SHA256 thumbprint claim
4086
                 * \return x5t#S256 as string
4087
                 * \throw std::runtime_error If claim was not present
4088
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4089
                 */
4090
                typename json_traits::string_type get_x5t_sha256() const { return get_jwk_claim("x5t#S256").as_string(); };
4091

4092
                /**
4093
                 * Get x5c claim as a string
4094
                 * \return x5c as an string
4095
                 * \throw std::runtime_error If claim was not present
4096
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
4097
                 */
4098
                typename json_traits::string_type get_x5c_key_value() const {
2✔
4099
                        auto x5c_array = get_jwk_claim("x5c").as_array();
2✔
4100
                        if (x5c_array.size() == 0) throw error::claim_not_present_exception();
2✔
4101

4102
                        return json_traits::as_string(x5c_array.front());
2✔
4103
                };
2✔
4104

4105
                /**
4106
                 * Check if a key type is present ("kty")
4107
                 * \return true if present, false otherwise
4108
                 */
4109
                bool has_key_type() const noexcept { return has_jwk_claim("kty"); }
4110

4111
                /**
4112
                 * Check if a public key usage indication is present ("use")
4113
                 * \return true if present, false otherwise
4114
                 */
4115
                bool has_use() const noexcept { return has_jwk_claim("use"); }
4116

4117
                /**
4118
                 * Check if a key operations parameter is present ("key_ops")
4119
                 * \return true if present, false otherwise
4120
                 */
4121
                bool has_key_operations() const noexcept { return has_jwk_claim("key_ops"); }
4122

4123
                /**
4124
                 * Check if algorithm is present ("alg")
4125
                 * \return true if present, false otherwise
4126
                 */
4127
                bool has_algorithm() const noexcept { return has_jwk_claim("alg"); }
9✔
4128

4129
                /**
4130
                 * Check if curve is present ("crv")
4131
                 * \return true if present, false otherwise
4132
                 */
4133
                bool has_curve() const noexcept { return has_jwk_claim("crv"); }
4134

4135
                /**
4136
                 * Check if key id is present ("kid")
4137
                 * \return true if present, false otherwise
4138
                 */
4139
                bool has_key_id() const noexcept { return has_jwk_claim("kid"); }
45✔
4140

4141
                /**
4142
                 * Check if X509 URL is present ("x5u")
4143
                 * \return true if present, false otherwise
4144
                 */
4145
                bool has_x5u() const noexcept { return has_jwk_claim("x5u"); }
4146

4147
                /**
4148
                 * Check if X509 Chain is present ("x5c")
4149
                 * \return true if present, false otherwise
4150
                 */
4151
                bool has_x5c() const noexcept { return has_jwk_claim("x5c"); }
6✔
4152

4153
                /**
4154
                 * Check if a X509 thumbprint is present ("x5t")
4155
                 * \return true if present, false otherwise
4156
                 */
4157
                bool has_x5t() const noexcept { return has_jwk_claim("x5t"); }
4158

4159
                /**
4160
                 * Check if a X509 SHA256 thumbprint is present ("x5t#S256")
4161
                 * \return true if present, false otherwise
4162
                 */
4163
                bool has_x5t_sha256() const noexcept { return has_jwk_claim("x5t#S256"); }
4164

4165
                /**
4166
                 * Check if a jwk claim is present
4167
                 * \return true if claim was present, false otherwise
4168
                 */
4169
                bool has_jwk_claim(const typename json_traits::string_type& name) const noexcept {
22✔
4170
                        return jwk_claims.has_claim(name);
22✔
4171
                }
4172

4173
                /**
4174
                 * Get jwk claim by name
4175
                 * \return Requested claim
4176
                 * \throw std::runtime_error If claim was not present
4177
                 */
4178
                basic_claim_t get_jwk_claim(const typename json_traits::string_type& name) const {
24✔
4179
                        return jwk_claims.get_claim(name);
24✔
4180
                }
4181

4182
                /**
4183
                * Check if the jwk has any claims
4184
                * \return true is any claim is present
4185
                 */
4186
                bool empty() const noexcept { return jwk_claims.empty(); }
4187

4188
                /**
4189
                 * Get all jwk claims
4190
                 * \return Map of claims
4191
                 */
4192
                typename json_traits::object_type get_claims() const { return this->jwk_claims.claims; }
4193
        };
4194

4195
        /**
4196
         * \brief JWK Set
4197
         *
4198
         * https://tools.ietf.org/html/rfc7517
4199
         *
4200
         * A JSON object that represents a set of JWKs.  The JSON object MUST
4201
         * have a "keys" member, which is an array of JWKs.
4202
         *
4203
         * This container takes a JWKs and simplifies it to a vector of JWKs
4204
         */
4205
        template<typename json_traits>
4206
        class jwks {
4207
        public:
4208
                /// JWK instance template specialization
4209
                using jwks_t = jwk<json_traits>;
4210
                /// Type specialization for the vector of JWK
4211
                using jwks_vector_t = std::vector<jwks_t>;
4212
                using iterator = typename jwks_vector_t::iterator;
4213
                using const_iterator = typename jwks_vector_t::const_iterator;
4214

4215
                /**
4216
                 * Default constructor producing an empty object without any keys
4217
                 */
4218
                jwks() = default;
1✔
4219

4220
                /**
4221
                 * Parses a string buffer to extract the JWKS.
4222
                 * \param str buffer containing JSON object representing a JWKS
4223
                 * \throw error::invalid_json_exception or underlying JSON implation error if the JSON is
4224
                 *        invalid with regards to the JWKS specification
4225
                */
4226
                JWT_CLAIM_EXPLICIT jwks(const typename json_traits::string_type& str) {
3✔
4227
                        typename json_traits::value_type parsed_val;
3✔
4228
                        if (!json_traits::parse(parsed_val, str)) throw error::invalid_json_exception();
3✔
4229

4230
                        const details::map_of_claims<json_traits> jwks_json = json_traits::as_object(parsed_val);
3✔
4231
                        if (!jwks_json.has_claim("keys")) throw error::invalid_json_exception();
6✔
4232

4233
                        auto jwk_list = jwks_json.get_claim("keys").as_array();
3✔
4234
                        std::transform(jwk_list.begin(), jwk_list.end(), std::back_inserter(jwk_claims),
3✔
4235
                                                   [](const typename json_traits::value_type& val) { return jwks_t{val}; });
7✔
4236
                }
3✔
4237

4238
                iterator begin() { return jwk_claims.begin(); }
2✔
4239
                iterator end() { return jwk_claims.end(); }
2✔
4240
                const_iterator cbegin() const { return jwk_claims.begin(); }
9✔
4241
                const_iterator cend() const { return jwk_claims.end(); }
9✔
4242
                const_iterator begin() const { return jwk_claims.begin(); }
4243
                const_iterator end() const { return jwk_claims.end(); }
9✔
4244

4245
                /**
4246
                 * Check if a jwk with the kid is present
4247
                 * \return true if jwk was present, false otherwise
4248
                 */
4249
                bool has_jwk(const typename json_traits::string_type& key_id) const noexcept {
4✔
4250
                        return find_by_kid(key_id) != end();
4✔
4251
                }
4252

4253
                /**
4254
                 * Get jwk
4255
                 * \return Requested jwk by key_id
4256
                 * \throw std::runtime_error If jwk was not present
4257
                 */
4258
                jwks_t get_jwk(const typename json_traits::string_type& key_id) const {
5✔
4259
                        const auto maybe = find_by_kid(key_id);
5✔
4260
                        if (maybe == end()) throw error::claim_not_present_exception();
5✔
4261
                        return *maybe;
8✔
4262
                }
4263

4264
        private:
4265
                jwks_vector_t jwk_claims;
4266

4267
                const_iterator find_by_kid(const typename json_traits::string_type& key_id) const noexcept {
9✔
4268
                        return std::find_if(cbegin(), cend(), [key_id](const jwks_t& jwk) {
18✔
4269
                                if (!jwk.has_key_id()) { return false; }
13✔
4270
                                return jwk.get_key_id() == key_id;
13✔
4271
                        });
9✔
4272
                }
4273
        };
4274

4275
        /**
4276
         * Create a verifier using the given clock
4277
         * \param c Clock instance to use
4278
         * \return verifier instance
4279
         */
4280
        template<typename Clock, typename json_traits>
4281
        verifier<Clock, json_traits> verify(Clock c) {
64✔
4282
                return verifier<Clock, json_traits>(c);
64✔
4283
        }
4284

4285
        /**
4286
         * Create a builder using the given clock
4287
         * \param c Clock instance to use
4288
         * \return builder instance
4289
         */
4290
        template<typename Clock, typename json_traits>
4291
        builder<Clock, json_traits> create(Clock c) {
4292
                return builder<Clock, json_traits>(c);
4293
        }
4294

4295
        /**
4296
         * Default clock class using std::chrono::system_clock as a backend.
4297
         */
4298
        struct default_clock {
4299
                /**
4300
                 * Gets the current system time
4301
                 * \return time_point of the host system
4302
                 */
4303
                date now() const { return date::clock::now(); }
72✔
4304
        };
4305

4306
        /**
4307
         * Create a verifier using the default_clock.
4308
         *
4309
         *
4310
         *
4311
         * \param c Clock instance to use
4312
         * \return verifier instance
4313
         */
4314
        template<typename json_traits>
4315
        verifier<default_clock, json_traits> verify(default_clock c = {}) {
24✔
4316
                return verifier<default_clock, json_traits>(c);
24✔
4317
        }
4318

4319
        /**
4320
         * Return a builder instance to create a new token
4321
         */
4322
        template<typename json_traits>
4323
        builder<default_clock, json_traits> create(default_clock c = {}) {
20✔
4324
                return builder<default_clock, json_traits>(c);
20✔
4325
        }
4326

4327
        /**
4328
         * \brief Decode a token. This can be used to to help access important feild like 'x5c'
4329
         * for verifying tokens. See associated example rsa-verify.cpp for more details.
4330
         *
4331
         * \tparam json_traits JSON implementation traits
4332
         * \tparam Decode is callable, taking a string_type and returns a string_type.
4333
         *         It should ensure the padding of the input and then base64url decode and
4334
         *         return the results.
4335
         * \param token Token to decode
4336
         * \param decode function that will pad and base64url decode the token
4337
         * \return Decoded token
4338
         * \throw std::invalid_argument Token is not in correct format
4339
         * \throw std::runtime_error Base64 decoding failed or invalid json
4340
         */
4341
        template<typename json_traits, typename Decode>
4342
        decoded_jwt<json_traits> decode(const typename json_traits::string_type& token, Decode decode) {
4343
                return decoded_jwt<json_traits>(token, decode);
4344
        }
4345

4346
        /**
4347
         * Decode a token. This can be used to to help access important feild like 'x5c'
4348
         * for verifying tokens. See associated example rsa-verify.cpp for more details.
4349
         *
4350
         * \tparam json_traits JSON implementation traits
4351
         * \param token Token to decode
4352
         * \return Decoded token
4353
         * \throw std::invalid_argument Token is not in correct format
4354
         * \throw std::runtime_error Base64 decoding failed or invalid json
4355
         */
4356
        template<typename json_traits>
4357
        decoded_jwt<json_traits> decode(const typename json_traits::string_type& token) {
28✔
4358
                return decoded_jwt<json_traits>(token);
28✔
4359
        }
4360
        /**
4361
         * Parse a single JSON Web Key
4362
         * \tparam json_traits JSON implementation traits
4363
         * \param jwk_ string buffer containing the JSON object
4364
         * \return Decoded jwk
4365
         */
4366
        template<typename json_traits>
4367
        jwk<json_traits> parse_jwk(const typename json_traits::string_type& jwk_) {
4368
                return jwk<json_traits>(jwk_);
4369
        }
4370
        /**
4371
         * Parse a JSON Web Key Set. This can be used to to help access
4372
         * important feild like 'x5c' for verifying tokens. See example
4373
         * jwks-verify.cpp for more information.
4374
         *
4375
         * \tparam json_traits JSON implementation traits
4376
         * \param jwks_ string buffer containing the JSON object
4377
         * \return Parsed JSON object containing the data of the JWK SET string
4378
         * \throw std::runtime_error Token is not in correct format
4379
         */
4380
        template<typename json_traits>
4381
        jwks<json_traits> parse_jwks(const typename json_traits::string_type& jwks_) {
4382
                return jwks<json_traits>(jwks_);
4383
        }
4384
} // namespace jwt
4385

4386
template<typename json_traits>
4387
std::istream& operator>>(std::istream& is, jwt::basic_claim<json_traits>& c) {
8✔
4388
        return c.operator>>(is);
8✔
4389
}
4390

4391
template<typename json_traits>
4392
std::ostream& operator<<(std::ostream& os, const jwt::basic_claim<json_traits>& c) {
4393
        return os << c.to_json();
4394
}
4395

4396
#ifndef JWT_DISABLE_PICOJSON
4397
#include "traits/kazuho-picojson/defaults.h"
4398
#endif
4399

4400
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc