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

prince-chrismc / jwt-cpp / 22085618954

17 Feb 2026 04:03AM UTC coverage: 94.549%. Remained the same
22085618954

push

github

web-flow
:arrow_up: Update LibreSSL version up to 4.2.1 (#410)

* Update LibreSSL version to 4.2.1 in CI configuration and documentation

* update OpenSSLErrorTest for LibreSSL 4.2.0+

Add Linux LibreSSL support in CMake presets

* add debug output to failure for all ssl libraries

* fix type in libressl version check

* chore: lint

1301 of 1376 relevant lines covered (94.55%)

261.92 hits per line

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

95.95
/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 >= 0x3050300fL
61
#define JWT_OPENSSL_1_1_0
62
#else
63
#define JWT_OPENSSL_1_0_0
64
#endif
65
#endif
66

67
#if defined(LIBWOLFSSL_VERSION_HEX)
68
#define JWT_OPENSSL_1_1_1
69
#endif
70

71
#ifndef JWT_CLAIM_EXPLICIT
72
#define JWT_CLAIM_EXPLICIT explicit
73
#endif
74

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

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

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

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

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

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

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

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

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

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

487
                private:
488
                        EVP_PKEY* m_key{nullptr};
489

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

499
                inline std::unique_ptr<BIO, decltype(&BIO_free_all)> make_mem_buf_bio() {
212✔
500
                        return std::unique_ptr<BIO, decltype(&BIO_free_all)>(BIO_new(BIO_s_mem()), BIO_free_all);
212✔
501
                }
502

503
                inline std::unique_ptr<BIO, decltype(&BIO_free_all)> make_mem_buf_bio(const std::string& data) {
33✔
504
                        return std::unique_ptr<BIO, decltype(&BIO_free_all)>(
505
#if OPENSSL_VERSION_NUMBER <= 0x10100003L
506
                                BIO_new_mem_buf(const_cast<char*>(data.data()), static_cast<int>(data.size())), BIO_free_all
507
#else
508
                                BIO_new_mem_buf(data.data(), static_cast<int>(data.size())), BIO_free_all
66✔
509
#endif
510
                        );
66✔
511
                }
512

513
                template<typename error_category = error::rsa_error>
514
                std::string write_bio_to_string(std::unique_ptr<BIO, decltype(&BIO_free_all)>& bio_out, std::error_code& ec) {
30✔
515
                        char* ptr = nullptr;
30✔
516
                        auto len = BIO_get_mem_data(bio_out.get(), &ptr);
30✔
517
                        if (len <= 0 || ptr == nullptr) {
30✔
518
                                ec = error_category::convert_to_pem_failed;
13✔
519
                                return {};
13✔
520
                        }
521
                        return {ptr, static_cast<size_t>(len)};
51✔
522
                }
523

524
                inline std::unique_ptr<EVP_MD_CTX, void (*)(EVP_MD_CTX*)> make_evp_md_ctx() {
94✔
525
                        return
526
#ifdef JWT_OPENSSL_1_0_0
527
                                std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)>(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy);
528
#else
529
                                std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
94✔
530
#endif
531
                }
532

533
                /**
534
                 * \brief Extract the public key of a pem certificate
535
                 *
536
                 * \tparam error_category        jwt::error enum category to match with the keys being used
537
                 * \param certstr                        String containing the certificate encoded as pem
538
                 * \param pw                                Password used to decrypt certificate (leave empty if not encrypted)
539
                 * \param ec                                error_code for error_detection (gets cleared if no error occurred)
540
                 */
541
                template<typename error_category = error::rsa_error>
542
                std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw, std::error_code& ec) {
33✔
543
                        ec.clear();
33✔
544
                        auto certbio = make_mem_buf_bio(certstr);
33✔
545
                        auto keybio = make_mem_buf_bio();
33✔
546
                        if (!certbio || !keybio) {
33✔
547
                                ec = error_category::create_mem_bio_failed;
4✔
548
                                return {};
4✔
549
                        }
550

551
                        std::unique_ptr<X509, decltype(&X509_free)> cert(
29✔
552
                                PEM_read_bio_X509(certbio.get(), nullptr, nullptr, const_cast<char*>(pw.c_str())), X509_free);
29✔
553
                        if (!cert) {
29✔
554
                                ec = error_category::cert_load_failed;
4✔
555
                                return {};
4✔
556
                        }
557
                        std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> key(X509_get_pubkey(cert.get()), EVP_PKEY_free);
25✔
558
                        if (!key) {
25✔
559
                                ec = error_category::get_key_failed;
4✔
560
                                return {};
4✔
561
                        }
562
                        if (PEM_write_bio_PUBKEY(keybio.get(), key.get()) == 0) {
21✔
563
                                ec = error_category::write_key_failed;
4✔
564
                                return {};
4✔
565
                        }
566

567
                        return write_bio_to_string<error_category>(keybio, ec);
17✔
568
                }
33✔
569

570
                /**
571
                 * \brief Extract the public key of a pem certificate
572
                 *
573
                 * \tparam error_category        jwt::error enum category to match with the keys being used
574
                 * \param certstr                        String containing the certificate encoded as pem
575
                 * \param pw                                Password used to decrypt certificate (leave empty if not encrypted)
576
                 * \throw                                        templated error_category's type exception if an error occurred
577
                 */
578
                template<typename error_category = error::rsa_error>
579
                std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw = "") {
6✔
580
                        std::error_code ec;
6✔
581
                        auto res = extract_pubkey_from_cert<error_category>(certstr, pw, ec);
6✔
582
                        error::throw_if_error(ec);
6✔
583
                        return res;
2✔
584
                }
5✔
585

586
                /**
587
                 * \brief Convert the certificate provided as DER to PEM.
588
                 *
589
                 * \param cert_der_str         String containing the certificate encoded as base64 DER
590
                 * \param ec                        error_code for error_detection (gets cleared if no error occurs)
591
                 */
592
                inline std::string convert_der_to_pem(const std::string& cert_der_str, std::error_code& ec) {
13✔
593
                        ec.clear();
13✔
594

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

597
                        std::unique_ptr<X509, decltype(&X509_free)> cert(
598
                                d2i_X509(NULL, &c_str, static_cast<int>(cert_der_str.size())), X509_free);
13✔
599
                        auto certbio = make_mem_buf_bio();
13✔
600
                        if (!cert || !certbio) {
13✔
601
                                ec = error::rsa_error::create_mem_bio_failed;
3✔
602
                                return {};
3✔
603
                        }
604

605
                        if (!PEM_write_bio_X509(certbio.get(), cert.get())) {
10✔
606
                                ec = error::rsa_error::write_cert_failed;
3✔
607
                                return {};
3✔
608
                        }
609

610
                        return write_bio_to_string(certbio, ec);
7✔
611
                }
13✔
612

613
                /**
614
                 * \brief Convert the certificate provided as base64 DER to PEM.
615
                 *
616
                 * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
617
                 * [here](https://tools.ietf.org/html/rfc7517#section-4.7).
618
                 *
619
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
620
                 * It should ensure the padding of the input and then base64 decode and return
621
                 * the results.
622
                 *
623
                 * \param cert_base64_der_str         String containing the certificate encoded as base64 DER
624
                 * \param decode                                 The function to decode the cert
625
                 * \param ec                                        error_code for error_detection (gets cleared if no error occurs)
626
                 */
627
                template<typename Decode>
628
                std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode,
12✔
629
                                                                                          std::error_code& ec) {
630
                        ec.clear();
12✔
631
                        const auto decoded_str = decode(cert_base64_der_str);
12✔
632
                        return convert_der_to_pem(decoded_str, ec);
24✔
633
                }
12✔
634

635
                /**
636
                 * \brief Convert the certificate provided as base64 DER to PEM.
637
                 *
638
                 * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
639
                 * [here](https://tools.ietf.org/html/rfc7517#section-4.7)
640
                 *
641
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
642
                 * It should ensure the padding of the input and then base64 decode and return
643
                 * the results.
644
                 *
645
                 * \param cert_base64_der_str         String containing the certificate encoded as base64 DER
646
                 * \param decode                                 The function to decode the cert
647
                 * \throw                                                rsa_exception if an error occurred
648
                 */
649
                template<typename Decode>
650
                std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode) {
651
                        std::error_code ec;
652
                        auto res = convert_base64_der_to_pem(cert_base64_der_str, std::move(decode), ec);
653
                        error::throw_if_error(ec);
654
                        return res;
655
                }
656

657
                /**
658
                 * \brief Convert the certificate provided as DER to PEM.
659
                 *
660
                 * \param cert_der_str         String containing the DER certificate
661
                 * \throw                                rsa_exception if an error occurred
662
                 */
663
                inline std::string convert_der_to_pem(const std::string& cert_der_str) {
1✔
664
                        std::error_code ec;
1✔
665
                        auto res = convert_der_to_pem(cert_der_str, ec);
1✔
666
                        error::throw_if_error(ec);
1✔
667
                        return res;
2✔
668
                }
×
669

670
#ifndef JWT_DISABLE_BASE64
671
                /**
672
                 * \brief Convert the certificate provided as base64 DER to PEM.
673
                 *
674
                 * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
675
                 * [here](https://tools.ietf.org/html/rfc7517#section-4.7)
676
                 *
677
                 * \param cert_base64_der_str         String containing the certificate encoded as base64 DER
678
                 * \param ec                                        error_code for error_detection (gets cleared if no error occurs)
679
                 */
680
                inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, std::error_code& ec) {
12✔
681
                        auto decode = [](const std::string& token) {
12✔
682
                                return base::decode<alphabet::base64>(base::pad<alphabet::base64>(token));
12✔
683
                        };
684
                        return convert_base64_der_to_pem(cert_base64_der_str, std::move(decode), ec);
24✔
685
                }
686

687
                /**
688
                 * \brief Convert the certificate provided as base64 DER to PEM.
689
                 *
690
                 * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
691
                 * [here](https://tools.ietf.org/html/rfc7517#section-4.7)
692
                 *
693
                 * \param cert_base64_der_str         String containing the certificate encoded as base64 DER
694
                 * \throw                                                rsa_exception if an error occurred
695
                 */
696
                inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str) {
7✔
697
                        std::error_code ec;
7✔
698
                        auto res = convert_base64_der_to_pem(cert_base64_der_str, ec);
7✔
699
                        error::throw_if_error(ec);
7✔
700
                        return res;
2✔
701
                }
6✔
702
#endif
703
                /**
704
                 * \brief Load a public key from a string.
705
                 *
706
                 * The string should contain a pem encoded certificate or public key
707
                 *
708
                 * \tparam error_category        jwt::error enum category to match with the keys being used
709
                 * \param key                String containing the certificate encoded as pem
710
                 * \param password        Password used to decrypt certificate (leave empty if not encrypted)
711
                 * \param ec                error_code for error_detection (gets cleared if no error occurs)
712
                 */
713
                template<typename error_category = error::rsa_error>
714
                evp_pkey_handle load_public_key_from_string(const std::string& key, const std::string& password,
83✔
715
                                                                                                        std::error_code& ec) {
716
                        ec.clear();
83✔
717
                        auto pubkey_bio = make_mem_buf_bio();
83✔
718
                        if (!pubkey_bio) {
83✔
719
                                ec = error_category::create_mem_bio_failed;
8✔
720
                                return {};
8✔
721
                        }
722
                        if (key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") {
75✔
723
                                auto epkey = helper::extract_pubkey_from_cert<error_category>(key, password, ec);
21✔
724
                                if (ec) return {};
21✔
725
                                // Ensure the size fits into an int before casting
726
                                if (epkey.size() > static_cast<std::size_t>((std::numeric_limits<int>::max)())) {
9✔
727
                                        ec = error_category::load_key_bio_write; // Add an appropriate error here
×
728
                                        return {};
×
729
                                }
730
                                int len = static_cast<int>(epkey.size());
9✔
731
                                if (BIO_write(pubkey_bio.get(), epkey.data(), len) != len) {
9✔
732
                                        ec = error_category::load_key_bio_write;
4✔
733
                                        return {};
4✔
734
                                }
735
                        } else {
21✔
736
                                // Ensure the size fits into an int before casting
737
                                if (key.size() > static_cast<std::size_t>((std::numeric_limits<int>::max)())) {
54✔
738
                                        ec = error_category::load_key_bio_write; // Add an appropriate error here
×
739
                                        return {};
×
740
                                }
741
                                int len = static_cast<int>(key.size());
54✔
742
                                if (BIO_write(pubkey_bio.get(), key.data(), len) != len) {
54✔
743
                                        ec = error_category::load_key_bio_write;
4✔
744
                                        return {};
4✔
745
                                }
746
                        }
747

748
                        evp_pkey_handle pkey(PEM_read_bio_PUBKEY(
55✔
749
                                pubkey_bio.get(), nullptr, nullptr,
750
                                (void*)password.data())); // NOLINT(google-readability-casting) requires `const_cast`
55✔
751
                        if (!pkey) ec = error_category::load_key_bio_read;
55✔
752
                        return pkey;
55✔
753
                }
83✔
754

755
                /**
756
                 * \brief Load a public key from a string.
757
                 *
758
                 * The string should contain a pem encoded certificate or public key
759
                 *
760
                 * \tparam error_category        jwt::error enum category to match with the keys being used
761
                 * \param key                                String containing the certificate encoded as pem
762
                 * \param password                        Password used to decrypt certificate (leave empty if not encrypted)
763
                 * \throw                                        Templated error_category's type exception if an error occurred
764
                 */
765
                template<typename error_category = error::rsa_error>
766
                inline evp_pkey_handle load_public_key_from_string(const std::string& key, const std::string& password = "") {
38✔
767
                        std::error_code ec;
38✔
768
                        auto res = load_public_key_from_string<error_category>(key, password, ec);
38✔
769
                        error::throw_if_error(ec);
38✔
770
                        return res;
40✔
771
                }
18✔
772

773
                /**
774
                 * \brief Load a private key from a string.
775
                 *
776
                 * \tparam error_category        jwt::error enum category to match with the keys being used
777
                 * \param key                                String containing a private key as pem
778
                 * \param password                        Password used to decrypt key (leave empty if not encrypted)
779
                 * \param ec                                error_code for error_detection (gets cleared if no error occurs)
780
                 */
781
                template<typename error_category = error::rsa_error>
782
                inline evp_pkey_handle load_private_key_from_string(const std::string& key, const std::string& password,
69✔
783
                                                                                                                        std::error_code& ec) {
784
                        ec.clear();
69✔
785
                        auto private_key_bio = make_mem_buf_bio();
69✔
786
                        if (!private_key_bio) {
69✔
787
                                ec = error_category::create_mem_bio_failed;
5✔
788
                                return {};
5✔
789
                        }
790
                        const int len = static_cast<int>(key.size());
64✔
791
                        if (BIO_write(private_key_bio.get(), key.data(), len) != len) {
64✔
792
                                ec = error_category::load_key_bio_write;
5✔
793
                                return {};
5✔
794
                        }
795
                        evp_pkey_handle pkey(
59✔
796
                                PEM_read_bio_PrivateKey(private_key_bio.get(), nullptr, nullptr, const_cast<char*>(password.c_str())));
59✔
797
                        if (!pkey) ec = error_category::load_key_bio_read;
59✔
798
                        return pkey;
59✔
799
                }
69✔
800

801
                /**
802
                 * \brief Load a private key from a string.
803
                 *
804
                 * \tparam error_category        jwt::error enum category to match with the keys being used
805
                 * \param key                                String containing a private key as pem
806
                 * \param password                        Password used to decrypt key (leave empty if not encrypted)
807
                 * \throw                                        Templated error_category's type exception if an error occurred
808
                 */
809
                template<typename error_category = error::rsa_error>
810
                inline evp_pkey_handle load_private_key_from_string(const std::string& key, const std::string& password = "") {
33✔
811
                        std::error_code ec;
33✔
812
                        auto res = load_private_key_from_string<error_category>(key, password, ec);
33✔
813
                        error::throw_if_error(ec);
33✔
814
                        return res;
50✔
815
                }
8✔
816

817
                /**
818
                 * \brief Load a public key from a string.
819
                 *
820
                 * The string should contain a pem encoded certificate or public key
821
                 *
822
                 * \deprecated Use the templated version helper::load_private_key_from_string with error::ecdsa_error
823
                 *
824
                 * \param key                String containing the certificate encoded as pem
825
                 * \param password        Password used to decrypt certificate (leave empty if not encrypted)
826
                 * \param ec                error_code for error_detection (gets cleared if no error occurs)
827
                 */
828
                inline evp_pkey_handle load_public_ec_key_from_string(const std::string& key, const std::string& password,
829
                                                                                                                          std::error_code& ec) {
830
                        return load_public_key_from_string<error::ecdsa_error>(key, password, ec);
831
                }
832

833
                /**
834
                 * Convert a OpenSSL BIGNUM to a std::string
835
                 * \param bn BIGNUM to convert
836
                 * \return bignum as string
837
                 */
838
                inline
839
#ifdef JWT_OPENSSL_1_0_0
840
                        std::string
841
                        bn2raw(BIGNUM* bn)
842
#else
843
                        std::string
844
                        bn2raw(const BIGNUM* bn)
10✔
845
#endif
846
                {
847
                        std::string res(BN_num_bytes(bn), '\0');
10✔
848
                        BN_bn2bin(bn, (unsigned char*)res.data()); // NOLINT(google-readability-casting) requires `const_cast`
10✔
849
                        return res;
10✔
850
                }
×
851
                /**
852
                 * Convert an std::string to a OpenSSL BIGNUM
853
                 * \param raw String to convert
854
                 * \param ec  error_code for error_detection (gets cleared if no error occurs)
855
                 * \return BIGNUM representation
856
                 */
857
                inline std::unique_ptr<BIGNUM, decltype(&BN_free)> raw2bn(const std::string& raw, std::error_code& ec) {
84✔
858
                        auto bn =
859
                                BN_bin2bn(reinterpret_cast<const unsigned char*>(raw.data()), static_cast<int>(raw.size()), nullptr);
84✔
860
                        // https://www.openssl.org/docs/man1.1.1/man3/BN_bin2bn.html#RETURN-VALUES
861
                        if (!bn) {
84✔
862
                                ec = error::rsa_error::set_rsa_failed;
×
863
                                return {nullptr, BN_free};
×
864
                        }
865
                        return {bn, BN_free};
84✔
866
                }
867
                /**
868
                 * Convert an std::string to a OpenSSL BIGNUM
869
                 * \param raw String to convert
870
                 * \return BIGNUM representation
871
                 */
872
                inline std::unique_ptr<BIGNUM, decltype(&BN_free)> raw2bn(const std::string& raw) {
873
                        std::error_code ec;
874
                        auto res = raw2bn(raw, ec);
875
                        error::throw_if_error(ec);
876
                        return res;
877
                }
878

879
                /**
880
                 * \brief Load a public key from a string.
881
                 *
882
                 * The string should contain a pem encoded certificate or public key
883
                 *
884
                 * \deprecated Use the templated version helper::load_private_key_from_string with error::ecdsa_error
885
                 *
886
                 * \param key                String containing the certificate or key encoded as pem
887
                 * \param password        Password used to decrypt certificate or key (leave empty if not encrypted)
888
                 * \throw                        ecdsa_exception if an error occurred
889
                 */
890
                inline evp_pkey_handle load_public_ec_key_from_string(const std::string& key,
38✔
891
                                                                                                                          const std::string& password = "") {
892
                        std::error_code ec;
38✔
893
                        auto res = load_public_key_from_string<error::ecdsa_error>(key, password, ec);
38✔
894
                        error::throw_if_error(ec);
38✔
895
                        return res;
54✔
896
                }
11✔
897

898
                /**
899
                 * \brief Load a private key from a string.
900
                 *
901
                 * \deprecated Use the templated version helper::load_private_key_from_string with error::ecdsa_error
902
                 *
903
                 * \param key                String containing a private key as pem
904
                 * \param password        Password used to decrypt key (leave empty if not encrypted)
905
                 * \param ec                error_code for error_detection (gets cleared if no error occurs)
906
                 */
907
                inline evp_pkey_handle load_private_ec_key_from_string(const std::string& key, const std::string& password,
908
                                                                                                                           std::error_code& ec) {
909
                        return load_private_key_from_string<error::ecdsa_error>(key, password, ec);
910
                }
911

912
                /**
913
                * \brief create public key from modulus and exponent. This is defined in
914
                * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3)
915
                * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter.
916
                *
917
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
918
                 * It should ensure the padding of the input and then base64url decode and
919
                 * return the results.
920
                * \param modulus        string containing base64url encoded modulus
921
                * \param exponent        string containing base64url encoded exponent
922
                * \param decode         The function to decode the RSA parameters
923
                * \param ec                        error_code for error_detection (gets cleared if no error occur
924
                * \return                         public key in PEM format
925
                */
926
                template<typename Decode>
