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

prince-chrismc / jwt-cpp / 22088910580

17 Feb 2026 06:55AM UTC coverage: 94.549%. Remained the same
22088910580

Pull #50

github

web-flow
Merge d5942e465 into 971b897d7
Pull Request #50: Fix CMake cache key to use container image fallback

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 >= 0x3070100fL // 3.7.1 - EdDSA support
61
#define JWT_OPENSSL_1_1_1
62
#elif LIBRESSL_VERSION_NUMBER >= 0x3050300fL // 3.5.3
63
#define JWT_OPENSSL_1_1_0
64
#else
65
#define JWT_OPENSSL_1_0_0
66
#endif
67
#endif
68

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

612
                        return write_bio_to_string(certbio, ec);
7✔
613
                }
13✔
614

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

980
                                ec = error::rsa_error::cert_load_failed;
4✔
981
                                return {};
4✔
982
                        }
983

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

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

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

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

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

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

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

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

1105
#if defined(JWT_OPENSSL_3_0)
1106

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

1127
#else
1128

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

1149
#endif
1150

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

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

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

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

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

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

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

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

1219
                                ec = error::ecdsa_error::cert_load_failed;
4✔
1220
                                return {};
4✔
1221
                        }
1222

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

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

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

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

1241
                        EC_GROUP_set_asn1_flag(ecgroup.get(), OPENSSL_EC_NAMED_CURVE);
1242

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

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

1257
#endif
1258

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1852
                                size_t len = EVP_PKEY_size(pkey.get());
4✔
1853
                                std::string res(len, '\0');
4✔
1854

1855
// LibreSSL and OpenSSL, require the oneshot EVP_DigestSign API.
1856
// wolfSSL uses the Update/Final pattern.
1857
#if defined(LIBWOLFSSL_VERSION_HEX)
1858
                                ERR_clear_error();
1859
                                if (EVP_DigestSignUpdate(ctx.get(), reinterpret_cast<const unsigned char*>(data.data()), data.size()) !=
1860
                                        1) {
1861
                                        std::cout << ERR_error_string(ERR_get_error(), NULL) << '\n';
1862
                                        ec = error::signature_generation_error::signupdate_failed;
1863
                                        return {};
1864
                                }
1865
                                if (EVP_DigestSignFinal(ctx.get(), reinterpret_cast<unsigned char*>(&res[0]), &len) != 1) {
1866
                                        ec = error::signature_generation_error::signfinal_failed;
1867
                                        return {};
1868
                                }
1869
#else
1870
                                if (EVP_DigestSign(ctx.get(), reinterpret_cast<unsigned char*>(&res[0]), &len,
8✔
1871
                                                                   reinterpret_cast<const unsigned char*>(data.data()), data.size()) != 1) {
8✔
1872
                                        ec = error::signature_generation_error::signfinal_failed;
1✔
1873
                                        return {};
1✔
1874
                                }
1875
#endif
1876

1877
                                res.resize(len);
3✔
1878
                                return res;
3✔
1879
                        }
6✔
1880

1881
                        /**
1882
                         * Check if signature is valid
1883
                         * \param data The data to check signature against
1884
                         * \param signature Signature provided by the jwt
1885
                         * \param ec Filled with details on error
1886
                         */
1887
                        void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
12✔
1888
                                ec.clear();
12✔
1889
                                auto ctx = helper::make_evp_md_ctx();
12✔
1890
                                if (!ctx) {
12✔
1891
                                        ec = error::signature_verification_error::create_context_failed;
1✔
1892
                                        return;
1✔
1893
                                }
1894
                                if (!EVP_DigestVerifyInit(ctx.get(), nullptr, nullptr, nullptr, pkey.get())) {
11✔
1895
                                        ec = error::signature_verification_error::verifyinit_failed;
1✔
1896
                                        return;
1✔
1897
                                }