927
                std::string create_public_key_from_rsa_components(const std::string& modulus, const std::string& exponent,
19✔
928
                                                                                                                  Decode decode, std::error_code& ec) {
929
                        ec.clear();
19✔
930
                        auto decoded_modulus = decode(modulus);
19✔
931
                        auto decoded_exponent = decode(exponent);
19✔
932

933
                        auto n = helper::raw2bn(decoded_modulus, ec);
19✔
934
                        if (ec) return {};
19✔
935
                        auto e = helper::raw2bn(decoded_exponent, ec);
19✔
936
                        if (ec) return {};
19✔
937

938
#if defined(JWT_OPENSSL_3_0)
939
                        // OpenSSL deprecated mutable keys and there is a new way for making them
940
                        // https://mta.openssl.org/pipermail/openssl-users/2021-July/013994.html
941
                        // https://www.openssl.org/docs/man3.1/man3/OSSL_PARAM_BLD_new.html#Example-2
942
                        std::unique_ptr<OSSL_PARAM_BLD, decltype(&OSSL_PARAM_BLD_free)> param_bld(OSSL_PARAM_BLD_new(),
19✔
943
                                                                                                                                                                          OSSL_PARAM_BLD_free);
19✔
944
                        if (!param_bld) {
19✔
945
                                ec = error::rsa_error::create_context_failed;
2✔
946
                                return {};
2✔
947
                        }
948

949
                        if (OSSL_PARAM_BLD_push_BN(param_bld.get(), "n", n.get()) != 1 ||
32✔
950
                                OSSL_PARAM_BLD_push_BN(param_bld.get(), "e", e.get()) != 1) {
15✔
951
                                ec = error::rsa_error::set_rsa_failed;
2✔
952
                                return {};
2✔
953
                        }
954

955
                        std::unique_ptr<OSSL_PARAM, decltype(&OSSL_PARAM_free)> params(OSSL_PARAM_BLD_to_param(param_bld.get()),
15✔
956
                                                                                                                                                   OSSL_PARAM_free);
15✔
957
                        if (!params) {
15✔
958
                                ec = error::rsa_error::set_rsa_failed;
2✔
959
                                return {};
2✔
960
                        }
961

962
                        std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
13✔
963
                                EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr), EVP_PKEY_CTX_free);
13✔
964
                        if (!ctx) {
13✔
965
                                ec = error::rsa_error::create_context_failed;
2✔
966
                                return {};
2✔
967
                        }
968

969
                        // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html#EXAMPLES
970
                        // Error codes based on https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_fromdata_init.html#RETURN-VALUES
971
                        EVP_PKEY* pkey = NULL;
11✔
972
                        if (EVP_PKEY_fromdata_init(ctx.get()) <= 0 ||
20✔
973
                                EVP_PKEY_fromdata(ctx.get(), &pkey, EVP_PKEY_KEYPAIR, params.get()) <= 0) {
9✔
974
                                // It's unclear if this can fail after allocating but free it anyways
975
                                // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html
976
                                EVP_PKEY_free(pkey);
4✔
977

978
                                ec = error::rsa_error::cert_load_failed;
4✔
979
                                return {};
4✔
980
                        }
981

982
                        // Transfer ownership so we get ref counter and cleanup
983
                        evp_pkey_handle rsa(pkey);
7✔
984

985
#else
986
                        std::unique_ptr<RSA, decltype(&RSA_free)> rsa(RSA_new(), RSA_free);
987

988
#if defined(JWT_OPENSSL_1_1_1) || defined(JWT_OPENSSL_1_1_0)
989
                        // After this RSA_free will also free the n and e big numbers
990
                        // See https://github.com/Thalhammer/jwt-cpp/pull/298#discussion_r1282619186
991
                        if (RSA_set0_key(rsa.get(), n.get(), e.get(), nullptr) == 1) {
992
                                // This can only fail we passed in NULL for `n` or `e`
993
                                // https://github.com/openssl/openssl/blob/d6e4056805f54bb1a0ef41fa3a6a35b70c94edba/crypto/rsa/rsa_lib.c#L396
994
                                // So to make sure there is no memory leak, we hold the references
995
                                n.release();
996
                                e.release();
997
                        } else {
998
                                ec = error::rsa_error::set_rsa_failed;
999
                                return {};
1000
                        }
1001
#elif defined(JWT_OPENSSL_1_0_0)
1002
                        rsa->e = e.release();
1003
                        rsa->n = n.release();
1004
                        rsa->d = nullptr;
1005
#endif
1006
#endif
1007

1008
                        auto pub_key_bio = make_mem_buf_bio();
7✔
1009
                        if (!pub_key_bio) {
7✔
1010
                                ec = error::rsa_error::create_mem_bio_failed;
2✔
1011
                                return {};
2✔
1012
                        }
1013

1014
                        auto write_pem_to_bio =
5✔
1015
#if defined(JWT_OPENSSL_3_0)
1016
                                // https://www.openssl.org/docs/man3.1/man3/PEM_write_bio_RSA_PUBKEY.html
1017
                                &PEM_write_bio_PUBKEY;
1018
#else
1019
                                &PEM_write_bio_RSA_PUBKEY;
1020
#endif
1021
                        if (write_pem_to_bio(pub_key_bio.get(), rsa.get()) != 1) {
5✔
1022
                                ec = error::rsa_error::load_key_bio_write;
2✔
1023
                                return {};
2✔
1024
                        }
1025

1026
                        return write_bio_to_string<error::rsa_error>(pub_key_bio, ec);
3✔
1027
                }
19✔
1028

1029
                /**
1030
                * Create public key from modulus and exponent. This is defined in
1031
                * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3)
1032
                * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter.
1033
                *
1034
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
1035
                 * It should ensure the padding of the input and then base64url decode and
1036
                 * return the results.
1037
                * \param modulus        string containing base64url encoded modulus
1038
                * \param exponent        string containing base64url encoded exponent
1039
                * \param decode         The function to decode the RSA parameters
1040
                * \return public key in PEM format
1041
                */
1042
                template<typename Decode>
1043
                std::string create_public_key_from_rsa_components(const std::string& modulus, const std::string& exponent,
1044
                                                                                                                  Decode decode) {
1045
                        std::error_code ec;
1046
                        auto res = create_public_key_from_rsa_components(modulus, exponent, decode, ec);
1047
                        error::throw_if_error(ec);
1048
                        return res;
1049
                }
1050

1051
#ifndef JWT_DISABLE_BASE64
1052
                /**
1053
                * Create public key from modulus and exponent. This is defined in
1054
                * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3)
1055
                * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter.
1056
                *
1057
                * \param modulus        string containing base64 encoded modulus
1058
                * \param exponent        string containing base64 encoded exponent
1059
                * \param ec                        error_code for error_detection (gets cleared if no error occur
1060
                * \return public key in PEM format
1061
                */
1062
                inline std::string create_public_key_from_rsa_components(const std::string& modulus,
19✔
1063
                                                                                                                                 const std::string& exponent, std::error_code& ec) {
1064
                        auto decode = [](const std::string& token) {
38✔
1065
                                return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(token));
38✔
1066
                        };
1067
                        return create_public_key_from_rsa_components(modulus, exponent, std::move(decode), ec);
38✔
1068
                }
1069
                /**
1070
                * Create public key from modulus and exponent. This is defined in
1071
                * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3)
1072
                * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter.
1073
                *
1074
                * \param modulus        string containing base64url encoded modulus
1075
                * \param exponent        string containing base64url encoded exponent
1076
                * \return public key in PEM format
1077
                */
1078
                inline std::string create_public_key_from_rsa_components(const std::string& modulus,
10✔
1079
                                                                                                                                 const std::string& exponent) {
1080
                        std::error_code ec;
10✔
1081
                        auto res = create_public_key_from_rsa_components(modulus, exponent, ec);
10✔
1082
                        error::throw_if_error(ec);
10✔
1083
                        return res;
2✔
1084
                }
9✔
1085
#endif
1086
                /**
1087
                 * \brief Load a private key from a string.
1088
                 *
1089
                 * \deprecated Use the templated version helper::load_private_key_from_string with error::ecdsa_error
1090
                 *
1091
                 * \param key                String containing a private key as pem
1092
                 * \param password        Password used to decrypt key (leave empty if not encrypted)
1093
                 * \throw                        ecdsa_exception if an error occurred
1094
                 */
1095
                inline evp_pkey_handle load_private_ec_key_from_string(const std::string& key,
33✔
1096
                                                                                                                           const std::string& password = "") {
1097
                        std::error_code ec;
33✔
1098
                        auto res = load_private_key_from_string<error::ecdsa_error>(key, password, ec);
33✔
1099
                        error::throw_if_error(ec);
33✔
1100
                        return res;
60✔
1101
                }
3✔
1102

1103
#if defined(JWT_OPENSSL_3_0)
1104

1105
                /**
1106
                 * \brief Convert a curve name to a group name.
1107
                 *
1108
                 * \param curve        string containing curve name
1109
                 * \param ec        error_code for error_detection
1110
                 * \return                 group name
1111
                 */
1112
                inline std::string curve2group(const std::string curve, std::error_code& ec) {
19✔
1113
                        if (curve == "P-256") {
19✔
1114
                                return "prime256v1";
×
1115
                        } else if (curve == "P-384") {
19✔
1116
                                return "secp384r1";
38✔
1117
                        } else if (curve == "P-521") {
×
1118
                                return "secp521r1";
×
1119
                        } else {
1120
                                ec = jwt::error::ecdsa_error::unknown_curve;
×
1121
                                return {};
×
1122
                        }
1123
                }
1124

1125
#else
1126

1127
                /**
1128
                 * \brief Convert a curve name to an ID.
1129
                 *
1130
                 * \param curve        string containing curve name
1131
                 * \param ec        error_code for error_detection
1132
                 * \return                 ID
1133
                 */
1134
                inline int curve2nid(const std::string curve, std::error_code& ec) {
1135
                        if (curve == "P-256") {
1136
                                return NID_X9_62_prime256v1;
1137
                        } else if (curve == "P-384") {
1138
                                return NID_secp384r1;
1139
                        } else if (curve == "P-521") {
1140
                                return NID_secp521r1;
1141
                        } else {
1142
                                ec = jwt::error::ecdsa_error::unknown_curve;
1143
                                return {};
1144
                        }
1145
                }
1146

1147
#endif
1148

1149
                /**
1150
                 * Create public key from curve name and coordinates. This is defined in
1151
                 * [RFC 7518 Section 6.2](https://www.rfc-editor.org/rfc/rfc7518#section-6.2)
1152
                 * Using the required "crv" (Curve), "x" (X Coordinate) and "y" (Y Coordinate) Parameters.
1153
                 *
1154
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
1155
                 * It should ensure the padding of the input and then base64url decode and
1156
                 * return the results.
1157
                 * \param curve        string containing curve name
1158
                 * \param x                string containing base64url encoded x coordinate
1159
                 * \param y                string containing base64url encoded y coordinate
1160
                 * \param decode        The function to decode the RSA parameters
1161
                 * \param ec                error_code for error_detection (gets cleared if no error occur
1162
                 * \return                 public key in PEM format
1163
                 */
1164
                template<typename Decode>
1165
                std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
21✔
1166
                                                                                                                 const std::string& y, Decode decode, std::error_code& ec) {
1167
                        ec.clear();
21✔
1168
                        auto decoded_x = decode(x);
21✔
1169
                        auto decoded_y = decode(y);
21✔
1170

1171
#if defined(JWT_OPENSSL_3_0)
1172
                        // OpenSSL deprecated mutable keys and there is a new way for making them
1173
                        // https://mta.openssl.org/pipermail/openssl-users/2021-July/013994.html
1174
                        // https://www.openssl.org/docs/man3.1/man3/OSSL_PARAM_BLD_new.html#Example-2
1175
                        std::unique_ptr<OSSL_PARAM_BLD, decltype(&OSSL_PARAM_BLD_free)> param_bld(OSSL_PARAM_BLD_new(),
21✔
1176
                                                                                                                                                                          OSSL_PARAM_BLD_free);
21✔
1177
                        if (!param_bld) {
21✔
1178
                                ec = error::ecdsa_error::create_context_failed;
2✔
1179
                                return {};
2✔
1180
                        }
1181

1182
                        std::string group = helper::curve2group(curve, ec);
19✔
1183
                        if (ec) return {};
19✔
1184

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

1188
                        if (OSSL_PARAM_BLD_push_utf8_string(param_bld.get(), "group", group.data(), group.size()) != 1 ||
36✔
1189
                                OSSL_PARAM_BLD_push_octet_string(param_bld.get(), "pub", pub.data(), pub.size()) != 1) {
17✔
1190
                                ec = error::ecdsa_error::set_ecdsa_failed;
4✔
1191
                                return {};
4✔
1192
                        }
1193

1194
                        std::unique_ptr<OSSL_PARAM, decltype(&OSSL_PARAM_free)> params(OSSL_PARAM_BLD_to_param(param_bld.get()),
15✔
1195
                                                                                                                                                   OSSL_PARAM_free);
15✔
1196
                        if (!params) {
15✔
1197
                                ec = error::ecdsa_error::set_ecdsa_failed;
2✔
1198
                                return {};
2✔
1199
                        }
1200

1201
                        std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
13✔
1202
                                EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr), EVP_PKEY_CTX_free);
13✔
1203
                        if (!ctx) {
13✔
1204
                                ec = error::ecdsa_error::create_context_failed;
2✔
1205
                                return {};
2✔
1206
                        }
1207

1208
                        // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html#EXAMPLES
1209
                        // Error codes based on https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_fromdata_init.html#RETURN-VALUES
1210
                        EVP_PKEY* pkey = NULL;
11✔
1211
                        if (EVP_PKEY_fromdata_init(ctx.get()) <= 0 ||
20✔
1212
                                EVP_PKEY_fromdata(ctx.get(), &pkey, EVP_PKEY_KEYPAIR, params.get()) <= 0) {
9✔
1213
                                // It's unclear if this can fail after allocating but free it anyways
1214
                                // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html
1215
                                EVP_PKEY_free(pkey);
4✔
1216

1217
                                ec = error::ecdsa_error::cert_load_failed;
4✔
1218
                                return {};
4✔
1219
                        }
1220

1221
                        // Transfer ownership so we get ref counter and cleanup
1222
                        evp_pkey_handle ecdsa(pkey);
7✔
1223

1224
#else
1225
                        int nid = helper::curve2nid(curve, ec);
1226
                        if (ec) return {};
1227

1228
                        auto qx = helper::raw2bn(decoded_x, ec);
1229
                        if (ec) return {};
1230
                        auto qy = helper::raw2bn(decoded_y, ec);
1231
                        if (ec) return {};
1232

1233
                        std::unique_ptr<EC_GROUP, decltype(&EC_GROUP_free)> ecgroup(EC_GROUP_new_by_curve_name(nid), EC_GROUP_free);
1234
                        if (!ecgroup) {
1235
                                ec = error::ecdsa_error::set_ecdsa_failed;
1236
                                return {};
1237
                        }
1238

1239
                        EC_GROUP_set_asn1_flag(ecgroup.get(), OPENSSL_EC_NAMED_CURVE);
1240

1241
                        std::unique_ptr<EC_POINT, decltype(&EC_POINT_free)> ecpoint(EC_POINT_new(ecgroup.get()), EC_POINT_free);
1242
                        if (!ecpoint ||
1243
                                EC_POINT_set_affine_coordinates_GFp(ecgroup.get(), ecpoint.get(), qx.get(), qy.get(), nullptr) != 1) {
1244
                                ec = error::ecdsa_error::set_ecdsa_failed;
1245
                                return {};
1246
                        }
1247

1248
                        std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> ecdsa(EC_KEY_new(), EC_KEY_free);
1249
                        if (!ecdsa || EC_KEY_set_group(ecdsa.get(), ecgroup.get()) != 1 ||
1250
                                EC_KEY_set_public_key(ecdsa.get(), ecpoint.get()) != 1) {
1251
                                ec = error::ecdsa_error::set_ecdsa_failed;
1252
                                return {};
1253
                        }
1254

1255
#endif
1256

1257
                        auto pub_key_bio = make_mem_buf_bio();
7✔
1258
                        if (!pub_key_bio) {
7✔
1259
                                ec = error::ecdsa_error::create_mem_bio_failed;
2✔
1260
                                return {};
2✔
1261
                        }
1262

1263
                        auto write_pem_to_bio =
5✔
1264
#if defined(JWT_OPENSSL_3_0)
1265
                                // https://www.openssl.org/docs/man3.1/man3/PEM_write_bio_EC_PUBKEY.html
1266
                                &PEM_write_bio_PUBKEY;
1267
#else
1268
                                &PEM_write_bio_EC_PUBKEY;
1269
#endif
1270
                        if (write_pem_to_bio(pub_key_bio.get(), ecdsa.get()) != 1) {
5✔
1271
                                ec = error::ecdsa_error::load_key_bio_write;
2✔
1272
                                return {};
2✔
1273
                        }
1274

1275
                        return write_bio_to_string<error::ecdsa_error>(pub_key_bio, ec);
3✔
1276
                }
21✔
1277

1278
                /**
1279
                * Create public key from curve name and coordinates. This is defined in
1280
                * [RFC 7518 Section 6.2](https://www.rfc-editor.org/rfc/rfc7518#section-6.2)
1281
                * Using the required "crv" (Curve), "x" (X Coordinate) and "y" (Y Coordinate) Parameters.
1282
                *
1283
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
1284
                 * It should ensure the padding of the input and then base64url decode and
1285
                 * return the results.
1286
                * \param curve        string containing curve name
1287
                * \param x                string containing base64url encoded x coordinate
1288
                * \param y                string containing base64url encoded y coordinate
1289
                * \param decode The function to decode the RSA parameters
1290
                * \return public key in PEM format
1291
                */
1292
                template<typename Decode>
1293
                std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
1294
                                                                                                                 const std::string& y, Decode decode) {
1295
                        std::error_code ec;
1296
                        auto res = create_public_key_from_ec_components(curve, x, y, decode, ec);
1297
                        error::throw_if_error(ec);
1298
                        return res;
1299
                }
1300

1301
#ifndef JWT_DISABLE_BASE64
1302
                /**
1303
                * Create public key from curve name and coordinates. This is defined in
1304
                * [RFC 7518 Section 6.2](https://www.rfc-editor.org/rfc/rfc7518#section-6.2)
1305
                * Using the required "crv" (Curve), "x" (X Coordinate) and "y" (Y Coordinate) Parameters.
1306
                *
1307
                * \param curve        string containing curve name
1308
                * \param x                string containing base64url encoded x coordinate
1309
                * \param y                string containing base64url encoded y coordinate
1310
                * \param ec                error_code for error_detection (gets cleared if no error occur
1311
                * \return public key in PEM format
1312
                */
1313
                inline std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
21✔
1314
                                                                                                                                const std::string& y, std::error_code& ec) {
1315
                        auto decode = [](const std::string& token) {
42✔
1316
                                return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(token));
42✔
1317
                        };
1318
                        return create_public_key_from_ec_components(curve, x, y, std::move(decode), ec);
42✔
1319
                }
1320
                /**
1321
                * Create public key from curve name and coordinates. This is defined in
1322
                * [RFC 7518 Section 6.2](https://www.rfc-editor.org/rfc/rfc7518#section-6.2)
1323
                * Using the required "crv" (Curve), "x" (X Coordinate) and "y" (Y Coordinate) Parameters.
1324
                *
1325
                * \param curve        string containing curve name
1326
                * \param x                string containing base64url encoded x coordinate
1327
                * \param y                string containing base64url encoded y coordinate
1328
                * \return public key in PEM format
1329
                */
1330
                inline std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
11✔
1331
                                                                                                                                const std::string& y) {
1332
                        std::error_code ec;
11✔
1333
                        auto res = create_public_key_from_ec_components(curve, x, y, ec);
11✔
1334
                        error::throw_if_error(ec);
11✔
1335
                        return res;
2✔
1336
                }
10✔
1337
#endif
1338
        } // namespace helper
1339

1340
        /**
1341
         * \brief Various cryptographic algorithms when working with JWT
1342
         *
1343
         * JWT (JSON Web Tokens) signatures are typically used as the payload for a JWS (JSON Web Signature) or
1344
         * JWE (JSON Web Encryption). Both of these use various cryptographic as specified by
1345
         * [RFC7518](https://tools.ietf.org/html/rfc7518) and are exposed through the a [JOSE
1346
         * Header](https://tools.ietf.org/html/rfc7515#section-4) which points to one of the JWA [JSON Web
1347
         * Algorithms](https://tools.ietf.org/html/rfc7518#section-3.1)
1348
         */
1349
        namespace algorithm {
1350
                /**
1351
                 * \brief "none" algorithm.
1352
                 *
1353
                 * Returns and empty signature and checks if the given signature is empty.
1354
                 * See [RFC 7518 Section 3.6](https://datatracker.ietf.org/doc/html/rfc7518#section-3.6)
1355
                 * for more information.
1356
                 */
1357
                struct none {
1358
                        /**
1359
                         * \brief Return an empty string
1360
                         */
1361
                        std::string sign(const std::string& /*unused*/, std::error_code& ec) const {
17✔
1362
                                ec.clear();
17✔
1363
                                return {};
17✔
1364
                        }
1365
                        /**
1366
                         * \brief Check if the given signature is empty.
1367
                         *
1368
                         * JWT's with "none" algorithm should not contain a signature.
1369
                         * \param signature Signature data to verify
1370
                         * \param ec                error_code filled with details about the error
1371
                         */
1372
                        void verify(const std::string& /*unused*/, const std::string& signature, std::error_code& ec) const {
28✔
1373
                                ec.clear();
28✔
1374
                                if (!signature.empty()) { ec = error::signature_verification_error::invalid_signature; }
28✔
1375
                        }
28✔
1376
                        /// Get algorithm name
1377
                        std::string name() const { return "none"; }
114✔
1378
                };
1379
                /**
1380
                 * \brief Base class for HMAC family of algorithms
1381
                 */
1382
                struct hmacsha {
1383
                        /**
1384
                         * Construct new hmac algorithm
1385
                         *
1386
                         * \param key Key to use for HMAC
1387
                         * \param md Pointer to hash function
1388
                         * \param name Name of the algorithm
1389
                         */
1390
                        hmacsha(std::string key, const EVP_MD* (*md)(), std::string name)
43✔
1391
                                : secret(std::move(key)), md(md), alg_name(std::move(name)) {}
43✔
1392
                        /**
1393
                         * Sign jwt data
1394
                         *
1395
                         * \param data The data to sign
1396
                         * \param ec error_code filled with details on error
1397
                         * \return HMAC signature for the given data
1398
                         */
1399
                        std::string sign(const std::string& data, std::error_code& ec) const {
47✔
1400
                                ec.clear();
47✔
1401
                                std::string res(static_cast<size_t>(EVP_MAX_MD_SIZE), '\0');
47✔
1402
                                auto len = static_cast<unsigned int>(res.size());
47✔
1403
                                if (HMAC(md(), secret.data(), static_cast<int>(secret.size()),
47✔
1404
                                                 reinterpret_cast<const unsigned char*>(data.data()), static_cast<int>(data.size()),
47✔
1405
                                                 (unsigned char*)res.data(), // NOLINT(google-readability-casting) requires `const_cast`
47✔
1406
                                                 &len) == nullptr) {
47✔
1407
                                        ec = error::signature_generation_error::hmac_failed;
1✔
1408
                                        return {};
1✔
1409
                                }
1410
                                res.resize(len);
46✔
1411
                                return res;
46✔
1412
                        }
47✔
1413
                        /**
1414
                         * Check if signature is valid
1415
                         *
1416
                         * \param data The data to check signature against
1417
                         * \param signature Signature provided by the jwt
1418
                         * \param ec Filled with details about failure.
1419
                         */
1420
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
28✔
1421
                                ec.clear();
28✔
1422
                                auto res = sign(data, ec);
28✔
1423
                                if (ec) return;
28✔
1424

1425
                                bool matched = true;
27✔
1426
                                for (size_t i = 0; i < std::min<size_t>(res.size(), signature.size()); i++)
890✔
1427
                                        if (res[i] != signature[i]) matched = false;
863✔
1428
                                if (res.size() != signature.size()) matched = false;
27✔
1429
                                if (!matched) {
27✔
1430
                                        ec = error::signature_verification_error::invalid_signature;
2✔
1431
                                        return;
2✔
1432
                                }
1433
                        }
28✔
1434
                        /**
1435
                         * Returns the algorithm name provided to the constructor
1436
                         *
1437
                         * \return algorithm's name
1438
                         */
1439
                        std::string name() const { return alg_name; }
43✔
1440

1441
                private:
1442
                        /// HMAC secret
1443
                        const std::string secret;
1444
                        /// HMAC hash generator
1445
                        const EVP_MD* (*md)();
1446
                        /// algorithm's name
1447
                        const std::string alg_name;
1448
                };
1449
                /**
1450
                 * \brief Base class for RSA family of algorithms
1451
                 */
1452
                struct rsa {
1453
                        /**
1454
                         * Construct new rsa algorithm
1455
                         *
1456
                         * \param public_key RSA public key in PEM format
1457
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
1458
                         * \param public_key_password Password to decrypt public key pem.
1459
                         * \param private_key_password Password to decrypt private key pem.
1460
                         * \param md Pointer to hash function
1461
                         * \param name Name of the algorithm
1462
                         */
1463
                        rsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
16✔
1464
                                const std::string& private_key_password, const EVP_MD* (*md)(), std::string name)
1465
                                : md(md), alg_name(std::move(name)) {
16✔
1466
                                if (!private_key.empty()) {
16✔
1467
                                        pkey = helper::load_private_key_from_string(private_key, private_key_password);
10✔
1468
                                } else if (!public_key.empty()) {
6✔
1469
                                        pkey = helper::load_public_key_from_string(public_key, public_key_password);
5✔
1470
                                } else
1471
                                        throw error::rsa_exception(error::rsa_error::no_key_provided);
1✔
1472
                        }
17✔
1473
                        /**
1474
                         * Construct new rsa algorithm
1475
                         *
1476
                         * \param key_pair openssl EVP_PKEY structure containing RSA key pair. The private part is optional.
1477
                         * \param md Pointer to hash function
1478
                         * \param name Name of the algorithm
1479
                         */
1480
                        rsa(helper::evp_pkey_handle key_pair, const EVP_MD* (*md)(), std::string name)
3✔
1481
                                : pkey(std::move(key_pair)), md(md), alg_name(std::move(name)) {
3✔
1482
                                if (!pkey) { throw error::rsa_exception(error::rsa_error::no_key_provided); }
3✔
1483
                        }
3✔
1484
                        /**
1485
                         * Sign jwt data
1486
                         * \param data The data to sign
1487
                         * \param ec error_code filled with details on error
1488
                         * \return RSA signature for the given data
1489
                         */
1490
                        std::string sign(const std::string& data, std::error_code& ec) const {
9✔
1491
                                ec.clear();
9✔
1492
                                auto ctx = helper::make_evp_md_ctx();
9✔
1493
                                if (!ctx) {
9✔
1494
                                        ec = error::signature_generation_error::create_context_failed;
1✔
1495
                                        return {};
1✔
1496
                                }
1497
                                if (!EVP_SignInit(ctx.get(), md())) {
8✔
1498
                                        ec = error::signature_generation_error::signinit_failed;
1✔
1499
                                        return {};
1✔
1500
                                }
1501

1502
                                std::string res(EVP_PKEY_size(pkey.get()), '\0');
7✔
1503
                                unsigned int len = 0;
7✔
1504

1505
                                if (!EVP_SignUpdate(ctx.get(), data.data(), data.size())) {
7✔
1506
                                        ec = error::signature_generation_error::signupdate_failed;
1✔
1507
                                        return {};
1✔
1508
                                }
1509
                                if (EVP_SignFinal(ctx.get(), (unsigned char*)res.data(), &len, pkey.get()) == 0) {
6✔
1510
                                        ec = error::signature_generation_error::signfinal_failed;
1✔
1511
                                        return {};
1✔
1512
                                }
1513

1514
                                res.resize(len);
5✔
1515
                                return res;
5✔
1516
                        }
9✔
1517
                        /**
1518
                         * Check if signature is valid
1519
                         *
1520
                         * \param data The data to check signature against
1521
                         * \param signature Signature provided by the jwt
1522
                         * \param ec Filled with details on failure
1523
                         */
1524
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
16✔
1525
                                ec.clear();
16✔
1526
                                auto ctx = helper::make_evp_md_ctx();
16✔
1527
                                if (!ctx) {
16✔
1528
                                        ec = error::signature_verification_error::create_context_failed;
1✔
1529
                                        return;
1✔
1530
                                }
1531
                                if (!EVP_VerifyInit(ctx.get(), md())) {
15✔
1532
                                        ec = error::signature_verification_error::verifyinit_failed;
1✔
1533
                                        return;
1✔
1534
                                }
1535
                                if (!EVP_VerifyUpdate(ctx.get(), data.data(), data.size())) {
14✔
1536
                                        ec = error::signature_verification_error::verifyupdate_failed;
1✔
1537
                                        return;
1✔
1538
                                }
1539
                                auto res = EVP_VerifyFinal(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
26✔
1540
                                                                                   static_cast<unsigned int>(signature.size()), pkey.get());
13✔
1541
                                if (res != 1) {
13✔
1542
                                        ec = error::signature_verification_error::verifyfinal_failed;
3✔
1543
                                        return;
3✔
1544
                                }
1545
                        }
16✔
1546
                        /**
1547
                         * Returns the algorithm name provided to the constructor
1548
                         * \return algorithm's name
1549
                         */
1550
                        std::string name() const { return alg_name; }
15✔
1551

1552
                private:
1553
                        /// OpenSSL structure containing converted keys
1554
                        helper::evp_pkey_handle pkey;
1555
                        /// Hash generator
1556
                        const EVP_MD* (*md)();
1557
                        /// algorithm's name
1558
                        const std::string alg_name;
1559
                };
1560
                /**
1561
                 * \brief Base class for ECDSA family of algorithms
1562
                 */
1563
                struct ecdsa {
1564
                        /**
1565
                         * Construct new ecdsa algorithm
1566
                         *
1567
                         * \param public_key ECDSA public key in PEM format
1568
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail
1569
                         * \param public_key_password Password to decrypt public key pem
1570
                         * \param private_key_password Password to decrypt private key pem
1571
                         * \param md Pointer to hash function
1572
                         * \param name Name of the algorithm
1573
                         * \param siglen The bit length of the signature
1574
                         */
1575
                        ecdsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
69✔
1576
                                  const std::string& private_key_password, const EVP_MD* (*md)(), std::string name, size_t siglen)
1577
                                : md(md), alg_name(std::move(name)), signature_length(siglen) {
69✔
1578
                                if (!private_key.empty()) {
69✔
1579
                                        pkey = helper::load_private_ec_key_from_string(private_key, private_key_password);
32✔
1580
                                        check_private_key(pkey.get());
29✔
1581
                                } else if (!public_key.empty()) {
37✔
1582
                                        pkey = helper::load_public_ec_key_from_string(public_key, public_key_password);
36✔
1583
                                        check_public_key(pkey.get());
25✔
1584
                                } else {
1585
                                        throw error::ecdsa_exception(error::ecdsa_error::no_key_provided);
1✔
1586
                                }
1587
                                if (!pkey) throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
50✔
1588

1589
                                size_t keysize = EVP_PKEY_bits(pkey.get());
50✔
1590
                                if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521))
50✔
1591
                                        throw error::ecdsa_exception(error::ecdsa_error::invalid_key_size);
24✔
1592
                        }
112✔
1593

1594
                        /**
1595
                         * Construct new ecdsa algorithm
1596
                         *
1597
                         * \param key_pair openssl EVP_PKEY structure containing ECDSA key pair. The private part is optional.
1598
                         * \param md Pointer to hash function
1599
                         * \param name Name of the algorithm
1600
                         * \param siglen The bit length of the signature
1601
                         */
1602
                        ecdsa(helper::evp_pkey_handle key_pair, const EVP_MD* (*md)(), std::string name, size_t siglen)
4✔
1603
                                : pkey(std::move(key_pair)), md(md), alg_name(std::move(name)), signature_length(siglen) {
4✔
1604
                                if (!pkey) { throw error::ecdsa_exception(error::ecdsa_error::no_key_provided); }
4✔
1605
                                size_t keysize = EVP_PKEY_bits(pkey.get());
3✔
1606
                                if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521))
3✔
1607
                                        throw error::ecdsa_exception(error::ecdsa_error::invalid_key_size);
×
1608
                        }
5✔
1609

1610
                        /**
1611
                         * Sign jwt data
1612
                         * \param data The data to sign
1613
                         * \param ec error_code filled with details on error
1614
                         * \return ECDSA signature for the given data
1615
                         */
1616
                        std::string sign(const std::string& data, std::error_code& ec) const {
15✔
1617
                                ec.clear();
15✔
1618
                                auto ctx = helper::make_evp_md_ctx();
15✔
1619
                                if (!ctx) {
15✔
1620
                                        ec = error::signature_generation_error::create_context_failed;
1✔
1621
                                        return {};
1✔
1622
                                }
1623
                                if (!EVP_DigestSignInit(ctx.get(), nullptr, md(), nullptr, pkey.get())) {
14✔
1624
                                        ec = error::signature_generation_error::signinit_failed;
1✔
1625
                                        return {};
1✔
1626
                                }
1627
                                if (!EVP_DigestUpdate(ctx.get(), data.data(), static_cast<unsigned int>(data.size()))) {
13✔
1628
                                        ec = error::signature_generation_error::digestupdate_failed;
1✔
1629
                                        return {};
1✔
1630
                                }
1631

1632
                                size_t len = 0;
12✔
1633
                                if (!EVP_DigestSignFinal(ctx.get(), nullptr, &len)) {
12✔
1634
                                        ec = error::signature_generation_error::signfinal_failed;
1✔
1635
                                        return {};
1✔
1636
                                }
1637
                                std::string res(len, '\0');
11✔
1638
                                if (!EVP_DigestSignFinal(ctx.get(), (unsigned char*)res.data(), &len)) {
11✔
1639
                                        ec = error::signature_generation_error::signfinal_failed;
5✔
1640
                                        return {};
5✔
1641
                                }
1642

1643
                                res.resize(len);
6✔
1644
                                return der_to_p1363_signature(res, ec);
6✔
1645
                        }
15✔
1646

1647
                        /**
1648
                         * Check if signature is valid
1649
                         * \param data The data to check signature against
1650
                         * \param signature Signature provided by the jwt
1651
                         * \param ec Filled with details on error
1652
                         */
1653
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
23✔
1654
                                ec.clear();
23✔
1655
                                std::string der_signature = p1363_to_der_signature(signature, ec);
23✔
1656
                                if (ec) { return; }
23✔
1657

1658
                                auto ctx = helper::make_evp_md_ctx();
20✔
1659
                                if (!ctx) {
20✔
1660
                                        ec = error::signature_verification_error::create_context_failed;
1✔
1661
                                        return;
1✔
1662
                                }
1663
                                if (!EVP_DigestVerifyInit(ctx.get(), nullptr, md(), nullptr, pkey.get())) {
19✔
1664
                                        ec = error::signature_verification_error::verifyinit_failed;
1✔
1665
                                        return;
1✔
1666
                                }
1667
                                if (!EVP_DigestUpdate(ctx.get(), data.data(), static_cast<unsigned int>(data.size()))) {
18✔
1668
                                        ec = error::signature_verification_error::verifyupdate_failed;
1✔
1669
                                        return;
1✔
1670
                                }
1671

1672
#if OPENSSL_VERSION_NUMBER < 0x10002000L
1673
                                unsigned char* der_sig_data = reinterpret_cast<unsigned char*>(const_cast<char*>(der_signature.data()));
1674
#else
1675
                                const unsigned char* der_sig_data = reinterpret_cast<const unsigned char*>(der_signature.data());
17✔
1676
#endif
1677
                                auto res =
1678
                                        EVP_DigestVerifyFinal(ctx.get(), der_sig_data, static_cast<unsigned int>(der_signature.length()));
17✔
1679
                                if (res == 0) {
17✔
1680
                                        ec = error::signature_verification_error::invalid_signature;
8✔
1681
                                        return;
8✔
1682
                                }
1683
                                if (res == -1) {
9✔
1684
                                        ec = error::signature_verification_error::verifyfinal_failed;
×
1685
                                        return;
×
1686
                                }
1687
                        }
34✔
1688
                        /**
1689
                         * Returns the algorithm name provided to the constructor
1690
                         * \return algorithm's name
1691
                         */
1692
                        std::string name() const { return alg_name; }
23✔
1693

1694
                private:
1695
                        static void check_public_key(EVP_PKEY* pkey) {
25✔
1696
#ifdef JWT_OPENSSL_3_0
1697
                                std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
1698
                                        EVP_PKEY_CTX_new_from_pkey(nullptr, pkey, nullptr), EVP_PKEY_CTX_free);
25✔
1699
                                if (!ctx) { throw error::ecdsa_exception(error::ecdsa_error::create_context_failed); }
25✔
1700
                                if (EVP_PKEY_public_check(ctx.get()) != 1) {
24✔
1701
                                        throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1✔
1702
                                }
1703
#else
1704
                                std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> eckey(EVP_PKEY_get1_EC_KEY(pkey), EC_KEY_free);
1705
                                if (!eckey) { throw error::ecdsa_exception(error::ecdsa_error::invalid_key); }
1706
                                if (EC_KEY_check_key(eckey.get()) == 0) throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1707
#endif
1708
                        }
25✔
1709

1710
                        static void check_private_key(EVP_PKEY* pkey) {
29✔
1711
#ifdef JWT_OPENSSL_3_0
1712
                                std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
1713
                                        EVP_PKEY_CTX_new_from_pkey(nullptr, pkey, nullptr), EVP_PKEY_CTX_free);
29✔
1714
                                if (!ctx) { throw error::ecdsa_exception(error::ecdsa_error::create_context_failed); }
29✔
1715
                                if (EVP_PKEY_private_check(ctx.get()) != 1) {
28✔
1716
                                        throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1✔
1717
                                }
1718
#else
1719
                                std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> eckey(EVP_PKEY_get1_EC_KEY(pkey), EC_KEY_free);
1720
                                if (!eckey) { throw error::ecdsa_exception(error::ecdsa_error::invalid_key); }
1721
                                if (EC_KEY_check_key(eckey.get()) == 0) throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1722
#endif
1723
                        }
29✔
1724

1725
                        std::string der_to_p1363_signature(const std::string& der_signature, std::error_code& ec) const {
6✔
1726
                                const unsigned char* possl_signature = reinterpret_cast<const unsigned char*>(der_signature.data());
6✔
1727
                                std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(
1728
                                        d2i_ECDSA_SIG(nullptr, &possl_signature, static_cast<long>(der_signature.length())),
6✔
1729
                                        ECDSA_SIG_free);
6✔
1730
                                if (!sig) {
6✔
1731
                                        ec = error::signature_generation_error::signature_decoding_failed;
1✔
1732
                                        return {};
1✔
1733
                                }
1734

1735
#ifdef JWT_OPENSSL_1_0_0
1736
                                auto rr = helper::bn2raw(sig->r);
1737
                                auto rs = helper::bn2raw(sig->s);
1738
#else
1739
                                const BIGNUM* r;
1740
                                const BIGNUM* s;
1741
                                ECDSA_SIG_get0(sig.get(), &r, &s);
5✔
1742
                                auto rr = helper::bn2raw(r);
5✔
1743
                                auto rs = helper::bn2raw(s);
5✔
1744
#endif
1745
                                if (rr.size() > signature_length / 2 || rs.size() > signature_length / 2)
5✔
1746
                                        throw std::logic_error("bignum size exceeded expected length");
×
1747
                                rr.insert(0, signature_length / 2 - rr.size(), '\0');
5✔
1748
                                rs.insert(0, signature_length / 2 - rs.size(), '\0');
5✔
1749
                                return rr + rs;
5✔
1750
                        }
6✔
1751

1752
                        std::string p1363_to_der_signature(const std::string& signature, std::error_code& ec) const {
23✔
1753
                                ec.clear();
23✔
1754
                                auto r = helper::raw2bn(signature.substr(0, signature.size() / 2), ec);
23✔
1755
                                if (ec) return {};
23✔
1756
                                auto s = helper::raw2bn(signature.substr(signature.size() / 2), ec);
23✔
1757
                                if (ec) return {};
23✔
1758

1759
                                ECDSA_SIG* psig;
1760
#ifdef JWT_OPENSSL_1_0_0
1761
                                ECDSA_SIG sig;
1762
                                sig.r = r.get();
1763
                                sig.s = s.get();
1764
                                psig = &sig;
1765
#else
1766
                                std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(ECDSA_SIG_new(), ECDSA_SIG_free);
23✔
1767
                                if (!sig) {
23✔
1768
                                        ec = error::signature_verification_error::create_context_failed;
1✔
1769
                                        return {};
1✔
1770
                                }
1771
                                ECDSA_SIG_set0(sig.get(), r.release(), s.release());
22✔
1772
                                psig = sig.get();
22✔
1773
#endif
1774

1775
                                int length = i2d_ECDSA_SIG(psig, nullptr);
22✔
1776
                                if (length < 0) {
22✔
1777
                                        ec = error::signature_verification_error::signature_encoding_failed;
1✔
1778
                                        return {};
1✔
1779
                                }
1780
                                std::string der_signature(length, '\0');
21✔
1781
                                unsigned char* psbuffer = (unsigned char*)der_signature.data();
21✔
1782
                                length = i2d_ECDSA_SIG(psig, &psbuffer);
21✔
1783
                                if (length < 0) {
21✔
1784
                                        ec = error::signature_verification_error::signature_encoding_failed;
1✔
1785
                                        return {};
1✔
1786
                                }
1787
                                der_signature.resize(length);
20✔
1788
                                return der_signature;
20✔
1789
                        }
23✔
1790

1791
                        /// OpenSSL struct containing keys
1792
                        helper::evp_pkey_handle pkey;
1793
                        /// Hash generator function
1794
                        const EVP_MD* (*md)();
1795
                        /// algorithm's name
1796
                        const std::string alg_name;
1797
                        /// Length of the resulting signature
1798
                        const size_t signature_length;
1799
                };
1800

1801
#if !defined(JWT_OPENSSL_1_0_0) && !defined(JWT_OPENSSL_1_1_0)
1802
                /**
1803
                 * \brief Base class for EdDSA family of algorithms
1804
                 *
1805
                 * https://tools.ietf.org/html/rfc8032
1806
                 *
1807
                 * The EdDSA algorithms were introduced in [OpenSSL v1.1.1](https://www.openssl.org/news/openssl-1.1.1-notes.html),
1808
                 * so these algorithms are only available when building against this version or higher.
1809
                 */