1898
// LibreSSL and OpenSSL, require the oneshot EVP_DigestVerify API.
1899
// wolfSSL uses the Update/Final pattern.
1900
#if defined(LIBWOLFSSL_VERSION_HEX)
1901
                                if (EVP_DigestVerifyUpdate(ctx.get(), reinterpret_cast<const unsigned char*>(data.data()),
1902
                                                                                   data.size()) != 1) {
1903
                                        ec = error::signature_verification_error::verifyupdate_failed;
1904
                                        return;
1905
                                }
1906
                                if (EVP_DigestVerifyFinal(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
1907
                                                                                  signature.size()) != 1) {
1908
                                        ec = error::signature_verification_error::verifyfinal_failed;
1909
                                        return;
1910
                                }
1911
#else
1912
                                auto res = EVP_DigestVerify(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
20✔
1913
                                                                                        signature.size(), reinterpret_cast<const unsigned char*>(data.data()),
10✔
1914
                                                                                        data.size());
1915
                                if (res != 1) {
10✔
1916
                                        ec = error::signature_verification_error::verifyfinal_failed;
5✔
1917
                                        return;
5✔
1918
                                }
1919
#endif
1920
                        }
12✔
1921
                        /**
1922
                         * Returns the algorithm name provided to the constructor
1923
                         * \return algorithm's name
1924
                         */
1925
                        std::string name() const { return alg_name; }
10✔
1926

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

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

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

2003
                                return res;
4✔
2004
                        }
8✔
2005

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

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

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

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

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

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

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

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

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

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

2328
                template<typename... Ts>
2329
                using void_t = typename make_void<Ts...>::type;
2330
#endif
2331

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

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

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

2358
                template<template<class...> class Op, class... Args>
2359
                using is_detected = typename detector<nonesuch, void, Op, Args...>::value;
2360
#endif
2361

2362
                template<typename T, typename Signature>
2363
                using is_signature = typename std::is_same<T, Signature>;
2364

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

2372
                template<typename traits_type, typename value_type>
2373
                struct supports_get_type {
2374
                        template<typename T>
2375
                        using get_type_t = decltype(T::get_type);
2376

2377
                        static constexpr auto value =
2378
                                is_function_signature_detected<traits_type, get_type_t, json::type(const value_type&)>::value;
2379

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

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

2399
                JWT_CPP_SUPPORTS_AS(object);
2400
                JWT_CPP_SUPPORTS_AS(array);
2401
                JWT_CPP_SUPPORTS_AS(string);
2402
                JWT_CPP_SUPPORTS_AS(number);
2403
                JWT_CPP_SUPPORTS_AS(integer);
2404
                JWT_CPP_SUPPORTS_AS(boolean);
2405

2406
#undef JWT_CPP_JSON_TYPE_TYPE
2407
#undef JWT_CPP_AS_TYPE_T
2408
#undef JWT_CPP_SUPPORTS_AS
2409

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

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

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

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

2447
#if __cplusplus > 201703L
2448
                template<typename T>
2449
                inline constexpr bool is_iterable_v = is_iterable<T>::value;
2450
#endif
2451

2452
                template<typename object_type, typename string_type>
2453
                using is_count_signature = typename std::is_integral<decltype(std::declval<const object_type>().count(
2454
                        std::declval<const string_type>()))>;
2455

2456
                template<typename object_type, typename string_type, typename = void>
2457
                struct is_subcription_operator_signature : std::false_type {};
2458

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

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

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

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

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

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

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

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

2524
                template<typename string_type>
2525
                using is_std_operate_plus_signature =
2526
                        typename std::is_same<decltype(std::operator+(std::declval<string_type>(), std::declval<string_type>())),
2527
                                                                  string_type>;
2528

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

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

2540
                        static constexpr auto value =
2541
                                std::is_constructible<value_type, string_type>::value && substr && operator_plus;
2542
                };
2543

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

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

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

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

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

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

2611
                typename json_traits::value_type val;
2612

2613
        public:
2614
                /**
2615
                 * Order list of strings
2616
                 */
2617
                using set_t = std::set<typename json_traits::string_type>;
2618

2619
                basic_claim() = default;
16✔
2620
                basic_claim(const basic_claim&) = default;
234✔
2621
                basic_claim(basic_claim&&) = default;