1810
                struct eddsa {
1811
                        /**
1812
                         * Construct new eddsa algorithm
1813
                         * \param public_key EdDSA public key in PEM format
1814
                         * \param private_key EdDSA private key or empty string if not available. If empty, signing will always
1815
                         * fail.
1816
                         * \param public_key_password Password to decrypt public key pem.
1817
                         * \param private_key_password Password
1818
                         * to decrypt private key pem.
1819
                         * \param name Name of the algorithm
1820
                         */
1821
                        eddsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
27✔
1822
                                  const std::string& private_key_password, std::string name)
1823
                                : alg_name(std::move(name)) {
27✔
1824
                                if (!private_key.empty()) {
27✔
1825
                                        pkey = helper::load_private_key_from_string(private_key, private_key_password);
10✔
1826
                                } else if (!public_key.empty()) {
17✔
1827
                                        pkey = helper::load_public_key_from_string(public_key, public_key_password);
16✔
1828
                                } else
1829
                                        throw error::ecdsa_exception(error::ecdsa_error::load_key_bio_read);
1✔
1830
                        }
41✔
1831
                        /**
1832
                         * Sign jwt data
1833
                         * \param data The data to sign
1834
                         * \param ec error_code filled with details on error
1835
                         * \return EdDSA signature for the given data
1836
                         */
1837
                        std::string sign(const std::string& data, std::error_code& ec) const {
6✔
1838
                                ec.clear();
6✔
1839
                                auto ctx = helper::make_evp_md_ctx();
6✔
1840
                                if (!ctx) {
6✔
1841
                                        ec = error::signature_generation_error::create_context_failed;
1✔
1842
                                        return {};
1✔
1843
                                }
1844
                                if (!EVP_DigestSignInit(ctx.get(), nullptr, nullptr, nullptr, pkey.get())) {
5✔
1845
                                        ec = error::signature_generation_error::signinit_failed;
1✔
1846
                                        return {};
1✔
1847
                                }
1848

1849
                                size_t len = EVP_PKEY_size(pkey.get());
4✔
1850
                                std::string res(len, '\0');
4✔
1851

1852
// LibreSSL is the special kid in the block, as it does not support EVP_DigestSign.
1853
// OpenSSL on the otherhand does not support using EVP_DigestSignUpdate for eddsa, which is why we end up with this
1854
// mess.
1855
#if defined(LIBRESSL_VERSION_NUMBER) || defined(LIBWOLFSSL_VERSION_HEX)
1856
                                ERR_clear_error();
1857
                                if (EVP_DigestSignUpdate(ctx.get(), reinterpret_cast<const unsigned char*>(data.data()), data.size()) !=
1858
                                        1) {
1859
                                        std::cout << ERR_error_string(ERR_get_error(), NULL) << '\n';
1860
                                        ec = error::signature_generation_error::signupdate_failed;
1861
                                        return {};
1862
                                }
1863
                                if (EVP_DigestSignFinal(ctx.get(), reinterpret_cast<unsigned char*>(&res[0]), &len) != 1) {
1864
                                        ec = error::signature_generation_error::signfinal_failed;
1865
                                        return {};
1866
                                }
1867
#else
1868
                                if (EVP_DigestSign(ctx.get(), reinterpret_cast<unsigned char*>(&res[0]), &len,
8✔
1869
                                                                   reinterpret_cast<const unsigned char*>(data.data()), data.size()) != 1) {
8✔
1870
                                        ec = error::signature_generation_error::signfinal_failed;
1✔
1871
                                        return {};
1✔
1872
                                }
1873
#endif
1874

1875
                                res.resize(len);
3✔
1876
                                return res;
3✔
1877
                        }
6✔
1878

1879
                        /**
1880
                         * Check if signature is valid
1881
                         * \param data The data to check signature against
1882
                         * \param signature Signature provided by the jwt
1883
                         * \param ec Filled with details on error
1884
                         */
1885
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
12✔
1886
                                ec.clear();
12✔
1887
                                auto ctx = helper::make_evp_md_ctx();
12✔
1888
                                if (!ctx) {
12✔
1889
                                        ec = error::signature_verification_error::create_context_failed;
1✔
1890
                                        return;
1✔
1891
                                }
1892
                                if (!EVP_DigestVerifyInit(ctx.get(), nullptr, nullptr, nullptr, pkey.get())) {
11✔
1893
                                        ec = error::signature_verification_error::verifyinit_failed;
1✔
1894
                                        return;
1✔
1895
                                }
1896
// LibreSSL is the special kid in the block, as it does not support EVP_DigestVerify.
1897
// OpenSSL on the otherhand does not support using EVP_DigestVerifyUpdate for eddsa, which is why we end up with this
1898
// mess.
1899
#if defined(LIBRESSL_VERSION_NUMBER) || defined(LIBWOLFSSL_VERSION_HEX)
1900
                                if (EVP_DigestVerifyUpdate(ctx.get(), reinterpret_cast<const unsigned char*>(data.data()),
1901
                                                                                   data.size()) != 1) {
1902
                                        ec = error::signature_verification_error::verifyupdate_failed;
1903
                                        return;
1904
                                }
1905
                                if (EVP_DigestVerifyFinal(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
1906
                                                                                  signature.size()) != 1) {
1907
                                        ec = error::signature_verification_error::verifyfinal_failed;
1908
                                        return;
1909
                                }
1910
#else
1911
                                auto res = EVP_DigestVerify(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
20✔
1912
                                                                                        signature.size(), reinterpret_cast<const unsigned char*>(data.data()),
10✔
1913
                                                                                        data.size());
1914
                                if (res != 1) {
10✔
1915
                                        ec = error::signature_verification_error::verifyfinal_failed;
5✔
1916
                                        return;
5✔
1917
                                }
1918
#endif
1919
                        }
12✔
1920
                        /**
1921
                         * Returns the algorithm name provided to the constructor
1922
                         * \return algorithm's name
1923
                         */
1924
                        std::string name() const { return alg_name; }
10✔
1925

1926
                private:
1927
                        /// OpenSSL struct containing keys
1928
                        helper::evp_pkey_handle pkey;
1929
                        /// algorithm's name
1930
                        const std::string alg_name;
1931
                };
1932
#endif
1933
                /**
1934
                 * \brief Base class for PSS-RSA family of algorithms
1935
                 */
1936
                struct pss {
1937
                        /**
1938
                         * Construct new pss algorithm
1939
                         * \param public_key RSA public key in PEM format
1940
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
1941
                         * \param public_key_password Password to decrypt public key pem.
1942
                         * \param private_key_password Password to decrypt private key pem.
1943
                         * \param md Pointer to hash function
1944
                         * \param name Name of the algorithm
1945
                         */
1946
                        pss(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
10✔
1947
                                const std::string& private_key_password, const EVP_MD* (*md)(), std::string name)
1948
                                : md(md), alg_name(std::move(name)) {
10✔
1949
                                if (!private_key.empty()) {
10✔
1950
                                        pkey = helper::load_private_key_from_string(private_key, private_key_password);
7✔
1951
                                } else if (!public_key.empty()) {
3✔
1952
                                        pkey = helper::load_public_key_from_string(public_key, public_key_password);
2✔
1953
                                } else
1954
                                        throw error::rsa_exception(error::rsa_error::no_key_provided);
1✔
1955
                        }
11✔
1956

1957
                        /**
1958
                         * Sign jwt data
1959
                         * \param data The data to sign
1960
                         * \param ec error_code filled with details on error
1961
                         * \return ECDSA signature for the given data
1962
                         */
1963
                        std::string sign(const std::string& data, std::error_code& ec) const {
8✔
1964
                                ec.clear();
8✔
1965
                                auto md_ctx = helper::make_evp_md_ctx();
8✔
1966
                                if (!md_ctx) {
8✔
1967
                                        ec = error::signature_generation_error::create_context_failed;
1✔
1968
                                        return {};
1✔
1969
                                }
1970
                                EVP_PKEY_CTX* ctx = nullptr;
7✔
1971
                                if (EVP_DigestSignInit(md_ctx.get(), &ctx, md(), nullptr, pkey.get()) != 1) {
7✔
1972
                                        ec = error::signature_generation_error::signinit_failed;
1✔
1973
                                        return {};
1✔
1974
                                }
1975
                                if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
6✔
1976
                                        ec = error::signature_generation_error::rsa_padding_failed;
×
1977
                                        return {};
×
1978
                                }
1979
// wolfSSL does not require EVP_PKEY_CTX_set_rsa_pss_saltlen. The default behavior
1980
// sets the salt length to the hash length. Unlike OpenSSL which exposes this functionality.
1981
#ifndef LIBWOLFSSL_VERSION_HEX
1982
                                if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
6✔
1983
                                        ec = error::signature_generation_error::set_rsa_pss_saltlen_failed;
×
1984
                                        return {};
×
1985
                                }
1986
#endif
1987
                                if (EVP_DigestUpdate(md_ctx.get(), data.data(), static_cast<unsigned int>(data.size())) != 1) {
6✔
1988
                                        ec = error::signature_generation_error::digestupdate_failed;
1✔
1989
                                        return {};
1✔
1990
                                }
1991

1992
                                size_t size = EVP_PKEY_size(pkey.get());
5✔
1993
                                std::string res(size, 0x00);
5✔
1994
                                if (EVP_DigestSignFinal(
5✔
1995
                                                md_ctx.get(),
1996
                                                (unsigned char*)res.data(), // NOLINT(google-readability-casting) requires `const_cast`
5✔
1997
                                                &size) <= 0) {
5✔
1998
                                        ec = error::signature_generation_error::signfinal_failed;
1✔
1999
                                        return {};
1✔
2000
                                }
2001

2002
                                return res;
4✔
2003
                        }
8✔
2004

2005
                        /**
2006
                         * Check if signature is valid
2007
                         * \param data The data to check signature against
2008
                         * \param signature Signature provided by the jwt
2009
                         * \param ec Filled with error details
2010
                         */
2011
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
8✔
2012
                                ec.clear();
8✔
2013

2014
                                auto md_ctx = helper::make_evp_md_ctx();
8✔
2015
                                if (!md_ctx) {
8✔
2016
                                        ec = error::signature_verification_error::create_context_failed;
1✔
2017
                                        return;
1✔
2018
                                }
2019
                                EVP_PKEY_CTX* ctx = nullptr;
7✔
2020
                                if (EVP_DigestVerifyInit(md_ctx.get(), &ctx, md(), nullptr, pkey.get()) != 1) {
7✔
2021
                                        ec = error::signature_verification_error::verifyinit_failed;
1✔
2022
                                        return;
1✔
2023
                                }
2024
                                if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
6✔
2025
                                        ec = error::signature_generation_error::rsa_padding_failed;
×
2026
                                        return;
×
2027
                                }
2028
// wolfSSL does not require EVP_PKEY_CTX_set_rsa_pss_saltlen. The default behavior
2029
// sets the salt length to the hash length. Unlike OpenSSL which exposes this functionality.
2030
#ifndef LIBWOLFSSL_VERSION_HEX
2031
                                if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
6✔
2032
                                        ec = error::signature_verification_error::set_rsa_pss_saltlen_failed;
×
2033
                                        return;
×
2034
                                }
2035
#endif
2036
                                if (EVP_DigestUpdate(md_ctx.get(), data.data(), static_cast<unsigned int>(data.size())) != 1) {
6✔
2037
                                        ec = error::signature_verification_error::verifyupdate_failed;
1✔
2038
                                        return;
1✔
2039
                                }
2040

2041
                                if (EVP_DigestVerifyFinal(md_ctx.get(), (unsigned char*)signature.data(), signature.size()) <= 0) {
5✔
2042
                                        ec = error::signature_verification_error::verifyfinal_failed;
2✔
2043
                                        return;
2✔
2044
                                }
2045
                        }
8✔
2046
                        /**
2047
                         * Returns the algorithm name provided to the constructor
2048
                         * \return algorithm's name
2049
                         */
2050
                        std::string name() const { return alg_name; }
6✔
2051

2052
                private:
2053
                        /// OpenSSL structure containing keys
2054
                        helper::evp_pkey_handle pkey;
2055
                        /// Hash generator function
2056
                        const EVP_MD* (*md)();
2057
                        /// algorithm's name
2058
                        const std::string alg_name;
2059
                };
2060

2061
                /**
2062
                 * HS256 algorithm
2063
                 */
2064
                struct hs256 : public hmacsha {
2065
                        /**
2066
                         * Construct new instance of algorithm
2067
                         * \param key HMAC signing key
2068
                         */
2069
                        explicit hs256(std::string key) : hmacsha(std::move(key), EVP_sha256, "HS256") {}
129✔
2070
                };
2071
                /**
2072
                 * HS384 algorithm
2073
                 */
2074
                struct hs384 : public hmacsha {
2075
                        /**
2076
                         * Construct new instance of algorithm
2077
                         * \param key HMAC signing key
2078
                         */
2079
                        explicit hs384(std::string key) : hmacsha(std::move(key), EVP_sha384, "HS384") {}
2080
                };
2081
                /**
2082
                 * HS512 algorithm
2083
                 */
2084
                struct hs512 : public hmacsha {
2085
                        /**
2086
                         * Construct new instance of algorithm
2087
                         * \param key HMAC signing key
2088
                         */
2089
                        explicit hs512(std::string key) : hmacsha(std::move(key), EVP_sha512, "HS512") {}
2090
                };
2091
                /**
2092
                 * RS256 algorithm.
2093
                 *
2094
                 * This data structure is used to describe the RSA256 and can be used to verify JWTs
2095
                 */
2096
                struct rs256 : public rsa {
2097
                        /**
2098
                         * \brief Construct new instance of algorithm
2099
                         *
2100
                         * \param public_key RSA public key in PEM format
2101
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2102
                         * \param public_key_password Password to decrypt public key pem.
2103
                         * \param private_key_password Password to decrypt private key pem.
2104
                         */
2105
                        explicit rs256(const std::string& public_key, const std::string& private_key = "",
11✔
2106
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2107
                                : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "RS256") {}
33✔
2108
                };
2109
                /**
2110
                 * RS384 algorithm
2111
                 */
2112
                struct rs384 : public rsa {
2113
                        /**
2114
                         * Construct new instance of algorithm
2115
                         * \param public_key RSA public key in PEM format
2116
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2117
                         * \param public_key_password Password to decrypt public key pem.
2118
                         * \param private_key_password Password to decrypt private key pem.
2119
                         */
2120
                        explicit rs384(const std::string& public_key, const std::string& private_key = "",
2121
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2122
                                : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "RS384") {}
2123
                };
2124
                /**
2125
                 * RS512 algorithm
2126
                 */
2127
                struct rs512 : public rsa {
2128
                        /**
2129
                         * Construct new instance of algorithm
2130
                         * \param public_key RSA public key in PEM format
2131
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2132
                         * \param public_key_password Password to decrypt public key pem.
2133
                         * \param private_key_password Password to decrypt private key pem.
2134
                         */
2135
                        explicit rs512(const std::string& public_key, const std::string& private_key = "",
5✔
2136
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2137
                                : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "RS512") {}
15✔
2138
                };
2139
                /**
2140
                 * ES256 algorithm
2141
                 */
2142
                struct es256 : public ecdsa {
2143
                        /**
2144
                         * Construct new instance of algorithm
2145
                         * \param public_key ECDSA public key in PEM format
2146
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always
2147
                         * fail.
2148
                         * \param public_key_password Password to decrypt public key pem.
2149
                         * \param private_key_password Password
2150
                         * to decrypt private key pem.
2151
                         */
2152
                        explicit es256(const std::string& public_key, const std::string& private_key = "",
39✔
2153
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2154
                                : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256", 64) {}
117✔
2155
                };
2156
                /**
2157
                 * ES384 algorithm
2158
                 */
2159
                struct es384 : public ecdsa {
2160
                        /**
2161
                         * Construct new instance of algorithm
2162
                         * \param public_key ECDSA public key in PEM format
2163
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always
2164
                         * fail.
2165
                         * \param public_key_password Password to decrypt public key pem.
2166
                         * \param private_key_password Password
2167
                         * to decrypt private key pem.
2168
                         */
2169
                        explicit es384(const std::string& public_key, const std::string& private_key = "",
15✔
2170
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2171
                                : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "ES384", 96) {}
45✔
2172
                };
2173
                /**
2174
                 * ES512 algorithm
2175
                 */
2176
                struct es512 : public ecdsa {
2177
                        /**
2178
                         * Construct new instance of algorithm
2179
                         * \param public_key ECDSA public key in PEM format
2180
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always
2181
                         * fail.
2182
                         * \param public_key_password Password to decrypt public key pem.
2183
                         * \param private_key_password Password
2184
                         * to decrypt private key pem.
2185
                         */
2186
                        explicit es512(const std::string& public_key, const std::string& private_key = "",
15✔
2187
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2188
                                : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "ES512", 132) {}
45✔
2189
                };
2190
                /**
2191
                 * ES256K algorithm
2192
                 */
2193
                struct es256k : public ecdsa {
2194
                        /**
2195
                         * Construct new instance of algorithm
2196
                         * \param public_key ECDSA public key in PEM format
2197
                         * \param private_key ECDSA private key or empty string if not available. If empty, signing will always
2198
                         * fail.
2199
                         * \param public_key_password Password to decrypt public key pem.
2200
                         * \param private_key_password Password to decrypt private key pem.
2201
                         */
2202
                        explicit es256k(const std::string& public_key, const std::string& private_key = "",
2203
                                                        const std::string& public_key_password = "", const std::string& private_key_password = "")
2204
                                : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256K", 64) {}
2205
                };
2206

2207
#if !defined(JWT_OPENSSL_1_0_0) && !defined(JWT_OPENSSL_1_1_0)
2208
                /**
2209
                 * Ed25519 algorithm
2210
                 *
2211
                 * https://en.wikipedia.org/wiki/EdDSA#Ed25519
2212
                 *
2213
                 * Requires at least OpenSSL 1.1.1.
2214
                 */
2215
                struct ed25519 : public eddsa {
2216
                        /**
2217
                         * Construct new instance of algorithm
2218
                         * \param public_key Ed25519 public key in PEM format
2219
                         * \param private_key Ed25519 private key or empty string if not available. If empty, signing will always
2220
                         * fail.
2221
                         * \param public_key_password Password to decrypt public key pem.
2222
                         * \param private_key_password Password
2223
                         * to decrypt private key pem.
2224
                         */
2225
                        explicit ed25519(const std::string& public_key, const std::string& private_key = "",
22✔
2226
                                                         const std::string& public_key_password = "", const std::string& private_key_password = "")
2227
                                : eddsa(public_key, private_key, public_key_password, private_key_password, "EdDSA") {}
66✔
2228
                };
2229

2230
                /**
2231
                 * Ed448 algorithm
2232
                 *
2233
                 * https://en.wikipedia.org/wiki/EdDSA#Ed448
2234
                 *
2235
                 * Requires at least OpenSSL 1.1.1.
2236
                 */
2237
                struct ed448 : public eddsa {
2238
                        /**
2239
                         * Construct new instance of algorithm
2240
                         * \param public_key Ed448 public key in PEM format
2241
                         * \param private_key Ed448 private key or empty string if not available. If empty, signing will always
2242
                         * fail.
2243
                         * \param public_key_password Password to decrypt public key pem.
2244
                         * \param private_key_password Password
2245
                         * to decrypt private key pem.
2246
                         */
2247
                        explicit ed448(const std::string& public_key, const std::string& private_key = "",
5✔
2248
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2249
                                : eddsa(public_key, private_key, public_key_password, private_key_password, "EdDSA") {}
15✔
2250
                };
2251
#endif
2252

2253
                /**
2254
                 * PS256 algorithm
2255
                 */
2256
                struct ps256 : public pss {
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 ps256(const std::string& public_key, const std::string& private_key = "",
8✔
2265
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2266
                                : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "PS256") {}
24✔
2267
                };
2268
                /**
2269
                 * PS384 algorithm
2270
                 */
2271
                struct ps384 : public pss {
2272
                        /**
2273
                         * Construct new instance of algorithm
2274
                         * \param public_key RSA public key in PEM format
2275
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2276
                         * \param public_key_password Password to decrypt public key pem.
2277
                         * \param private_key_password Password to decrypt private key pem.
2278
                         */
2279
                        explicit ps384(const std::string& public_key, const std::string& private_key = "",
1✔
2280
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2281
                                : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "PS384") {}
3✔
2282
                };
2283
                /**
2284
                 * PS512 algorithm
2285
                 */
2286
                struct ps512 : public pss {
2287
                        /**
2288
                         * Construct new instance of algorithm
2289
                         * \param public_key RSA public key in PEM format
2290
                         * \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
2291
                         * \param public_key_password Password to decrypt public key pem.
2292
                         * \param private_key_password Password to decrypt private key pem.
2293
                         */
2294
                        explicit ps512(const std::string& public_key, const std::string& private_key = "",
1✔
2295
                                                   const std::string& public_key_password = "", const std::string& private_key_password = "")
2296
                                : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "PS512") {}
3✔
2297
                };
2298
        } // namespace algorithm
2299

2300
        /**
2301
         * \brief JSON Abstractions for working with any library
2302
         */
2303
        namespace json {
2304
                /**
2305
                 * \brief Categories for the various JSON types used in JWTs
2306
                 *
2307
                 * This enum is to abstract the third party underlying types and allows the library
2308
                 * to identify the different structures and reason about them without needing a "concept"
2309
                 * to capture that defintion to compare against a concrete type.
2310
                 */
2311
                enum class type { boolean, integer, number, string, array, object };
2312
        } // namespace json
2313