46✔
2622
                basic_claim& operator=(const basic_claim&) = default;
2623
                basic_claim& operator=(basic_claim&&) = default;
2624
                ~basic_claim() = default;
644✔
2625

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2748
                        map_of_claims() = default;
174✔
2749
                        map_of_claims(const map_of_claims&) = default;
22✔
2750
                        map_of_claims(map_of_claims&&) = default;
2751
                        map_of_claims& operator=(const map_of_claims&) = default;
2752
                        map_of_claims& operator=(map_of_claims&&) = default;
166✔
2753

2754
                        map_of_claims(typename json_traits::object_type json) : claims(std::move(json)) {}
176✔
2755

2756
                        iterator begin() { return claims.begin(); }
2757
                        iterator end() { return claims.end(); }
2758
                        const_iterator cbegin() const { return claims.begin(); }
2759
                        const_iterator cend() const { return claims.end(); }
2760
                        const_iterator begin() const { return claims.begin(); }
2761
                        const_iterator end() const { return claims.end(); }
2762

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

2775
                                return json_traits::as_object(val);
333✔
2776
                        };
170✔
2777

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

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

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

2809
        public:
2810
                using basic_claim_t = basic_claim<json_traits>;
2811

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

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

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

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

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

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

3053
                        header = decode(header_base64);
84✔
3054
                        payload = decode(payload_base64);
83✔
3055
                        signature = decode(signature_base64);
83✔
3056

3057
                        this->header_claims = details::map_of_claims<json_traits>::parse_claims(header);
83✔
3058
                        this->payload_claims = details::map_of_claims<json_traits>::parse_claims(payload);
82✔
3059
                }
127✔
3060

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

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

3137
                /// Instance of clock type
3138
                Clock clock;
3139

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

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

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

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

3349
                        const auto header = encode(json_traits::serialize(typename json_traits::value_type(obj_header)));
53✔
3350
                        const auto payload = encode(json_traits::serialize(typename json_traits::value_type(payload_claims)));
53✔
3351
                        const auto token = header + "." + payload;
53✔
3352

3353
                        auto signature = algo.sign(token, ec);
53✔
3354
                        if (ec) return {};
53✔
3355

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

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

3395
                        /// The claim key to apply this comparison on
3396
                        typename json_traits::string_type claim_key{};
3397

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

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

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

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

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

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

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

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

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

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

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

3594
                                return out;
10✔
3595
                        }
5✔
3596
                };
3597
        } // namespace verify_ops
3598

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

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

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

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

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

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

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

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

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

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

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

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

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

3871
        public:
3872
                JWT_CLAIM_EXPLICIT jwk(const typename json_traits::string_type& str)
3✔
3873
                        : jwk_claims(details::map_of_claims<json_traits>::parse_claims(str)) {}
3✔
3874

3875
                JWT_CLAIM_EXPLICIT jwk(const typename json_traits::value_type& json)
7✔
3876
                        : jwk_claims(json_traits::as_object(json)) {}
7✔
3877

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

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

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

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

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

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

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

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

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

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

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

3974
                        return json_traits::as_string(x5c_array.front());
2✔
3975
                };
2✔
3976

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4087
                /**
4088
                 * Default constructor producing an empty object without any keys
4089
                 */
4090
                jwks() = default;
1✔
4091

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

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

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

4110
                iterator begin() { return jwk_claims.begin(); }
2✔
4111
                iterator end() { return jwk_claims.end(); }
2✔
4112
                const_iterator cbegin() const { return jwk_claims.begin(); }
9✔
4113
                const_iterator cend() const { return jwk_claims.end(); }
9✔
4114
                const_iterator begin() const { return jwk_claims.begin(); }
4115
                const_iterator end() const { return jwk_claims.end(); }
9✔
4116

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

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

4136
        private:
4137
                jwks_vector_t jwk_claims;
4138

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

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

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

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

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

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

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

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

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

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

4268
#ifndef JWT_DISABLE_PICOJSON
4269
#include "traits/kazuho-picojson/defaults.h"
4270
#endif
4271

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