2314
        namespace details {
2315
#ifdef __cpp_lib_void_t
2316
                template<typename... Ts>
2317
                using void_t = std::void_t<Ts...>;
2318
#else
2319
                // https://en.cppreference.com/w/cpp/types/void_t
2320
                template<typename... Ts>
2321
                struct make_void {
2322
                        using type = void;
2323
                };
2324

2325
                template<typename... Ts>
2326
                using void_t = typename make_void<Ts...>::type;
2327
#endif
2328

2329
#ifdef __cpp_lib_experimental_detect
2330
                template<template<typename...> class _Op, typename... _Args>
2331
                using is_detected = std::experimental::is_detected<_Op, _Args...>;
2332
#else
2333
                struct nonesuch {
2334
                        nonesuch() = delete;
2335
                        ~nonesuch() = delete;
2336
                        nonesuch(nonesuch const&) = delete;
2337
                        nonesuch(nonesuch const&&) = delete;
2338
                        void operator=(nonesuch const&) = delete;
2339
                        void operator=(nonesuch&&) = delete;
2340
                };
2341

2342
                // https://en.cppreference.com/w/cpp/experimental/is_detected
2343
                template<class Default, class AlwaysVoid, template<class...> class Op, class... Args>
2344
                struct detector {
2345
                        using value = std::false_type;
2346
                        using type = Default;
2347
                };
2348

2349
                template<class Default, template<class...> class Op, class... Args>
2350
                struct detector<Default, void_t<Op<Args...>>, Op, Args...> {
2351
                        using value = std::true_type;
2352
                        using type = Op<Args...>;
2353
                };
2354

2355
                template<template<class...> class Op, class... Args>
2356
                using is_detected = typename detector<nonesuch, void, Op, Args...>::value;
2357
#endif
2358

2359
                template<typename T, typename Signature>
2360
                using is_signature = typename std::is_same<T, Signature>;
2361

2362
                template<typename traits_type, template<typename...> class Op, typename Signature>
2363
                struct is_function_signature_detected {
2364
                        using type = Op<traits_type>;
2365
                        static constexpr auto value = is_detected<Op, traits_type>::value && std::is_function<type>::value &&
2366
                                                                                  is_signature<type, Signature>::value;
2367
                };
2368

2369
                template<typename traits_type, typename value_type>
2370
                struct supports_get_type {
2371
                        template<typename T>
2372
                        using get_type_t = decltype(T::get_type);
2373

2374
                        static constexpr auto value =
2375
                                is_function_signature_detected<traits_type, get_type_t, json::type(const value_type&)>::value;
2376

2377
                        // Internal assertions for better feedback
2378
                        static_assert(value, "traits implementation must provide `jwt::json::type get_type(const value_type&)`");
2379
                };
2380

2381
#define JWT_CPP_JSON_TYPE_TYPE(TYPE) json_##TYPE_type
2382
#define JWT_CPP_AS_TYPE_T(TYPE) as_##TYPE_t
2383
#define JWT_CPP_SUPPORTS_AS(TYPE)                                                                                      \
2384
        template<typename traits_type, typename value_type, typename JWT_CPP_JSON_TYPE_TYPE(TYPE)>                         \
2385
        struct supports_as_##TYPE {                                                                                        \
2386
                template<typename T>                                                                                           \
2387
                using JWT_CPP_AS_TYPE_T(TYPE) = decltype(T::as_##TYPE);                                                        \
2388
                                                                                                                       \
2389
                static constexpr auto value =                                                                                  \
2390
                        is_function_signature_detected<traits_type, JWT_CPP_AS_TYPE_T(TYPE),                                       \
2391
                                                                                   JWT_CPP_JSON_TYPE_TYPE(TYPE)(const value_type&)>::value;                    \
2392
                                                                                                                       \
2393
                static_assert(value, "traits implementation must provide `" #TYPE "_type as_" #TYPE "(const value_type&)`");   \
2394
        }
2395

2396
                JWT_CPP_SUPPORTS_AS(object);
2397
                JWT_CPP_SUPPORTS_AS(array);
2398
                JWT_CPP_SUPPORTS_AS(string);
2399
                JWT_CPP_SUPPORTS_AS(number);
2400
                JWT_CPP_SUPPORTS_AS(integer);
2401
                JWT_CPP_SUPPORTS_AS(boolean);
2402

2403
#undef JWT_CPP_JSON_TYPE_TYPE
2404
#undef JWT_CPP_AS_TYPE_T
2405
#undef JWT_CPP_SUPPORTS_AS
2406

2407
                template<typename traits>
2408
                struct is_valid_traits {
2409
                        static constexpr auto value =
2410
                                supports_get_type<traits, typename traits::value_type>::value &&
2411
                                supports_as_object<traits, typename traits::value_type, typename traits::object_type>::value &&
2412
                                supports_as_array<traits, typename traits::value_type, typename traits::array_type>::value &&
2413
                                supports_as_string<traits, typename traits::value_type, typename traits::string_type>::value &&
2414
                                supports_as_number<traits, typename traits::value_type, typename traits::number_type>::value &&
2415
                                supports_as_integer<traits, typename traits::value_type, typename traits::integer_type>::value &&
2416
                                supports_as_boolean<traits, typename traits::value_type, typename traits::boolean_type>::value;
2417
                };
2418

2419
                template<typename value_type>
2420
                struct is_valid_json_value {
2421
                        static constexpr auto value =
2422
                                std::is_default_constructible<value_type>::value &&
2423
                                std::is_constructible<value_type, const value_type&>::value && // a more generic is_copy_constructible
2424
                                std::is_move_constructible<value_type>::value && std::is_assignable<value_type, value_type>::value &&
2425
                                std::is_copy_assignable<value_type>::value && std::is_move_assignable<value_type>::value;
2426
                        // TODO(prince-chrismc): Stream operators
2427
                };
2428

2429
                // https://stackoverflow.com/a/53967057/8480874
2430
                template<typename T, typename = void>
2431
                struct is_iterable : std::false_type {};
2432

2433
                template<typename T>
2434
                struct is_iterable<T, void_t<decltype(std::begin(std::declval<T>())), decltype(std::end(std::declval<T>())),
2435
#if __cplusplus > 201402L
2436
                                                                         decltype(std::cbegin(std::declval<T>())), decltype(std::cend(std::declval<T>()))
2437
#else
2438
                                                                         decltype(std::begin(std::declval<const T>())),
2439
                                                                         decltype(std::end(std::declval<const T>()))
2440
#endif
2441
                                                                         >> : std::true_type {
2442
                };
2443

2444
#if __cplusplus > 201703L
2445
                template<typename T>
2446
                inline constexpr bool is_iterable_v = is_iterable<T>::value;
2447
#endif
2448

2449
                template<typename object_type, typename string_type>
2450
                using is_count_signature = typename std::is_integral<decltype(std::declval<const object_type>().count(
2451
                        std::declval<const string_type>()))>;
2452

2453
                template<typename object_type, typename string_type, typename = void>
2454
                struct is_subcription_operator_signature : std::false_type {};
2455

2456
                template<typename object_type, typename string_type>
2457
                struct is_subcription_operator_signature<
2458
                        object_type, string_type,
2459
                        void_t<decltype(std::declval<object_type>().operator[](std::declval<string_type>()))>> : std::true_type {
2460
                        // TODO(prince-chrismc): I am not convienced this is meaningful anymore
2461
                        static_assert(
2462
                                value,
2463
                                "object_type must implementate the subscription operator '[]' taking string_type as an argument");
2464
                };
2465

2466
                template<typename object_type, typename value_type, typename string_type>
2467
                using is_at_const_signature =
2468
                        typename std::is_same<decltype(std::declval<const object_type>().at(std::declval<const string_type>())),
2469
                                                                  const value_type&>;
2470

2471
                template<typename value_type, typename string_type, typename object_type>
2472
                struct is_valid_json_object {
2473
                        template<typename T>
2474
                        using mapped_type_t = typename T::mapped_type;
2475
                        template<typename T>
2476
                        using key_type_t = typename T::key_type;
2477
                        template<typename T>
2478
                        using iterator_t = typename T::iterator;
2479
                        template<typename T>
2480
                        using const_iterator_t = typename T::const_iterator;
2481

2482
                        static constexpr auto value =
2483
                                std::is_constructible<value_type, object_type>::value &&
2484
                                is_detected<mapped_type_t, object_type>::value &&
2485
                                std::is_same<typename object_type::mapped_type, value_type>::value &&
2486
                                is_detected<key_type_t, object_type>::value &&
2487
                                (std::is_same<typename object_type::key_type, string_type>::value ||
2488
                                 std::is_constructible<typename object_type::key_type, string_type>::value) &&
2489
                                is_detected<iterator_t, object_type>::value && is_detected<const_iterator_t, object_type>::value &&
2490
                                is_iterable<object_type>::value && is_count_signature<object_type, string_type>::value &&
2491
                                is_subcription_operator_signature<object_type, string_type>::value &&
2492
                                is_at_const_signature<object_type, value_type, string_type>::value;
2493
                };
2494

2495
                template<typename value_type, typename array_type>
2496
                struct is_valid_json_array {
2497
                        template<typename T>
2498
                        using value_type_t = typename T::value_type;
2499
                        using front_base_type = typename std::decay<decltype(std::declval<array_type>().front())>::type;
2500

2501
                        static constexpr auto value = std::is_constructible<value_type, array_type>::value &&
2502
                                                                                  is_iterable<array_type>::value &&
2503
                                                                                  is_detected<value_type_t, array_type>::value &&
2504
                                                                                  std::is_same<typename array_type::value_type, value_type>::value &&
2505
                                                                                  std::is_same<front_base_type, value_type>::value;
2506
                };
2507

2508
                template<typename string_type, typename integer_type>
2509
                using is_substr_start_end_index_signature =
2510
                        typename std::is_same<decltype(std::declval<string_type>().substr(
2511
                                                                          static_cast<size_t>(std::declval<integer_type>()),
2512
                                                                          static_cast<size_t>(std::declval<integer_type>()))),
2513
                                                                  string_type>;
2514

2515
                template<typename string_type, typename integer_type>
2516
                using is_substr_start_index_signature =
2517
                        typename std::is_same<decltype(std::declval<string_type>().substr(
2518
                                                                          static_cast<size_t>(std::declval<integer_type>()))),
2519
                                                                  string_type>;
2520

2521
                template<typename string_type>
2522
                using is_std_operate_plus_signature =
2523
                        typename std::is_same<decltype(std::operator+(std::declval<string_type>(), std::declval<string_type>())),
2524
                                                                  string_type>;
2525

2526
                template<typename value_type, typename string_type, typename integer_type>
2527
                struct is_valid_json_string {
2528
                        static constexpr auto substr = is_substr_start_end_index_signature<string_type, integer_type>::value &&
2529
                                                                                   is_substr_start_index_signature<string_type, integer_type>::value;
2530
                        static_assert(substr, "string_type must have a substr method taking only a start index and an overload "
2531
                                                                  "taking a start and end index, both must return a string_type");
2532

2533
                        static constexpr auto operator_plus = is_std_operate_plus_signature<string_type>::value;
2534
                        static_assert(operator_plus,
2535
                                                  "string_type must have a '+' operator implemented which returns the concatenated string");
2536

2537
                        static constexpr auto value =
2538
                                std::is_constructible<value_type, string_type>::value && substr && operator_plus;
2539
                };
2540

2541
                template<typename value_type, typename number_type>
2542
                struct is_valid_json_number {
2543
                        static constexpr auto value =
2544
                                std::is_floating_point<number_type>::value && std::is_constructible<value_type, number_type>::value;
2545
                };
2546

2547
                template<typename value_type, typename integer_type>
2548
                struct is_valid_json_integer {
2549
                        static constexpr auto value = std::is_signed<integer_type>::value &&
2550
                                                                                  !std::is_floating_point<integer_type>::value &&
2551
                                                                                  std::is_constructible<value_type, integer_type>::value;
2552
                };
2553
                template<typename value_type, typename boolean_type>
2554
                struct is_valid_json_boolean {
2555
                        static constexpr auto value = std::is_convertible<boolean_type, bool>::value &&
2556
                                                                                  std::is_constructible<value_type, boolean_type>::value;
2557
                };
2558

2559
                template<typename value_type, typename object_type, typename array_type, typename string_type,
2560
                                 typename number_type, typename integer_type, typename boolean_type>
2561
                struct is_valid_json_types {
2562
                        // Internal assertions for better feedback
2563
                        static_assert(is_valid_json_value<value_type>::value,
2564
                                                  "value_type must meet basic requirements, default constructor, copyable, moveable");
2565
                        static_assert(is_valid_json_object<value_type, string_type, object_type>::value,
2566
                                                  "object_type must be a string_type to value_type container");
2567
                        static_assert(is_valid_json_array<value_type, array_type>::value,
2568
                                                  "array_type must be a container of value_type");
2569

2570
                        static constexpr auto value = is_valid_json_value<value_type>::value &&
2571
                                                                                  is_valid_json_object<value_type, string_type, object_type>::value &&
2572
                                                                                  is_valid_json_array<value_type, array_type>::value &&
2573
                                                                                  is_valid_json_string<value_type, string_type, integer_type>::value &&
2574
                                                                                  is_valid_json_number<value_type, number_type>::value &&
2575
                                                                                  is_valid_json_integer<value_type, integer_type>::value &&
2576
                                                                                  is_valid_json_boolean<value_type, boolean_type>::value;
2577
                };
2578
        } // namespace details
2579

2580
        /**
2581
         * \brief a class to store a generic JSON value as claim
2582
         *
2583
         * \tparam json_traits : JSON implementation traits
2584
         *
2585
         * \see [RFC 7519: JSON Web Token (JWT)](https://tools.ietf.org/html/rfc7519)
2586
         */
2587
        template<typename json_traits>
2588
        class basic_claim {
2589
                /**
2590
                 * The reason behind this is to provide an expressive abstraction without
2591
                 * over complicating the API. For more information take the time to read
2592
                 * https://github.com/nlohmann/json/issues/774. It maybe be expanded to
2593
                 * support custom string types.
2594
                 */
2595
                static_assert(std::is_same<typename json_traits::string_type, std::string>::value ||
2596
                                                  std::is_convertible<typename json_traits::string_type, std::string>::value ||
2597
                                                  std::is_constructible<typename json_traits::string_type, std::string>::value,
2598
                                          "string_type must be a std::string, convertible to a std::string, or construct a std::string.");
2599

2600
                static_assert(
2601
                        details::is_valid_json_types<typename json_traits::value_type, typename json_traits::object_type,
2602
                                                                                 typename json_traits::array_type, typename json_traits::string_type,
2603
                                                                                 typename json_traits::number_type, typename json_traits::integer_type,
2604
                                                                                 typename json_traits::boolean_type>::value,
2605
                        "must satisfy json container requirements");
2606
                static_assert(details::is_valid_traits<json_traits>::value, "traits must satisfy requirements");
2607

2608
                typename json_traits::value_type val;
2609

2610
        public:
2611
                /**
2612
                 * Order list of strings
2613
                 */
2614
                using set_t = std::set<typename json_traits::string_type>;
2615

2616
                basic_claim() = default;
16✔
2617
                basic_claim(const basic_claim&) = default;
234✔
2618
                basic_claim(basic_claim&&) = default;
46✔
2619
                basic_claim& operator=(const basic_claim&) = default;
2620
                basic_claim& operator=(basic_claim&&) = default;
2621
                ~basic_claim() = default;
644✔
2622

2623
                JWT_CLAIM_EXPLICIT basic_claim(typename json_traits::string_type s) : val(std::move(s)) {}
49✔
2624
                JWT_CLAIM_EXPLICIT basic_claim(const date& d)
30✔
2625
                        : val(typename json_traits::integer_type(
36✔
2626
                                  std::chrono::duration_cast<std::chrono::seconds>(d.time_since_epoch()).count())) {}
60✔
2627
                JWT_CLAIM_EXPLICIT basic_claim(typename json_traits::array_type a) : val(std::move(a)) {}
2628
                JWT_CLAIM_EXPLICIT basic_claim(typename json_traits::value_type v) : val(std::move(v)) {}
256✔
2629
                JWT_CLAIM_EXPLICIT basic_claim(const set_t& s) : val(typename json_traits::array_type(s.begin(), s.end())) {}
6✔
2630
                template<typename Iterator>
2631
                basic_claim(Iterator begin, Iterator end) : val(typename json_traits::array_type(begin, end)) {}
15✔
2632

2633
                /**
2634
                 * Get wrapped JSON value
2635
                 * \return Wrapped JSON value
2636
                 */
2637
                typename json_traits::value_type to_json() const { return val; }
56✔
2638

2639
                /**
2640
                 * Parse input stream into underlying JSON value
2641
                 * \return input stream
2642
                 */
2643
                std::istream& operator>>(std::istream& is) { return is >> val; }
8✔
2644

2645
                /**
2646
                 * Serialize claim to output stream from wrapped JSON value
2647
                 * \return output stream
2648
                 */
2649
                std::ostream& operator<<(std::ostream& os) { return os << val; }
2650

2651
                /**
2652
                 * Get type of contained JSON value
2653
                 * \return Type
2654
                 * \throw std::logic_error An internal error occurred
2655
                 */
2656
                json::type get_type() const { return json_traits::get_type(val); }
208✔
2657

2658
                /**
2659
                 * Get the contained JSON value as a string
2660
                 * \return content as string
2661
                 * \throw std::bad_cast Content was not a string
2662
                 */
2663
                typename json_traits::string_type as_string() const { return json_traits::as_string(val); }
217✔
2664

2665
                /**
2666
                 * \brief Get the contained JSON value as a date
2667
                 *
2668
                 * If the value is a decimal, it is rounded to the closest integer
2669
                 *
2670
                 * \return content as date
2671
                 * \throw std::bad_cast Content was not a date
2672
                 */
2673
                date as_date() const {
45✔
2674
                        using std::chrono::system_clock;
2675
                        if (get_type() == json::type::number)
45✔
2676
                                return date(std::chrono::seconds(static_cast<int64_t>(std::llround(as_number()))));
×
2677
                        return date(std::chrono::seconds(as_integer()));
45✔
2678
                }
2679

2680
                /**
2681
                 * Get the contained JSON value as an array
2682
                 * \return content as array
2683
                 * \throw std::bad_cast Content was not an array
2684
                 */
2685
                typename json_traits::array_type as_array() const { return json_traits::as_array(val); }
8✔
2686

2687
                /**
2688
                 * Get the contained JSON value as a set of strings
2689
                 * \return content as set of strings
2690
                 * \throw std::bad_cast Content was not an array of string
2691
                 */
2692
                set_t as_set() const {
1✔
2693
                        set_t res;
1✔
2694
                        for (const auto& e : json_traits::as_array(val)) {
3✔
2695
                                res.insert(json_traits::as_string(e));
2✔
2696
                        }
2697
                        return res;
1✔
2698
                }
×
2699

2700
                /**
2701
                 * Get the contained JSON value as an integer
2702
                 * \return content as int
2703
                 * \throw std::bad_cast Content was not an int
2704
                 */
2705
                typename json_traits::integer_type as_integer() const { return json_traits::as_integer(val); }
47✔
2706

2707
                /**
2708
                 * Get the contained JSON value as a bool
2709
                 * \return content as bool
2710
                 * \throw std::bad_cast Content was not a bool
2711
                 */
2712
                typename json_traits::boolean_type as_boolean() const { return json_traits::as_boolean(val); }
1✔
2713

2714
                /**
2715
                 * Get the contained JSON value as a number
2716
                 * \return content as double
2717
                 * \throw std::bad_cast Content was not a number
2718
                 */
2719
                typename json_traits::number_type as_number() const { return json_traits::as_number(val); }
1✔
2720
        };
2721

2722
        namespace error {
2723
                /**
2724
                 * Attempt to parse JSON was unsuccessful
2725
                 */
2726
                struct invalid_json_exception : public std::runtime_error {
2727
                        invalid_json_exception() : runtime_error("invalid json") {}
3✔
2728
                };
2729
                /**
2730
                 * Attempt to access claim was unsuccessful
2731
                 */
2732
                struct claim_not_present_exception : public std::out_of_range {
2733
                        claim_not_present_exception() : out_of_range("claim not found") {}
6✔
2734
                };
2735
        } // namespace error
2736

2737
        namespace details {
2738
                template<typename json_traits>
2739
                struct map_of_claims {
2740
                        typename json_traits::object_type claims;
2741
                        using basic_claim_t = basic_claim<json_traits>;
2742
                        using iterator = typename json_traits::object_type::iterator;
2743
                        using const_iterator = typename json_traits::object_type::const_iterator;
2744

2745
                        map_of_claims() = default;
174✔
2746
                        map_of_claims(const map_of_claims&) = default;
22✔
2747
                        map_of_claims(map_of_claims&&) = default;
2748
                        map_of_claims& operator=(const map_of_claims&) = default;
2749
                        map_of_claims& operator=(map_of_claims&&) = default;
166✔
2750

2751
                        map_of_claims(typename json_traits::object_type json) : claims(std::move(json)) {}
176✔
2752

2753
                        iterator begin() { return claims.begin(); }
2754
                        iterator end() { return claims.end(); }
2755
                        const_iterator cbegin() const { return claims.begin(); }
2756
                        const_iterator cend() const { return claims.end(); }
2757
                        const_iterator begin() const { return claims.begin(); }
2758
                        const_iterator end() const { return claims.end(); }
2759

2760
                        /**
2761
                         * \brief Parse a JSON string into a map of claims
2762
                         *
2763
                         * The implication is that a "map of claims" is identic to a JSON object
2764
                         *
2765
                         * \param str JSON data to be parse as an object
2766
                         * \return content as JSON object
2767
                         */
2768
                        static typename json_traits::object_type parse_claims(const typename json_traits::string_type& str) {
170✔
2769
                                typename json_traits::value_type val;
170✔
2770
                                if (!json_traits::parse(val, str)) throw error::invalid_json_exception();
170✔
2771

2772
                                return json_traits::as_object(val);
333✔
2773
                        };
170✔
2774

2775
                        /**
2776
                         * Check if a claim is present in the map
2777
                         * \return true if claim was present, false otherwise
2778
                         */
2779
                        bool has_claim(const typename json_traits::string_type& name) const noexcept {
619✔
2780
                                return claims.count(name) != 0;
619✔
2781
                        }
2782

2783
                        /**
2784
                         * Get a claim by name
2785
                         *
2786
                         * \param name the name of the desired claim
2787
                         * \return Requested claim
2788
                         * \throw jwt::error::claim_not_present_exception if the claim was not present
2789
                         */
2790
                        basic_claim_t get_claim(const typename json_traits::string_type& name) const {
250✔
2791
                                if (!has_claim(name)) throw error::claim_not_present_exception();
250✔
2792
                                return basic_claim_t{claims.at(name)};
246✔
2793
                        }
2794
                };
2795
        } // namespace details
2796

2797
        /**
2798
         * Base class that represents a token payload.
2799
         * Contains Convenience accessors for common claims.
2800
         */
2801
        template<typename json_traits>
2802
        class payload {
2803
        protected:
2804
                details::map_of_claims<json_traits> payload_claims;
2805

2806
        public:
2807
                using basic_claim_t = basic_claim<json_traits>;
2808

2809
                /**
2810
                 * Check if issuer is present ("iss")
2811
                 * \return true if present, false otherwise
2812
                 */
2813
                bool has_issuer() const noexcept { return has_payload_claim("iss"); }
27✔
2814
                /**
2815
                 * Check if subject is present ("sub")
2816
                 * \return true if present, false otherwise
2817
                 */
2818
                bool has_subject() const noexcept { return has_payload_claim("sub"); }
27✔
2819
                /**
2820
                 * Check if audience is present ("aud")
2821
                 * \return true if present, false otherwise
2822
                 */
2823
                bool has_audience() const noexcept { return has_payload_claim("aud"); }
24✔
2824
                /**
2825
                 * Check if expires is present ("exp")
2826
                 * \return true if present, false otherwise
2827
                 */
2828
                bool has_expires_at() const noexcept { return has_payload_claim("exp"); }
210✔
2829
                /**
2830
                 * Check if not before is present ("nbf")
2831
                 * \return true if present, false otherwise
2832
                 */
2833
                bool has_not_before() const noexcept { return has_payload_claim("nbf"); }
228✔
2834
                /**
2835
                 * Check if issued at is present ("iat")
2836
                 * \return true if present, false otherwise
2837
                 */
2838
                bool has_issued_at() const noexcept { return has_payload_claim("iat"); }
216✔
2839
                /**
2840
                 * Check if token id is present ("jti")
2841
                 * \return true if present, false otherwise
2842
                 */
2843
                bool has_id() const noexcept { return has_payload_claim("jti"); }
24✔
2844
                /**
2845
                 * Get issuer claim
2846
                 * \return issuer as string
2847
                 * \throw std::runtime_error If claim was not present
2848
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
2849
                 */
2850
                typename json_traits::string_type get_issuer() const { return get_payload_claim("iss").as_string(); }
9✔
2851
                /**
2852
                 * Get subject claim
2853
                 * \return subject as string
2854
                 * \throw std::runtime_error If claim was not present
2855
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
2856
                 */
2857
                typename json_traits::string_type get_subject() const { return get_payload_claim("sub").as_string(); }
3✔
2858
                /**
2859
                 * Get audience claim
2860
                 * \return audience as a set of strings
2861
                 * \throw std::runtime_error If claim was not present
2862
                 * \throw std::bad_cast Claim was present but not a set (Should not happen in a valid token)
2863
                 */
2864
                typename basic_claim_t::set_t get_audience() const {
6✔
2865
                        auto aud = get_payload_claim("aud");
6✔
2866
                        if (aud.get_type() == json::type::string) return {aud.as_string()};
21✔
2867

2868
                        return aud.as_set();
1✔
2869
                }
11✔
2870
                /**
2871
                 * Get expires claim
2872
                 * \return expires as a date in utc
2873
                 * \throw std::runtime_error If claim was not present
2874
                 * \throw std::bad_cast Claim was present but not a date (Should not happen in a valid token)
2875
                 */
2876
                date get_expires_at() const { return get_payload_claim("exp").as_date(); }
60✔
2877
                /**
2878
                 * Get not valid before claim
2879
                 * \return nbf date in utc
2880
                 * \throw std::runtime_error If claim was not present
2881
                 * \throw std::bad_cast Claim was present but not a date (Should not happen in a valid token)
2882
                 */
2883
                date get_not_before() const { return get_payload_claim("nbf").as_date(); }
12✔
2884
                /**
2885
                 * Get issued at claim
2886
                 * \return issued at as date in utc
2887
                 * \throw std::runtime_error If claim was not present
2888
                 * \throw std::bad_cast Claim was present but not a date (Should not happen in a valid token)
2889
                 */
2890
                date get_issued_at() const { return get_payload_claim("iat").as_date(); }
60✔
2891
                /**
2892
                 * Get id claim
2893
                 * \return id as string
2894
                 * \throw std::runtime_error If claim was not present
2895
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
2896
                 */
2897
                typename json_traits::string_type get_id() const { return get_payload_claim("jti").as_string(); }
2898
                /**
2899
                 * Check if a payload claim is present
2900
                 * \return true if claim was present, false otherwise
2901
                 */
2902
                bool has_payload_claim(const typename json_traits::string_type& name) const noexcept {
302✔
2903
                        return payload_claims.has_claim(name);
302✔
2904
                }
2905
                /**
2906
                 * Get payload claim
2907
                 * \return Requested claim
2908
                 * \throw std::runtime_error If claim was not present
2909
                 */
2910
                basic_claim_t get_payload_claim(const typename json_traits::string_type& name) const {
54✔
2911
                        return payload_claims.get_claim(name);
54✔
2912
                }
2913
        };
2914

2915
        /**
2916
         * Base class that represents a token header.
2917
         * Contains Convenience accessors for common claims.
2918
         */
2919
        template<typename json_traits>
2920
        class header {
2921
        protected:
2922
                details::map_of_claims<json_traits> header_claims;
2923

2924
        public:
2925
                using basic_claim_t = basic_claim<json_traits>;
2926
                /**
2927
                 * Check if algorithm is present ("alg")
2928
                 * \return true if present, false otherwise
2929
                 */
2930
                bool has_algorithm() const noexcept { return has_header_claim("alg"); }
27✔
2931
                /**
2932
                 * Check if type is present ("typ")
2933
                 * \return true if present, false otherwise
2934
                 */
2935
                bool has_type() const noexcept { return has_header_claim("typ"); }
27✔
2936
                /**
2937
                 * Check if content type is present ("cty")
2938
                 * \return true if present, false otherwise
2939
                 */
2940
                bool has_content_type() const noexcept { return has_header_claim("cty"); }
24✔
2941
                /**
2942
                 * Check if key id is present ("kid")
2943
                 * \return true if present, false otherwise
2944
                 */
2945
                bool has_key_id() const noexcept { return has_header_claim("kid"); }
24✔
2946
                /**
2947
                 * Get algorithm claim
2948
                 * \return algorithm as string
2949
                 * \throw std::runtime_error If claim was not present
2950
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
2951
                 */
2952
                typename json_traits::string_type get_algorithm() const { return get_header_claim("alg").as_string(); }
312✔
2953
                /**
2954
                 * Get type claim
2955
                 * \return type as a string
2956
                 * \throw std::runtime_error If claim was not present
2957
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
2958
                 */
2959
                typename json_traits::string_type get_type() const { return get_header_claim("typ").as_string(); }
27✔
2960
                /**
2961
                 * Get content type claim
2962
                 * \return content type as string
2963
                 * \throw std::runtime_error If claim was not present
2964
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
2965
                 */
2966
                typename json_traits::string_type get_content_type() const { return get_header_claim("cty").as_string(); }
2967
                /**
2968
                 * Get key id claim
2969
                 * \return key id as string
2970
                 * \throw std::runtime_error If claim was not present
2971
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
2972
                 */
2973
                typename json_traits::string_type get_key_id() const { return get_header_claim("kid").as_string(); }
2974
                /**
2975
                 * Check if a header claim is present
2976
                 * \return true if claim was present, false otherwise
2977
                 */
2978
                bool has_header_claim(const typename json_traits::string_type& name) const noexcept {
37✔
2979
                        return header_claims.has_claim(name);
37✔
2980
                }
2981
                /**
2982
                 * Get header claim
2983
                 * \return Requested claim
2984
                 * \throw std::runtime_error If claim was not present
2985
                 */
2986
                basic_claim_t get_header_claim(const typename json_traits::string_type& name) const {
113✔
2987
                        return header_claims.get_claim(name);
113✔
2988
                }
2989
        };
2990

2991
        /**
2992
         * Class containing all information about a decoded token
2993
         */
2994
        template<typename json_traits>
2995
        class decoded_jwt : public header<json_traits>, public payload<json_traits> {
2996
        protected:
2997
                /// Unmodified token, as passed to constructor
2998
                typename json_traits::string_type token;
2999
                /// Header part decoded from base64
3000
                typename json_traits::string_type header;
3001
                /// Unmodified header part in base64
3002
                typename json_traits::string_type header_base64;
3003
                /// Payload part decoded from base64
3004
                typename json_traits::string_type payload;
3005
                /// Unmodified payload part in base64
3006
                typename json_traits::string_type payload_base64;
3007
                /// Signature part decoded from base64
3008
                typename json_traits::string_type signature;
3009
                /// Unmodified signature part in base64
3010
                typename json_traits::string_type signature_base64;
3011

3012
        public:
3013
                using basic_claim_t = basic_claim<json_traits>;
3014
#ifndef JWT_DISABLE_BASE64
3015
                /**
3016
                 * \brief Parses a given token
3017
                 *
3018
                 * \note Decodes using the jwt::base64url which supports an std::string
3019
                 *
3020
                 * \param token The token to parse
3021
                 * \throw std::invalid_argument Token is not in correct format
3022
                 * \throw std::runtime_error Base64 decoding failed or invalid json
3023
                 */
3024
                JWT_CLAIM_EXPLICIT decoded_jwt(const typename json_traits::string_type& token)
87✔
3025
                        : decoded_jwt(token, [](const typename json_traits::string_type& str) {
250✔
3026
                                  return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(str));
250✔
3027
                          }) {}
87✔
3028
#endif
3029
                /**
3030
                 * \brief Parses a given token
3031
                 *
3032
                 * \tparam Decode is callable, taking a string_type and returns a string_type.
3033
                 * It should ensure the padding of the input and then base64url decode and
3034
                 * return the results.
3035
                 * \param token The token to parse
3036
                 * \param decode The function to decode the token
3037
                 * \throw std::invalid_argument Token is not in correct format
3038
                 * \throw std::runtime_error Base64 decoding failed or invalid json
3039
                 */
3040
                template<typename Decode>
3041
                decoded_jwt(const typename json_traits::string_type& token, Decode decode) : token(token) {
87✔
3042
                        auto hdr_end = token.find('.');
87✔
3043
                        if (hdr_end == json_traits::string_type::npos) throw std::invalid_argument("invalid token supplied");
87✔
3044
                        auto payload_end = token.find('.', hdr_end + 1);
86✔
3045
                        if (payload_end == json_traits::string_type::npos) throw std::invalid_argument("invalid token supplied");
86✔
3046
                        header_base64 = token.substr(0, hdr_end);
84✔
3047
                        payload_base64 = token.substr(hdr_end + 1, payload_end - hdr_end - 1);
84✔
3048
                        signature_base64 = token.substr(payload_end + 1);
84✔
3049

3050
                        header = decode(header_base64);
84✔
3051
                        payload = decode(payload_base64);
83✔
3052
                        signature = decode(signature_base64);
83✔
3053

3054
                        this->header_claims = details::map_of_claims<json_traits>::parse_claims(header);
83✔
3055
                        this->payload_claims = details::map_of_claims<json_traits>::parse_claims(payload);
82✔
3056
                }
127✔
3057

3058
                /**
3059
                 * Get token string, as passed to constructor
3060
                 * \return token as passed to constructor
3061
                 */
3062
                const typename json_traits::string_type& get_token() const noexcept { return token; }
1✔
3063
                /**
3064
                 * Get header part as json string
3065
                 * \return header part after base64 decoding
3066
                 */
3067
                const typename json_traits::string_type& get_header() const noexcept { return header; }
3068
                /**
3069
                 * Get payload part as json string
3070
                 * \return payload part after base64 decoding
3071
                 */
3072
                const typename json_traits::string_type& get_payload() const noexcept { return payload; }
3073
                /**
3074
                 * Get signature part as json string
3075
                 * \return signature part after base64 decoding
3076
                 */
3077
                const typename json_traits::string_type& get_signature() const noexcept { return signature; }
94✔
3078
                /**
3079
                 * Get header part as base64 string
3080
                 * \return header part before base64 decoding
3081
                 */
3082
                const typename json_traits::string_type& get_header_base64() const noexcept { return header_base64; }
94✔
3083
                /**
3084
                 * Get payload part as base64 string
3085
                 * \return payload part before base64 decoding
3086
                 */
3087
                const typename json_traits::string_type& get_payload_base64() const noexcept { return payload_base64; }
94✔
3088
                /**
3089
                 * Get signature part as base64 string
3090
                 * \return signature part before base64 decoding
3091
                 */
3092
                const typename json_traits::string_type& get_signature_base64() const noexcept { return signature_base64; }
3093
                /**
3094
                 * Get all payload as JSON object
3095
                 * \return map of claims
3096
                 */
3097
                typename json_traits::object_type get_payload_json() const { return this->payload_claims.claims; }
3098
                /**
3099
                 * Get all header as JSON object
3100
                 * \return map of claims
3101
                 */
3102
                typename json_traits::object_type get_header_json() const { return this->header_claims.claims; }
3103
                /**
3104
                 * Get a payload claim by name
3105
                 *
3106
                 * \param name the name of the desired claim
3107
                 * \return Requested claim
3108
                 * \throw jwt::error::claim_not_present_exception if the claim was not present
3109
                 */
3110
                basic_claim_t get_payload_claim(const typename json_traits::string_type& name) const {
47✔
3111
                        return this->payload_claims.get_claim(name);
47✔
3112
                }
3113
                /**
3114
                 * Get a header claim by name
3115
                 *
3116
                 * \param name the name of the desired claim
3117
                 * \return Requested claim
3118
                 * \throw jwt::error::claim_not_present_exception if the claim was not present
3119
                 */
3120
                basic_claim_t get_header_claim(const typename json_traits::string_type& name) const {
4✔
3121
                        return this->header_claims.get_claim(name);
4✔
3122
                }
3123
        };
3124

3125
        /**
3126
         * Builder class to build and sign a new token
3127
         * Use jwt::create() to get an instance of this class.
3128
         */
3129
        template<typename Clock, typename json_traits>
3130
        class builder {
3131
                typename json_traits::object_type header_claims;
3132
                typename json_traits::object_type payload_claims;
3133

3134
                /// Instance of clock type
3135
                Clock clock;
3136

3137
        public:
3138
                /**
3139
                 * Constructor for building a new builder instance
3140
                 * \param c Clock instance
3141
                 */
3142
                JWT_CLAIM_EXPLICIT builder(Clock c) : clock(c) {}
53✔
3143
                /**
3144
                 * Set a header claim.
3145
                 * \param id Name of the claim
3146
                 * \param c Claim to add
3147
                 * \return *this to allow for method chaining
3148
                 */
3149
                builder& set_header_claim(const typename json_traits::string_type& id, typename json_traits::value_type c) {
25✔
3150
                        header_claims[id] = std::move(c);
25✔
3151
                        return *this;
25✔
3152
                }
3153

3154
                /**
3155
                 * Set a header claim.
3156
                 * \param id Name of the claim
3157
                 * \param c Claim to add
3158
                 * \return *this to allow for method chaining
3159
                 */
3160
                builder& set_header_claim(const typename json_traits::string_type& id, basic_claim<json_traits> c) {
3161
                        header_claims[id] = c.to_json();
3162
                        return *this;
3163
                }
3164
                /**
3165
                 * Set a payload claim.
3166
                 * \param id Name of the claim
3167
                 * \param c Claim to add
3168
                 * \return *this to allow for method chaining
3169
                 */
3170
                builder& set_payload_claim(const typename json_traits::string_type& id, typename json_traits::value_type c) {
37✔
3171
                        payload_claims[id] = std::move(c);
37✔
3172
                        return *this;
37✔
3173
                }
3174
                /**
3175
                 * Set a payload claim.
3176
                 * \param id Name of the claim
3177
                 * \param c Claim to add
3178
                 * \return *this to allow for method chaining
3179
                 */
3180
                builder& set_payload_claim(const typename json_traits::string_type& id, basic_claim<json_traits> c) {
40✔
3181
                        payload_claims[id] = c.to_json();
40✔
3182
                        return *this;
40✔
3183
                }
3184
                /**
3185
                 * \brief Set algorithm claim
3186
                 * You normally don't need to do this, as the algorithm is automatically set if you don't change it.
3187
                 *
3188
                 * \param str Name of algorithm
3189
                 * \return *this to allow for method chaining
3190
                 */
3191
                builder& set_algorithm(typename json_traits::string_type str) {
1✔
3192
                        return set_header_claim("alg", typename json_traits::value_type(str));
3✔
3193
                }
3194
                /**
3195
                 * Set type claim
3196
                 * \param str Type to set
3197
                 * \return *this to allow for method chaining
3198
                 */
3199
                builder& set_type(typename json_traits::string_type str) {
24✔
3200
                        return set_header_claim("typ", typename json_traits::value_type(str));
72✔
3201
                }
3202
                /**
3203
                 * Set content type claim
3204
                 * \param str Type to set
3205
                 * \return *this to allow for method chaining
3206
                 */
3207
                builder& set_content_type(typename json_traits::string_type str) {
3208
                        return set_header_claim("cty", typename json_traits::value_type(str));
3209
                }
3210
                /**
3211
                 * \brief Set key id claim
3212
                 *
3213
                 * \param str Key id to set
3214
                 * \return *this to allow for method chaining
3215
                 */
3216
                builder& set_key_id(typename json_traits::string_type str) {
3217
                        return set_header_claim("kid", typename json_traits::value_type(str));
3218
                }
3219
                /**
3220
                 * Set issuer claim
3221
                 * \param str Issuer to set
3222
                 * \return *this to allow for method chaining
3223
                 */
3224
                builder& set_issuer(typename json_traits::string_type str) {
33✔
3225
                        return set_payload_claim("iss", typename json_traits::value_type(str));
99✔
3226
                }
3227
                /**
3228
                 * Set subject claim
3229
                 * \param str Subject to set
3230
                 * \return *this to allow for method chaining
3231
                 */
3232
                builder& set_subject(typename json_traits::string_type str) {
3233
                        return set_payload_claim("sub", typename json_traits::value_type(str));
3234
                }
3235
                /**
3236
                 * Set audience claim
3237
                 * \param a Audience set
3238
                 * \return *this to allow for method chaining
3239
                 */
3240
                builder& set_audience(typename json_traits::array_type a) {
1✔
3241
                        return set_payload_claim("aud", typename json_traits::value_type(a));
3✔
3242
                }
3243
                /**
3244
                 * Set audience claim
3245
                 * \param aud Single audience
3246
                 * \return *this to allow for method chaining
3247
                 */
3248
                builder& set_audience(typename json_traits::string_type aud) {
2✔
3249
                        return set_payload_claim("aud", typename json_traits::value_type(aud));
6✔
3250
                }
3251
                /**
3252
                 * Set expires at claim
3253
                 * \param d Expires time
3254
                 * \return *this to allow for method chaining
3255
                 */
3256
                builder& set_expires_at(const date& d) { return set_payload_claim("exp", basic_claim<json_traits>(d)); }
30✔
3257
                /**
3258
                 * Set expires at claim to @p d from the current moment
3259
                 * \param d token expiration timeout
3260
                 * \return *this to allow for method chaining
3261
                 */
3262
                template<class Rep, class Period>
3263
                builder& set_expires_in(const std::chrono::duration<Rep, Period>& d) {
4✔
3264
                        return set_payload_claim("exp", basic_claim<json_traits>(clock.now() + d));
12✔
3265
                }
3266
                /**
3267
                 * Set not before claim
3268
                 * \param d First valid time
3269
                 * \return *this to allow for method chaining
3270
                 */
3271
                builder& set_not_before(const date& d) { return set_payload_claim("nbf", basic_claim<json_traits>(d)); }
6✔
3272
                /**
3273
                 * Set issued at claim
3274
                 * \param d Issued at time, should be current time
3275
                 * \return *this to allow for method chaining
3276
                 */
3277
                builder& set_issued_at(const date& d) { return set_payload_claim("iat", basic_claim<json_traits>(d)); }
42✔
3278
                /**
3279
                 * Set issued at claim to the current moment
3280
                 * \return *this to allow for method chaining
3281
                 */
3282
                builder& set_issued_now() { return set_issued_at(clock.now()); }
4✔
3283
                /**
3284
                 * Set id claim
3285
                 * \param str ID to set
3286
                 * \return *this to allow for method chaining
3287
                 */
3288
                builder& set_id(const typename json_traits::string_type& str) {
3289
                        return set_payload_claim("jti", typename json_traits::value_type(str));
3290
                }
3291

3292
                /**
3293
                 * Sign token and return result
3294
                 * \tparam Algo Callable method which takes a string_type and return the signed input as a string_type
3295
                 * \tparam Encode Callable method which takes a string_type and base64url safe encodes it,
3296
                 * MUST return the result with no padding; trim the result.
3297
                 * \param algo Instance of an algorithm to sign the token with
3298
                 * \param encode Callable to transform the serialized json to base64 with no padding
3299
                 * \return Final token as a string
3300
                 *
3301
                 * \note If the 'alg' header in not set in the token it will be set to `algo.name()`
3302
                 */
3303
                template<typename Algo, typename Encode>
3304
                typename json_traits::string_type sign(const Algo& algo, Encode encode) const {
3305
                        std::error_code ec;
3306
                        auto res = sign(algo, encode, ec);
3307
                        error::throw_if_error(ec);
3308
                        return res;
3309
                }
3310
#ifndef JWT_DISABLE_BASE64
3311
                /**
3312
                 * Sign token and return result
3313
                 *
3314
                 * using the `jwt::base` functions provided
3315
                 *
3316
                 * \param algo Instance of an algorithm to sign the token with
3317
                 * \return Final token as a string
3318
                 */
3319
                template<typename Algo>
3320
                typename json_traits::string_type sign(const Algo& algo) const {
53✔
3321
                        std::error_code ec;
53✔
3322
                        auto res = sign(algo, ec);
53✔
3323
                        error::throw_if_error(ec);
53✔
3324
                        return res;
98✔
3325
                }
4✔
3326
#endif
3327

3328
                /**
3329
                 * Sign token and return result
3330
                 * \tparam Algo Callable method which takes a string_type and return the signed input as a string_type
3331
                 * \tparam Encode Callable method which takes a string_type and base64url safe encodes it,
3332
                 * MUST return the result with no padding; trim the result.
3333
                 * \param algo Instance of an algorithm to sign the token with
3334
                 * \param encode Callable to transform the serialized json to base64 with no padding
3335
                 * \param ec error_code filled with details on error
3336
                 * \return Final token as a string
3337
                 *
3338
                 * \note If the 'alg' header in not set in the token it will be set to `algo.name()`
3339
                 */
3340
                template<typename Algo, typename Encode>
3341
                typename json_traits::string_type sign(const Algo& algo, Encode encode, std::error_code& ec) const {
53✔
3342
                        // make a copy such that a builder can be re-used
3343
                        typename json_traits::object_type obj_header = header_claims;
53✔
3344
                        if (header_claims.count("alg") == 0) obj_header["alg"] = typename json_traits::value_type(algo.name());
223✔
3345

3346
                        const auto header = encode(json_traits::serialize(typename json_traits::value_type(obj_header)));
53✔
3347
                        const auto payload = encode(json_traits::serialize(typename json_traits::value_type(payload_claims)));
53✔
3348
                        const auto token = header + "." + payload;
53✔
3349

3350
                        auto signature = algo.sign(token, ec);
53✔
3351
                        if (ec) return {};
53✔
3352

3353
                        return token + "." + encode(signature);
49✔
3354
                }
53✔
3355
#ifndef JWT_DISABLE_BASE64
3356
                /**
3357
                 * Sign token and return result
3358
                 *
3359
                 * using the `jwt::base` functions provided
3360
                 *
3361
                 * \param algo Instance of an algorithm to sign the token with
3362
                 * \param ec error_code filled with details on error
3363
                 * \return Final token as a string
3364
                 */
3365
                template<typename Algo>
3366
                typename json_traits::string_type sign(const Algo& algo, std::error_code& ec) const {
53✔
3367
                        return sign(
3368
                                algo,
3369
                                [](const typename json_traits::string_type& data) {
155✔
3370
                                        return base::trim<alphabet::base64url>(base::encode<alphabet::base64url>(data));
155✔
3371
                                },
3372
                                ec);
53✔
3373
                }
3374
#endif
3375
        };
3376

3377
        namespace verify_ops {
3378
                /**
3379
                 * This is the base container which holds the token that need to be verified
3380
                 */
3381
                template<typename json_traits>
3382
                struct verify_context {
3383
                        verify_context(date ctime, const decoded_jwt<json_traits>& j, size_t l)
75✔
3384
                                : current_time(ctime), jwt(j), default_leeway(l) {}
75✔
3385
                        /// Current time, retrieved from the verifiers clock and cached for performance and consistency
3386
                        date current_time;
3387
                        /// The jwt passed to the verifier
3388
                        const decoded_jwt<json_traits>& jwt;
3389
                        /// The configured default leeway for this verification
3390
                        size_t default_leeway{0};
3391

3392
                        /// The claim key to apply this comparison on
3393
                        typename json_traits::string_type claim_key{};
3394

3395
                        /**
3396
                         * \brief Helper method to get a claim from the jwt in this context
3397
                         * \param in_header check JWT header or payload sections
3398
                         * \param ec std::error_code which will indicate if any error occure
3399
                         * \return basic_claim if it was present otherwise empty
3400
                         */
3401
                        basic_claim<json_traits> get_claim(bool in_header, std::error_code& ec) const {
53✔
3402
                                if (in_header) {
53✔
3403
                                        if (!jwt.has_header_claim(claim_key)) {
3✔
3404
                                                ec = error::token_verification_error::missing_claim;
×
3405
                                                return {};
×
3406
                                        }
3407
                                        return jwt.get_header_claim(claim_key);
3✔
3408
                                } else {
3409
                                        if (!jwt.has_payload_claim(claim_key)) {
50✔
3410
                                                ec = error::token_verification_error::missing_claim;
4✔
3411
                                                return {};
4✔
3412
                                        }
3413
                                        return jwt.get_payload_claim(claim_key);
46✔
3414
                                }
3415
                        }
3416
                        /**
3417
                         * Helper method to get a claim of a specific type from the jwt in this context
3418
                         * \param in_header check JWT header or payload sections
3419
                         * \param t the expected type of the claim
3420
                         * \param ec std::error_code which will indicate if any error occure
3421
                         * \return basic_claim if it was present otherwise empty
3422
                          */
3423
                        basic_claim<json_traits> get_claim(bool in_header, json::type t, std::error_code& ec) const {
50✔
3424
                                auto c = get_claim(in_header, ec);
50✔
3425
                                if (ec) return {};
50✔
3426
                                if (c.get_type() != t) {
47✔
3427
                                        ec = error::token_verification_error::claim_type_missmatch;
1✔
3428
                                        return {};
1✔
3429
                                }
3430
                                return c;
46✔
3431
                        }
50✔
3432
                        /**
3433
                         * \brief Helper method to get a payload claim from the jwt
3434
                         * \param ec std::error_code which will indicate if any error occure
3435
                         * \return basic_claim if it was present otherwise empty
3436
                          */
3437
                        basic_claim<json_traits> get_claim(std::error_code& ec) const { return get_claim(false, ec); }
3438
                        /**
3439
                         * \brief Helper method to get a payload claim of a specific type from the jwt
3440
                         * \param t the expected type of the claim
3441
                         * \param ec std::error_code which will indicate if any error occure
3442
                         * \return basic_claim if it was present otherwise empty
3443
                          */
3444
                        basic_claim<json_traits> get_claim(json::type t, std::error_code& ec) const {
3445
                                return get_claim(false, t, ec);
3446
                        }
3447
                };
3448

3449
                /**
3450
                 * This is the default operation and does case sensitive matching
3451
                 */
3452
                template<typename json_traits, bool in_header = false>
3453
                struct equals_claim {
3454
                        const basic_claim<json_traits> expected;
3455
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
47✔
3456
                                auto jc = ctx.get_claim(in_header, expected.get_type(), ec);
47✔
3457
                                if (ec) return;
47✔
3458
                                const bool matches = [&]() {
×
3459
                                        switch (expected.get_type()) {
43✔
3460
                                        case json::type::boolean: return expected.as_boolean() == jc.as_boolean();
×
3461
                                        case json::type::integer: return expected.as_integer() == jc.as_integer();
×
3462
                                        case json::type::number: return expected.as_number() == jc.as_number();
×
3463
                                        case json::type::string: return expected.as_string() == jc.as_string();
35✔
3464
                                        case json::type::array:
8✔
3465
                                        case json::type::object:
3466
                                                return json_traits::serialize(expected.to_json()) == json_traits::serialize(jc.to_json());
8✔
3467
                                        default: throw std::logic_error("internal error, should be unreachable");
×
3468
                                        }
3469
                                }();
43✔
3470
                                if (!matches) {
43✔
3471
                                        ec = error::token_verification_error::claim_value_missmatch;
1✔
3472
                                        return;
1✔
3473
                                }
3474
                        }
47✔
3475
                };
3476

3477
                /**
3478
                 * Checks that the current time is before the time specified in the given
3479
                 * claim. This is identical to how the "exp" check works.
3480
                 */
3481
                template<typename json_traits, bool in_header = false>
3482
                struct date_before_claim {
3483
                        const size_t leeway;
3484
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3485
                                auto jc = ctx.get_claim(in_header, json::type::integer, ec);
3486
                                if (ec) return;
3487
                                auto c = jc.as_date();
3488
                                if (ctx.current_time > c + std::chrono::seconds(leeway)) {
3489
                                        ec = error::token_verification_error::token_expired;
3490
                                }
3491
                        }
3492
                };
3493

3494
                /**
3495
                 * Checks that the current time is after the time specified in the given
3496
                 * claim. This is identical to how the "nbf" and "iat" check works.
3497
                 */
3498
                template<typename json_traits, bool in_header = false>
3499
                struct date_after_claim {
3500
                        const size_t leeway;
3501
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3502
                                auto jc = ctx.get_claim(in_header, json::type::integer, ec);
3503
                                if (ec) return;
3504
                                auto c = jc.as_date();
3505
                                if (ctx.current_time < c - std::chrono::seconds(leeway)) {
3506
                                        ec = error::token_verification_error::token_expired;
3507
                                }
3508
                        }
3509
                };
3510

3511
                /**
3512
                 * Checks if the given set is a subset of the set inside the token.
3513
                 * If the token value is a string it is treated as a set with a single element.
3514
                 * The comparison is case sensitive.
3515
                 */
3516
                template<typename json_traits, bool in_header = false>
3517
                struct is_subset_claim {
3518
                        const typename basic_claim<json_traits>::set_t expected;
3519
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3✔
3520
                                auto c = ctx.get_claim(in_header, ec);
3✔
3521
                                if (ec) return;
3✔
3522
                                if (c.get_type() == json::type::string) {
2✔
3523
                                        if (expected.size() != 1 || *expected.begin() != c.as_string()) {
2✔
3524
                                                ec = error::token_verification_error::audience_missmatch;
2✔
3525
                                                return;
2✔
3526
                                        }
3527
                                } else if (c.get_type() == json::type::array) {
×
3528
                                        auto jc = c.as_set();
×
3529
                                        for (auto& e : expected) {
×
3530
                                                if (jc.find(e) == jc.end()) {
×
3531
                                                        ec = error::token_verification_error::audience_missmatch;
×
3532
                                                        return;
×
3533
                                                }
3534
                                        }
3535
                                } else {
×
3536
                                        ec = error::token_verification_error::claim_type_missmatch;
×
3537
                                        return;
×
3538
                                }
3539
                        }
3✔
3540
                };
3541

3542
                /**
3543
                 * Checks if the claim is a string and does an case insensitive comparison.
3544
                 */
3545
                template<typename json_traits, bool in_header = false>
3546
                struct insensitive_string_claim {
3547
                        const typename json_traits::string_type expected;
3548
                        std::locale locale;
3549
                        insensitive_string_claim(const typename json_traits::string_type& e, std::locale loc)
2✔
3550
                                : expected(to_lower_unicode(e, loc)), locale(loc) {}
2✔
3551

3552
                        void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3✔
3553
                                const auto c = ctx.get_claim(in_header, json::type::string, ec);
3✔
3554
                                if (ec) return;
3✔
3555
                                if (to_lower_unicode(c.as_string(), locale) != expected) {
3✔
3556
                                        ec = error::token_verification_error::claim_value_missmatch;
1✔
3557
                                }
3558
                        }
3✔
3559

3560
                        static std::string to_lower_unicode(const std::string& str, const std::locale& loc) {
5✔
3561
                                std::mbstate_t state = std::mbstate_t();
5✔
3562
                                const char* in_next = str.data();
5✔
3563
                                const char* in_end = str.data() + str.size();
5✔
3564
                                std::wstring wide;
5✔
3565
                                wide.reserve(str.size());
5✔
3566

3567
                                while (in_next != in_end) {
20✔
3568
                                        wchar_t wc;
3569
                                        std::size_t result = std::mbrtowc(&wc, in_next, in_end - in_next, &state);
15✔
3570
                                        if (result == static_cast<std::size_t>(-1)) {
15✔
3571
                                                throw std::runtime_error("encoding error: " + std::string(std::strerror(errno)));
×
3572
                                        } else if (result == static_cast<std::size_t>(-2)) {
15✔
3573
                                                throw std::runtime_error("conversion error: next bytes constitute an incomplete, but so far "
×
3574
                                                                                                 "valid, multibyte character.");
3575
                                        }
3576
                                        in_next += result;
15✔
3577
                                        wide.push_back(wc);
15✔
3578
                                }
3579

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

3583
                                std::string out;
5✔
3584
                                out.reserve(wide.size());
5✔
3585
                                for (wchar_t wc : wide) {
20✔
3586
                                        char mb[MB_LEN_MAX];
3587
                                        std::size_t n = std::wcrtomb(mb, wc, &state);
15✔
3588
                                        if (n != static_cast<std::size_t>(-1)) out.append(mb, n);
15✔
3589
                                }
3590

3591
                                return out;
10✔
3592
                        }
5✔
3593
                };
3594
        } // namespace verify_ops
3595

3596
        /**
3597
         * Verifier class used to check if a decoded token contains all claims required by your application and has a valid
3598
         * signature.
3599
         */
3600
        template<typename Clock, typename json_traits>
3601
        class verifier {
3602
        public:
3603
                using basic_claim_t = basic_claim<json_traits>;
3604
                /**
3605
                 * \brief Verification function data structure.
3606
                 *
3607
                 * This gets passed the current verifier, a reference to the decoded jwt, a reference to the key of this claim,
3608
                 * as well as a reference to an error_code.
3609
                 * The function checks if the actual value matches certain rules (e.g. equality to value x) and sets the error_code if
3610
                 * it does not. Once a non zero error_code is encountered the verification stops and this error_code becomes the result
3611
                 * returned from verify
3612
                 */
3613
                using verify_check_fn_t =
3614
                        std::function<void(const verify_ops::verify_context<json_traits>&, std::error_code& ec)>;
3615

3616
        private:
3617
                struct algo_base {
3618
                        virtual ~algo_base() = default;
83✔
3619
                        virtual void verify(const std::string& data, const std::string& sig, std::error_code& ec) = 0;
3620
                };
3621
                template<typename T>
3622
                struct algo : public algo_base {
3623
                        T alg;
3624
                        explicit algo(T a) : alg(a) {}
83✔
3625
                        void verify(const std::string& data, const std::string& sig, std::error_code& ec) override {
93✔
3626
                                alg.verify(data, sig, ec);
93✔
3627
                        }
93✔
3628
                };
3629
                /// Required claims
3630
                std::unordered_map<typename json_traits::string_type, verify_check_fn_t> claims;
3631
                /// Leeway time for exp, nbf and iat
3632
                size_t default_leeway = 0;
3633
                /// Instance of clock type
3634
                Clock clock;
3635
                /// Supported algorithms
3636
                std::unordered_map<std::string, std::shared_ptr<algo_base>> algs;
3637

3638
        public:
3639
                /**
3640
                 * Constructor for building a new verifier instance
3641
                 * \param c Clock instance
3642
                 */
3643
                explicit verifier(Clock c) : clock(c) {
87✔
3644
                        claims["exp"] = [](const verify_ops::verify_context<json_traits>& ctx, std::error_code& ec) {
208✔
3645
                                if (!ctx.jwt.has_expires_at()) return;
62✔
3646
                                auto exp = ctx.jwt.get_expires_at();
20✔
3647
                                if (ctx.current_time > exp + std::chrono::seconds(ctx.default_leeway)) {
20✔
3648
                                        ec = error::token_verification_error::token_expired;
10✔
3649
                                }
3650
                        };
3651
                        claims["iat"] = [](const verify_ops::verify_context<json_traits>& ctx, std::error_code& ec) {
210✔
3652
                                if (!ctx.jwt.has_issued_at()) return;
64✔
3653
                                auto iat = ctx.jwt.get_issued_at();
20✔
3654
                                if (ctx.current_time < iat - std::chrono::seconds(ctx.default_leeway)) {
20✔
3655
                                        ec = error::token_verification_error::token_expired;
2✔
3656
                                }
3657
                        };
3658
                        claims["nbf"] = [](const verify_ops::verify_context<json_traits>& ctx, std::error_code& ec) {
214✔
3659
                                if (!ctx.jwt.has_not_before()) return;
68✔
3660
                                auto nbf = ctx.jwt.get_not_before();
4✔
3661
                                if (ctx.current_time < nbf - std::chrono::seconds(ctx.default_leeway)) {
4✔
3662
                                        ec = error::token_verification_error::token_expired;
2✔
3663
                                }
3664
                        };
3665
                }
87✔
3666

3667
                /**
3668
                 * Set default leeway to use.
3669
                 * \param leeway Default leeway to use if not specified otherwise
3670
                 * \return *this to allow chaining
3671
                 */
3672
                verifier& leeway(size_t leeway) {
3673
                        default_leeway = leeway;
3674
                        return *this;
3675
                }
3676
                /**
3677
                 * Set leeway for expires at.
3678
                 * If not specified the default leeway will be used.
3679
                 * \param leeway Set leeway to use for expires at.
3680
                 * \return *this to allow chaining
3681
                 */
3682
                verifier& expires_at_leeway(size_t leeway) {
3683
                        claims["exp"] = verify_ops::date_before_claim<json_traits>{leeway};
3684
                        return *this;
3685
                }
3686
                /**
3687
                 * Set leeway for not before.
3688
                 * If not specified the default leeway will be used.
3689
                 * \param leeway Set leeway to use for not before.
3690
                 * \return *this to allow chaining
3691
                 */
3692
                verifier& not_before_leeway(size_t leeway) {
3693
                        claims["nbf"] = verify_ops::date_after_claim<json_traits>{leeway};
3694
                        return *this;
3695
                }
3696
                /**
3697
                 * Set leeway for issued at.
3698
                 * If not specified the default leeway will be used.
3699
                 * \param leeway Set leeway to use for issued at.
3700
                 * \return *this to allow chaining
3701
                 */
3702
                verifier& issued_at_leeway(size_t leeway) {
3703
                        claims["iat"] = verify_ops::date_after_claim<json_traits>{leeway};
3704
                        return *this;
3705
                }
3706

3707
                /**
3708
                 * Set an type to check for.
3709
                 *
3710
                 * According to [RFC 7519 Section 5.1](https://datatracker.ietf.org/doc/html/rfc7519#section-5.1),
3711
                 * This parameter is ignored by JWT implementations; any processing of this parameter is performed by the JWT application.
3712
                 * Check is case sensitive.
3713
                 *
3714
                 * \param type Type Header Parameter to check for.
3715
                 * \param locale Localization functionality to use when comparing
3716
                 * \return *this to allow chaining
3717
                 */
3718
                verifier& with_type(const typename json_traits::string_type& type, std::locale locale = std::locale{}) {
2✔
3719
                        return with_claim("typ", verify_ops::insensitive_string_claim<json_traits, true>{type, std::move(locale)});
6✔
3720
                }
3721

3722
                /**
3723
                 * Set an issuer to check for.
3724
                 * Check is case sensitive.
3725
                 * \param iss Issuer to check for.
3726
                 * \return *this to allow chaining
3727
                 */
3728
                verifier& with_issuer(const typename json_traits::string_type& iss) {
43✔
3729
                        return with_claim("iss", basic_claim_t(iss));
129✔
3730
                }
3731

3732
                /**
3733
                 * Set a subject to check for.
3734
                 * Check is case sensitive.
3735
                 * \param sub Subject to check for.
3736
                 * \return *this to allow chaining
3737
                 */
3738
                verifier& with_subject(const typename json_traits::string_type& sub) {
1✔
3739
                        return with_claim("sub", basic_claim_t(sub));
3✔
3740
                }
3741
                /**
3742
                 * Set an audience to check for.
3743
                 * If any of the specified audiences is not present in the token the check fails.
3744
                 * \param aud Audience to check for.
3745
                 * \return *this to allow chaining
3746
                 */
3747
                verifier& with_audience(const typename basic_claim_t::set_t& aud) {
3✔
3748
                        claims["aud"] = verify_ops::is_subset_claim<json_traits>{aud};
9✔
3749
                        return *this;
3✔
3750
                }
3✔
3751
                /**
3752
                 * Set an audience to check for.
3753
                 * If the specified audiences is not present in the token the check fails.
3754
                 * \param aud Audience to check for.
3755
                 * \return *this to allow chaining
3756
                 */
3757
                verifier& with_audience(const typename json_traits::string_type& aud) {
2✔
3758
                        typename basic_claim_t::set_t s;
2✔
3759
                        s.insert(aud);
2✔
3760
                        return with_audience(s);
4✔
3761
                }
2✔
3762
                /**
3763
                 * Set an id to check for.
3764
                 * Check is case sensitive.
3765
                 * \param id ID to check for.
3766
                 * \return *this to allow chaining
3767
                 */
3768
                verifier& with_id(const typename json_traits::string_type& id) { return with_claim("jti", basic_claim_t(id)); }
3769

3770
                /**
3771
                 * Specify a claim to check for using the specified operation.
3772
                 * This is helpful for implementating application specific authentication checks
3773
                 * such as the one seen in partial-claim-verifier.cpp
3774
                 *
3775
                 * \snippet{trimleft} partial-claim-verifier.cpp verifier check custom claim
3776
                 *
3777
                 * \param name Name of the claim to check for
3778
                 * \param fn Function to use for verifying the claim
3779
                 * \return *this to allow chaining
3780
                 */
3781
                verifier& with_claim(const typename json_traits::string_type& name, verify_check_fn_t fn) {
57✔
3782
                        claims[name] = fn;
57✔
3783
                        return *this;
57✔
3784
                }
3785

3786
                /**
3787
                 * Specify a claim to check for equality (both type & value).
3788
                 * See the private-claims.cpp example.
3789
                 *
3790
                 * \snippet{trimleft} private-claims.cpp verify exact claim
3791
                 *
3792
                 * \param name Name of the claim to check for
3793
                 * \param c Claim to check for
3794
                 * \return *this to allow chaining
3795
                 */
3796
                verifier& with_claim(const typename json_traits::string_type& name, basic_claim_t c) {
55✔
3797
                        return with_claim(name, verify_ops::equals_claim<json_traits>{c});
55✔
3798
                }
55✔
3799

3800
                /**
3801
                 * \brief Add an algorithm available for checking.
3802
                 *
3803
                 * This is used to handle incomming tokens for predefined algorithms
3804
                 * which the authorization server is provided. For example a small system
3805
                 * where only a single RSA key-pair is used to sign tokens
3806
                 *
3807
                 * \snippet{trimleft} example/rsa-verify.cpp allow rsa algorithm
3808
                 *
3809
                 * \tparam Algorithm any algorithm such as those provided by jwt::algorithm
3810
                 * \param alg Algorithm to allow
3811
                 * \return *this to allow chaining
3812
                 */
3813
                template<typename Algorithm>
3814
                verifier& allow_algorithm(Algorithm alg) {
83✔
3815
                        algs[alg.name()] = std::make_shared<algo<Algorithm>>(alg);
83✔
3816
                        return *this;
83✔
3817
                }
3818

3819
                /**
3820
                 * Verify the given token.
3821
                 * \param jwt Token to check
3822
                 * \throw token_verification_exception Verification failed
3823
                 */
3824
                void verify(const decoded_jwt<json_traits>& jwt) const {
82✔
3825
                        std::error_code ec;
82✔
3826
                        verify(jwt, ec);
82✔
3827
                        error::throw_if_error(ec);
82✔
3828
                }
48✔
3829
                /**
3830
                 * Verify the given token.
3831
                 * \param jwt Token to check
3832
                 * \param ec error_code filled with details on error
3833
                 */
3834
                void verify(const decoded_jwt<json_traits>& jwt, std::error_code& ec) const {
94✔
3835
                        ec.clear();
94✔
3836
                        const typename json_traits::string_type data = jwt.get_header_base64() + "." + jwt.get_payload_base64();
94✔
3837
                        const typename json_traits::string_type sig = jwt.get_signature();
94✔
3838
                        const std::string algo = jwt.get_algorithm();
94✔
3839
                        if (algs.count(algo) == 0) {
94✔
3840
                                ec = error::token_verification_error::wrong_algorithm;
1✔
3841
                                return;
1✔
3842
                        }
3843
                        algs.at(algo)->verify(data, sig, ec);
93✔
3844
                        if (ec) return;
93✔
3845

3846
                        verify_ops::verify_context<json_traits> ctx{clock.now(), jwt, default_leeway};
75✔
3847
                        for (auto& c : claims) {
299✔
3848
                                ctx.claim_key = c.first;
247✔
3849
                                c.second(ctx, ec);
247✔
3850
                                if (ec) return;
247✔
3851
                        }
3852
                }
201✔
3853
        };
3854

3855
        /**
3856
         * \brief JSON Web Key
3857
         *
3858
         * https://tools.ietf.org/html/rfc7517
3859
         *
3860
         * A JSON object that represents a cryptographic key.  The members of
3861
         * the object represent properties of the key, including its value.
3862
         */
3863
        template<typename json_traits>
3864
        class jwk {
3865
                using basic_claim_t = basic_claim<json_traits>;
3866
                const details::map_of_claims<json_traits> jwk_claims;
3867

3868
        public:
3869
                JWT_CLAIM_EXPLICIT jwk(const typename json_traits::string_type& str)
3✔
3870
                        : jwk_claims(details::map_of_claims<json_traits>::parse_claims(str)) {}
3✔
3871

3872
                JWT_CLAIM_EXPLICIT jwk(const typename json_traits::value_type& json)
7✔
3873
                        : jwk_claims(json_traits::as_object(json)) {}
7✔
3874

3875
                /**
3876
                 * Get key type claim
3877
                 *
3878
                 * This returns the general type (e.g. RSA or EC), not a specific algorithm value.
3879
                 * \return key type as string
3880
                 * \throw std::runtime_error If claim was not present
3881
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3882
                 */
3883
                typename json_traits::string_type get_key_type() const { return get_jwk_claim("kty").as_string(); }
3884

3885
                /**
3886
                 * Get public key usage claim
3887
                 * \return usage parameter as string
3888
                 * \throw std::runtime_error If claim was not present
3889
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3890
                 */
3891
                typename json_traits::string_type get_use() const { return get_jwk_claim("use").as_string(); }
3892

3893
                /**
3894
                 * Get key operation types claim
3895
                 * \return key operation types as a set of strings
3896
                 * \throw std::runtime_error If claim was not present
3897
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3898
                 */
3899
                typename basic_claim_t::set_t get_key_operations() const { return get_jwk_claim("key_ops").as_set(); }
3900

3901
                /**
3902
                 * Get algorithm claim
3903
                 * \return algorithm as string
3904
                 * \throw std::runtime_error If claim was not present
3905
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3906
                 */
3907
                typename json_traits::string_type get_algorithm() const { return get_jwk_claim("alg").as_string(); }
6✔
3908

3909
                /**
3910
                 * Get key id claim
3911
                 * \return key id as string
3912
                 * \throw std::runtime_error If claim was not present
3913
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3914
                 */
3915
                typename json_traits::string_type get_key_id() const { return get_jwk_claim("kid").as_string(); }
51✔
3916

3917
                /**
3918
                 * \brief Get curve claim
3919
                 *
3920
                 * https://www.rfc-editor.org/rfc/rfc7518.html#section-6.2.1.1
3921
                 * https://www.iana.org/assignments/jose/jose.xhtml#table-web-key-elliptic-curve
3922
                 *
3923
                 * \return curve as string
3924
                 * \throw std::runtime_error If claim was not present
3925
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3926
                 */
3927
                typename json_traits::string_type get_curve() const { return get_jwk_claim("crv").as_string(); }
3928

3929
                /**
3930
                 * Get x5c claim
3931
                 * \return x5c as an array
3932
                 * \throw std::runtime_error If claim was not present
3933
                 * \throw std::bad_cast Claim was present but not a array (Should not happen in a valid token)
3934
                 */
3935
                typename json_traits::array_type get_x5c() const { return get_jwk_claim("x5c").as_array(); };
9✔
3936

3937
                /**
3938
                 * Get X509 URL claim
3939
                 * \return x5u as string
3940
                 * \throw std::runtime_error If claim was not present
3941
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3942
                 */
3943
                typename json_traits::string_type get_x5u() const { return get_jwk_claim("x5u").as_string(); };
3944

3945
                /**
3946
                 * Get X509 thumbprint claim
3947
                 * \return x5t as string
3948
                 * \throw std::runtime_error If claim was not present
3949
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3950
                 */
3951
                typename json_traits::string_type get_x5t() const { return get_jwk_claim("x5t").as_string(); };
3952

3953
                /**
3954
                 * Get X509 SHA256 thumbprint claim
3955
                 * \return x5t#S256 as string
3956
                 * \throw std::runtime_error If claim was not present
3957
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3958
                 */
3959
                typename json_traits::string_type get_x5t_sha256() const { return get_jwk_claim("x5t#S256").as_string(); };
3960

3961
                /**
3962
                 * Get x5c claim as a string
3963
                 * \return x5c as an string
3964
                 * \throw std::runtime_error If claim was not present
3965
                 * \throw std::bad_cast Claim was present but not a string (Should not happen in a valid token)
3966
                 */
3967
                typename json_traits::string_type get_x5c_key_value() const {
2✔
3968
                        auto x5c_array = get_jwk_claim("x5c").as_array();
2✔
3969
                        if (x5c_array.size() == 0) throw error::claim_not_present_exception();
2✔
3970

3971
                        return json_traits::as_string(x5c_array.front());
2✔
3972
                };
2✔
3973

3974
                /**
3975
                 * Check if a key type is present ("kty")
3976
                 * \return true if present, false otherwise
3977
                 */
3978
                bool has_key_type() const noexcept { return has_jwk_claim("kty"); }
3979

3980
                /**
3981
                 * Check if a public key usage indication is present ("use")
3982
                 * \return true if present, false otherwise
3983
                 */
3984
                bool has_use() const noexcept { return has_jwk_claim("use"); }
3985

3986
                /**
3987
                 * Check if a key operations parameter is present ("key_ops")
3988
                 * \return true if present, false otherwise
3989
                 */
3990
                bool has_key_operations() const noexcept { return has_jwk_claim("key_ops"); }
3991

3992
                /**
3993
                 * Check if algorithm is present ("alg")
3994
                 * \return true if present, false otherwise
3995
                 */
3996
                bool has_algorithm() const noexcept { return has_jwk_claim("alg"); }
9✔
3997

3998
                /**
3999
                 * Check if curve is present ("crv")
4000
                 * \return true if present, false otherwise
4001
                 */
4002
                bool has_curve() const noexcept { return has_jwk_claim("crv"); }
4003

4004
                /**
4005
                 * Check if key id is present ("kid")
4006
                 * \return true if present, false otherwise
4007
                 */
4008
                bool has_key_id() const noexcept { return has_jwk_claim("kid"); }
45✔
4009

4010
                /**
4011
                 * Check if X509 URL is present ("x5u")
4012
                 * \return true if present, false otherwise
4013
                 */
4014
                bool has_x5u() const noexcept { return has_jwk_claim("x5u"); }
4015

4016
                /**
4017
                 * Check if X509 Chain is present ("x5c")
4018
                 * \return true if present, false otherwise
4019
                 */
4020
                bool has_x5c() const noexcept { return has_jwk_claim("x5c"); }
6✔
4021

4022
                /**
4023
                 * Check if a X509 thumbprint is present ("x5t")
4024
                 * \return true if present, false otherwise
4025
                 */
4026
                bool has_x5t() const noexcept { return has_jwk_claim("x5t"); }
4027

4028
                /**
4029
                 * Check if a X509 SHA256 thumbprint is present ("x5t#S256")
4030
                 * \return true if present, false otherwise
4031
                 */
4032
                bool has_x5t_sha256() const noexcept { return has_jwk_claim("x5t#S256"); }
4033

4034
                /**
4035
                 * Check if a jwk claim is present
4036
                 * \return true if claim was present, false otherwise
4037
                 */
4038
                bool has_jwk_claim(const typename json_traits::string_type& name) const noexcept {
22✔
4039
                        return jwk_claims.has_claim(name);
22✔
4040
                }
4041

4042
                /**
4043
                 * Get jwk claim by name
4044
                 * \return Requested claim
4045
                 * \throw std::runtime_error If claim was not present
4046
                 */
4047
                basic_claim_t get_jwk_claim(const typename json_traits::string_type& name) const {
24✔
4048
                        return jwk_claims.get_claim(name);
24✔
4049
                }
4050

4051
                /**
4052
                * Check if the jwk has any claims
4053
                * \return true is any claim is present
4054
                 */
4055
                bool empty() const noexcept { return jwk_claims.empty(); }
4056

4057
                /**
4058
                 * Get all jwk claims
4059
                 * \return Map of claims
4060
                 */
4061
                typename json_traits::object_type get_claims() const { return this->jwk_claims.claims; }
4062
        };
4063

4064
        /**
4065
         * \brief JWK Set
4066
         *
4067
         * https://tools.ietf.org/html/rfc7517
4068
         *
4069
         * A JSON object that represents a set of JWKs.  The JSON object MUST
4070
         * have a "keys" member, which is an array of JWKs.
4071
         *
4072
         * This container takes a JWKs and simplifies it to a vector of JWKs
4073
         */
4074
        template<typename json_traits>
4075
        class jwks {
4076
        public:
4077
                /// JWK instance template specialization
4078
                using jwks_t = jwk<json_traits>;
4079
                /// Type specialization for the vector of JWK
4080
                using jwks_vector_t = std::vector<jwks_t>;
4081
                using iterator = typename jwks_vector_t::iterator;
4082
                using const_iterator = typename jwks_vector_t::const_iterator;
4083

4084
                /**
4085
                 * Default constructor producing an empty object without any keys
4086
                 */
4087
                jwks() = default;
1✔
4088

4089
                /**
4090
                 * Parses a string buffer to extract the JWKS.
4091
                 * \param str buffer containing JSON object representing a JWKS
4092
                 * \throw error::invalid_json_exception or underlying JSON implation error if the JSON is
4093
                 *        invalid with regards to the JWKS specification
4094
                */
4095
                JWT_CLAIM_EXPLICIT jwks(const typename json_traits::string_type& str) {
3✔
4096
                        typename json_traits::value_type parsed_val;
3✔
4097
                        if (!json_traits::parse(parsed_val, str)) throw error::invalid_json_exception();
3✔
4098

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

4102
                        auto jwk_list = jwks_json.get_claim("keys").as_array();
3✔
4103
                        std::transform(jwk_list.begin(), jwk_list.end(), std::back_inserter(jwk_claims),
3✔
4104
                                                   [](const typename json_traits::value_type& val) { return jwks_t{val}; });
7✔
4105
                }
3✔
4106

4107
                iterator begin() { return jwk_claims.begin(); }
2✔
4108
                iterator end() { return jwk_claims.end(); }
2✔
4109
                const_iterator cbegin() const { return jwk_claims.begin(); }
9✔
4110
                const_iterator cend() const { return jwk_claims.end(); }
9✔
4111
                const_iterator begin() const { return jwk_claims.begin(); }
4112
                const_iterator end() const { return jwk_claims.end(); }
9✔
4113

4114
                /**
4115
                 * Check if a jwk with the kid is present
4116
                 * \return true if jwk was present, false otherwise
4117
                 */
4118
                bool has_jwk(const typename json_traits::string_type& key_id) const noexcept {
4✔
4119
                        return find_by_kid(key_id) != end();
4✔
4120
                }
4121

4122
                /**
4123
                 * Get jwk
4124
                 * \return Requested jwk by key_id
4125
                 * \throw std::runtime_error If jwk was not present
4126
                 */
4127
                jwks_t get_jwk(const typename json_traits::string_type& key_id) const {
5✔
4128
                        const auto maybe = find_by_kid(key_id);
5✔
4129
                        if (maybe == end()) throw error::claim_not_present_exception();
5✔
4130
                        return *maybe;
8✔
4131
                }
4132

4133
        private:
4134
                jwks_vector_t jwk_claims;
4135

4136
                const_iterator find_by_kid(const typename json_traits::string_type& key_id) const noexcept {
9✔
4137
                        return std::find_if(cbegin(), cend(), [key_id](const jwks_t& jwk) {
18✔
4138
                                if (!jwk.has_key_id()) { return false; }
13✔
4139
                                return jwk.get_key_id() == key_id;
13✔
4140
                        });
9✔
4141
                }
4142
        };
4143

4144
        /**
4145
         * Create a verifier using the given clock
4146
         * \param c Clock instance to use
4147
         * \return verifier instance
4148
         */
4149
        template<typename Clock, typename json_traits>
4150
        verifier<Clock, json_traits> verify(Clock c) {
63✔
4151
                return verifier<Clock, json_traits>(c);
63✔
4152
        }
4153

4154
        /**
4155
         * Create a builder using the given clock
4156
         * \param c Clock instance to use
4157
         * \return builder instance
4158
         */
4159
        template<typename Clock, typename json_traits>
4160
        builder<Clock, json_traits> create(Clock c) {
4161
                return builder<Clock, json_traits>(c);
4162
        }
4163

4164
        /**
4165
         * Default clock class using std::chrono::system_clock as a backend.
4166
         */
4167
        struct default_clock {
4168
                /**
4169
                 * Gets the current system time
4170
                 * \return time_point of the host system
4171
                 */
4172
                date now() const { return date::clock::now(); }
71✔
4173
        };
4174

4175
        /**
4176
         * Create a verifier using the default_clock.
4177
         *
4178
         *
4179
         *
4180
         * \param c Clock instance to use
4181
         * \return verifier instance
4182
         */
4183
        template<typename json_traits>
4184
        verifier<default_clock, json_traits> verify(default_clock c = {}) {
24✔
4185
                return verifier<default_clock, json_traits>(c);
24✔
4186
        }
4187

4188
        /**
4189
         * Return a builder instance to create a new token
4190
         */
4191
        template<typename json_traits>
4192
        builder<default_clock, json_traits> create(default_clock c = {}) {
20✔
4193
                return builder<default_clock, json_traits>(c);
20✔
4194
        }
4195

4196
        /**
4197
         * \brief Decode a token. This can be used to to help access important feild like 'x5c'
4198
         * for verifying tokens. See associated example rsa-verify.cpp for more details.
4199
         *
4200
         * \tparam json_traits JSON implementation traits
4201
         * \tparam Decode is callable, taking a string_type and returns a string_type.
4202
         *         It should ensure the padding of the input and then base64url decode and
4203
         *         return the results.
4204
         * \param token Token to decode
4205
         * \param decode function that will pad and base64url decode the token
4206
         * \return Decoded token
4207
         * \throw std::invalid_argument Token is not in correct format
4208
         * \throw std::runtime_error Base64 decoding failed or invalid json
4209
         */
4210
        template<typename json_traits, typename Decode>
4211
        decoded_jwt<json_traits> decode(const typename json_traits::string_type& token, Decode decode) {
4212
                return decoded_jwt<json_traits>(token, decode);
4213
        }
4214

4215
        /**
4216
         * Decode a token. This can be used to to help access important feild like 'x5c'
4217
         * for verifying tokens. See associated example rsa-verify.cpp for more details.
4218
         *
4219
         * \tparam json_traits JSON implementation traits
4220
         * \param token Token to decode
4221
         * \return Decoded token
4222
         * \throw std::invalid_argument Token is not in correct format
4223
         * \throw std::runtime_error Base64 decoding failed or invalid json
4224
         */
4225
        template<typename json_traits>
4226
        decoded_jwt<json_traits> decode(const typename json_traits::string_type& token) {
28✔
4227
                return decoded_jwt<json_traits>(token);
28✔
4228
        }
4229
        /**
4230
         * Parse a single JSON Web Key
4231
         * \tparam json_traits JSON implementation traits
4232
         * \param jwk_ string buffer containing the JSON object
4233
         * \return Decoded jwk
4234
         */
4235
        template<typename json_traits>
4236
        jwk<json_traits> parse_jwk(const typename json_traits::string_type& jwk_) {
4237
                return jwk<json_traits>(jwk_);
4238
        }
4239
        /**
4240
         * Parse a JSON Web Key Set. This can be used to to help access
4241
         * important feild like 'x5c' for verifying tokens. See example
4242
         * jwks-verify.cpp for more information.
4243
         *
4244
         * \tparam json_traits JSON implementation traits
4245
         * \param jwks_ string buffer containing the JSON object
4246
         * \return Parsed JSON object containing the data of the JWK SET string
4247
         * \throw std::runtime_error Token is not in correct format
4248
         */
4249
        template<typename json_traits>
4250
        jwks<json_traits> parse_jwks(const typename json_traits::string_type& jwks_) {
4251
                return jwks<json_traits>(jwks_);
4252
        }
4253
} // namespace jwt
4254

4255
template<typename json_traits>
4256
std::istream& operator>>(std::istream& is, jwt::basic_claim<json_traits>& c) {
8✔
4257
        return c.operator>>(is);
8✔
4258
}
4259

4260
template<typename json_traits>
4261
std::ostream& operator<<(std::ostream& os, const jwt::basic_claim<json_traits>& c) {
4262
        return os << c.to_json();
4263
}
4264

4265
#ifndef JWT_DISABLE_PICOJSON
4266
#include "traits/kazuho-picojson/defaults.h"
4267
#endif
4268

4269
#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