From 99d041deb9461c340a3f5351237168405a830cfe Mon Sep 17 00:00:00 2001 From: Arun M Date: Fri, 18 May 2018 20:26:06 +0530 Subject: [PATCH 01/79] Some tests don't pass #14 --- include/jwt/impl/jwt.ipp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index b2de1cd..87a8035 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -425,10 +425,10 @@ std::error_code jwt_object::verify( { if (has_claim(registered_claims::issuer)) { - jwt::string_view p_issuer = payload() - .get_claim_value(registered_claims::issuer); + const std::string& p_issuer = payload() + .get_claim_value(registered_claims::issuer); - if (p_issuer.data() != dparams.issuer) { + if (p_issuer != dparams.issuer) { ec = VerificationErrc::InvalidIssuer; return ec; } @@ -443,10 +443,10 @@ std::error_code jwt_object::verify( { if (has_claim(registered_claims::audience)) { - jwt::string_view p_aud = payload() - .get_claim_value(registered_claims::audience); + const std::string& p_aud = payload() + .get_claim_value(registered_claims::audience); - if (p_aud.data() != dparams.aud) { + if (p_aud != dparams.aud) { ec = VerificationErrc::InvalidAudience; return ec; } @@ -461,9 +461,9 @@ std::error_code jwt_object::verify( { if (has_claim(registered_claims::subject)) { - jwt::string_view p_sub = payload() - .get_claim_value(registered_claims::subject); - if (p_sub.data() != dparams.sub) { + const std::string& p_sub = payload() + .get_claim_value(registered_claims::subject); + if (p_sub != dparams.sub) { ec = VerificationErrc::InvalidSubject; return ec; } From 55c36d4c301309841d59760cdfd8e6b4d16f00d7 Mon Sep 17 00:00:00 2001 From: Arun M Date: Sat, 19 May 2018 18:43:28 +0530 Subject: [PATCH 02/79] Enable compiler warnings --- CMakeLists.txt | 2 +- tests/test_jwt_encode.cc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ab398cc..390fa77 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ cmake_minimum_required (VERSION 2.8.11) project (cpp-jwt) #SET (CMAKE_CXX_COMPILER /usr/local/bin/g++) -SET( CMAKE_CXX_FLAGS "-std=c++14" ) +SET( CMAKE_CXX_FLAGS "-std=c++14 -Wall" ) include_directories (include) diff --git a/tests/test_jwt_encode.cc b/tests/test_jwt_encode.cc index 0580b2c..ccb7584 100644 --- a/tests/test_jwt_encode.cc +++ b/tests/test_jwt_encode.cc @@ -278,7 +278,7 @@ TEST (EncodeTest, HeaderParamTest) bool ret = obj.header().add_header("kid", 1234567); EXPECT_TRUE (ret); - ret = obj.header().add_header("crit", std::array{"exp"}); + ret = obj.header().add_header("crit", std::array{ {"exp"} }); EXPECT_TRUE (ret); std::cout << obj.header() << std::endl; From e5fc25bbe874d6b6ea871060b3d4e533d9a75e34 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Sat, 19 May 2018 16:29:12 +0200 Subject: [PATCH 03/79] Fixed a few warnings about signed and unsigned comparison. --- include/jwt/base64.hpp | 2 +- include/jwt/impl/algorithm.ipp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/jwt/base64.hpp b/include/jwt/base64.hpp index 2f2a646..fcf99d6 100644 --- a/include/jwt/base64.hpp +++ b/include/jwt/base64.hpp @@ -94,7 +94,7 @@ std::string base64_encode(const char* in, size_t len) int i = 0; int j = 0; - for (; i < len - 2; i += 3) { + for (; i < static_cast(len) - 2; i += 3) { const auto first = in[i]; const auto second = in[i+1]; const auto third = in[i+2]; diff --git a/include/jwt/impl/algorithm.ipp b/include/jwt/impl/algorithm.ipp index c9fe51a..55d6591 100644 --- a/include/jwt/impl/algorithm.ipp +++ b/include/jwt/impl/algorithm.ipp @@ -306,9 +306,9 @@ std::string PEMSign::public_key_ser( ECDSA_SIG_get0(ec_sig.get(), &ec_sig_r, &ec_sig_s); - auto r_len = BN_num_bytes(ec_sig_r); - auto s_len = BN_num_bytes(ec_sig_s); - auto bn_len = (degree + 7) / 8; + int r_len = BN_num_bytes(ec_sig_r); + int s_len = BN_num_bytes(ec_sig_s); + int bn_len = static_cast((degree + 7) / 8); if ((r_len > bn_len) || (s_len > bn_len)) { ec = AlgorithmErrc::SigningErr; From 1fcfbaac75ffac03d39144d7e503150c1f049846 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Sat, 19 May 2018 19:03:46 +0200 Subject: [PATCH 04/79] Fix more signed/unsigned warnings. --- include/jwt/impl/jwt.ipp | 4 ++-- tests/test_jwt_decode.cc | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 87a8035..caec865 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -414,7 +414,7 @@ std::error_code jwt_object::verify( auto p_exp = payload() .get_claim_value(registered_claims::expiration); - if (curr_time > (p_exp + dparams.leeway)) { + if (static_cast(curr_time) > static_cast(p_exp + dparams.leeway)) { ec = VerificationErrc::TokenExpired; return ec; } @@ -483,7 +483,7 @@ std::error_code jwt_object::verify( auto p_exp = payload() .get_claim_value(registered_claims::not_before); - if ((p_exp - dparams.leeway) > curr_time) { + if (static_cast(p_exp - dparams.leeway) > static_cast(curr_time)) { ec = VerificationErrc::ImmatureSignature; return ec; } diff --git a/tests/test_jwt_decode.cc b/tests/test_jwt_decode.cc index 4933665..4d8e4cb 100644 --- a/tests/test_jwt_decode.cc +++ b/tests/test_jwt_decode.cc @@ -34,7 +34,7 @@ TEST (DecodeTest, DecodeNoneAlgSign) EXPECT_TRUE (obj.has_claim("aud")); EXPECT_TRUE (obj.has_claim("exp")); - EXPECT_EQ (obj.payload().get_claim_value("exp"), 1513863371); + EXPECT_EQ (obj.payload().get_claim_value("exp"), static_cast(1513863371)); } TEST (DecodeTest, DecodeWrongAlgo) From 8ef6d055ae66f0045ed90f4bfa459c6d6d0e8e0e Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Sat, 19 May 2018 21:38:25 +0200 Subject: [PATCH 05/79] Make it possible to only include base64.hpp without having to include jwt.hpp by adding missing includes to resolve incomplete types. --- include/jwt/base64.hpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/include/jwt/base64.hpp b/include/jwt/base64.hpp index fcf99d6..7fa067f 100644 --- a/include/jwt/base64.hpp +++ b/include/jwt/base64.hpp @@ -25,6 +25,8 @@ SOFTWARE. #include #include +#include +#include #include "jwt/string_view.hpp" namespace jwt { From 22856e9da26e948fa836c1b7142a686fd31c713a Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Sun, 20 May 2018 00:47:37 +0200 Subject: [PATCH 06/79] Functions made inline because they're in the header. Otherwise multiple definition errors will appear when this file is included. --- include/jwt/base64.hpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/jwt/base64.hpp b/include/jwt/base64.hpp index 7fa067f..8965cb3 100644 --- a/include/jwt/base64.hpp +++ b/include/jwt/base64.hpp @@ -86,7 +86,7 @@ class EMap * @in : Input byte string to be encoded. * @len : Length of the input byte string. */ -std::string base64_encode(const char* in, size_t len) +inline std::string base64_encode(const char* in, size_t len) { std::string result; const auto encoded_siz = encoding_size(len); @@ -189,7 +189,7 @@ class DMap * @in : Encoded base64 byte string. * @len : Length of the encoded input byte string. */ -std::string base64_decode(const char* in, size_t len) +inline std::string base64_decode(const char* in, size_t len) { std::string result; const auto decoded_siz = decoding_size(len); @@ -266,7 +266,7 @@ std::string base64_decode(const char* in, size_t len) * Returns: * Length of the URL safe base64 encoded byte string. */ -size_t base64_uri_encode(char* data, size_t len) noexcept +inline size_t base64_uri_encode(char* data, size_t len) noexcept { size_t i = 0; size_t j = 0; @@ -299,7 +299,7 @@ size_t base64_uri_encode(char* data, size_t len) noexcept * @data : URL safe base64 encoded byte string. * @len : Length of the input byte string. */ -std::string base64_uri_decode(const char* data, size_t len) +inline std::string base64_uri_decode(const char* data, size_t len) { std::string uri_dec; uri_dec.resize(len + 4); From a9562500a0e373cf3223f200821b6fb68e883c86 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Sun, 20 May 2018 02:57:13 +0200 Subject: [PATCH 07/79] More inline definitions to for header files to avoid double definition problems. --- include/jwt/algorithm.hpp | 4 ++-- include/jwt/impl/error_codes.ipp | 6 +++--- include/jwt/impl/jwt.ipp | 28 ++++++++++++++-------------- include/jwt/jwt.hpp | 6 +++--- include/jwt/parameters.hpp | 30 +++++++++++++++--------------- 5 files changed, 37 insertions(+), 37 deletions(-) diff --git a/include/jwt/algorithm.hpp b/include/jwt/algorithm.hpp index e117760..e778a6a 100644 --- a/include/jwt/algorithm.hpp +++ b/include/jwt/algorithm.hpp @@ -219,7 +219,7 @@ enum class algorithm * Convert the algorithm enum class type to * its stringified form. */ -jwt::string_view alg_to_str(enum algorithm alg) noexcept +inline jwt::string_view alg_to_str(enum algorithm alg) noexcept { switch (alg) { case algorithm::HS256: return "HS256"; @@ -243,7 +243,7 @@ jwt::string_view alg_to_str(enum algorithm alg) noexcept * Convert stringified algorithm to enum class. * The string comparison is case insesitive. */ -enum algorithm str_to_alg(const jwt::string_view alg) noexcept +inline enum algorithm str_to_alg(const jwt::string_view alg) noexcept { if (!alg.length()) return algorithm::NONE; diff --git a/include/jwt/impl/error_codes.ipp b/include/jwt/impl/error_codes.ipp index 8aebeba..c4f6b43 100644 --- a/include/jwt/impl/error_codes.ipp +++ b/include/jwt/impl/error_codes.ipp @@ -141,17 +141,17 @@ const VerificationErrorCategory theVerificationErrorCategory {}; // Create the AlgorithmErrc error code -std::error_code make_error_code(AlgorithmErrc err) +inline std::error_code make_error_code(AlgorithmErrc err) { return { static_cast(err), theAlgorithmErrCategory }; } -std::error_code make_error_code(DecodeErrc err) +inline std::error_code make_error_code(DecodeErrc err) { return { static_cast(err), theDecodeErrorCategory }; } -std::error_code make_error_code(VerificationErrc err) +inline std::error_code make_error_code(VerificationErrc err) { return { static_cast(err), theVerificationErrorCategory }; } diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index caec865..9ce3ef8 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -61,7 +61,7 @@ std::ostream& operator<< (std::ostream& os, const T& obj) //======================================================================== -void jwt_header::decode(const jwt::string_view enc_str, std::error_code& ec) +inline void jwt_header::decode(const jwt::string_view enc_str, std::error_code& ec) { ec.clear(); std::string json_str = base64_decode(enc_str); @@ -114,7 +114,7 @@ void jwt_header::decode(const jwt::string_view enc_str, std::error_code& ec) return; } -void jwt_header::decode(const jwt::string_view enc_str) +inline void jwt_header::decode(const jwt::string_view enc_str) { std::error_code ec; decode(enc_str, ec); @@ -124,7 +124,7 @@ void jwt_header::decode(const jwt::string_view enc_str) return; } -void jwt_payload::decode(const jwt::string_view enc_str, std::error_code& ec) +inline void jwt_payload::decode(const jwt::string_view enc_str, std::error_code& ec) { ec.clear(); std::string json_str = base64_decode(enc_str); @@ -146,7 +146,7 @@ void jwt_payload::decode(const jwt::string_view enc_str, std::error_code& ec) return; } -void jwt_payload::decode(const jwt::string_view enc_str) +inline void jwt_payload::decode(const jwt::string_view enc_str) { std::error_code ec; decode(enc_str, ec); @@ -156,7 +156,7 @@ void jwt_payload::decode(const jwt::string_view enc_str) return; } -std::string jwt_signature::encode(const jwt_header& header, +inline std::string jwt_signature::encode(const jwt_header& header, const jwt_payload& payload, std::error_code& ec) { @@ -191,7 +191,7 @@ std::string jwt_signature::encode(const jwt_header& header, return jwt_msg; } -verify_result_t jwt_signature::verify(const jwt_header& header, +inline verify_result_t jwt_signature::verify(const jwt_header& header, const jwt::string_view hdr_pld_sign, const jwt::string_view jwt_sign) { @@ -200,7 +200,7 @@ verify_result_t jwt_signature::verify(const jwt_header& header, } -sign_func_t +inline sign_func_t jwt_signature::get_sign_algorithm_impl(const jwt_header& hdr) const noexcept { sign_func_t ret = nullptr; @@ -245,7 +245,7 @@ jwt_signature::get_sign_algorithm_impl(const jwt_header& hdr) const noexcept -verify_func_t +inline verify_func_t jwt_signature::get_verify_algorithm_impl(const jwt_header& hdr) const noexcept { verify_func_t ret = nullptr; @@ -337,13 +337,13 @@ void jwt_object::set_parameters( set_parameters(std::forward(rargs)...); } -void jwt_object::set_parameters() +inline void jwt_object::set_parameters() { //sentinel call return; } -jwt_object& jwt_object::add_claim(const jwt::string_view name, system_time_t tp) +inline jwt_object& jwt_object::add_claim(const jwt::string_view name, system_time_t tp) { return add_claim( name, @@ -352,13 +352,13 @@ jwt_object& jwt_object::add_claim(const jwt::string_view name, system_time_t tp) ); } -jwt_object& jwt_object::remove_claim(const jwt::string_view name) +inline jwt_object& jwt_object::remove_claim(const jwt::string_view name) { payload_.remove_claim(name); return *this; } -std::string jwt_object::signature(std::error_code& ec) const +inline std::string jwt_object::signature(std::error_code& ec) const { ec.clear(); @@ -374,7 +374,7 @@ std::string jwt_object::signature(std::error_code& ec) const return jws.encode(header_, payload_, ec); } -std::string jwt_object::signature() const +inline std::string jwt_object::signature() const { std::error_code ec; std::string res = signature(ec); @@ -514,7 +514,7 @@ std::error_code jwt_object::verify( } -std::array +inline std::array jwt_object::three_parts(const jwt::string_view enc_str) { std::array result; diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index d627c0f..de540b5 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -58,7 +58,7 @@ enum class type * Converts a string representing a value of type * `enum class type` into its actual type. */ -enum type str_to_type(const jwt::string_view typ) noexcept +inline enum type str_to_type(const jwt::string_view typ) noexcept { assert (typ.length() && "Empty type string"); @@ -72,7 +72,7 @@ enum type str_to_type(const jwt::string_view typ) noexcept * Converts an instance of type `enum class type` * to its string equivalent. */ -jwt::string_view type_to_str(enum type typ) +inline jwt::string_view type_to_str(enum type typ) { switch (typ) { case type::JWT: return "JWT"; @@ -109,7 +109,7 @@ enum class registered_claims * Converts an instance of type `enum class registered_claims` * to its string equivalent representation. */ -jwt::string_view reg_claims_to_str(enum registered_claims claim) noexcept +inline jwt::string_view reg_claims_to_str(enum registered_claims claim) noexcept { switch (claim) { case registered_claims::expiration: return "exp"; diff --git a/include/jwt/parameters.hpp b/include/jwt/parameters.hpp index 3e4c4d3..b444e6e 100644 --- a/include/jwt/parameters.hpp +++ b/include/jwt/parameters.hpp @@ -265,7 +265,7 @@ using param_seq_list_t = std::initializer_list; /** */ -detail::payload_param> +inline detail::payload_param> payload(const param_init_list_t& kvs) { std::unordered_map m; @@ -292,28 +292,28 @@ payload(MappingConcept&& mc) /** */ -detail::secret_param secret(const string_view sv) +inline detail::secret_param secret(const string_view sv) { return { sv }; } /** */ -detail::algorithm_param algorithm(const string_view sv) +inline detail::algorithm_param algorithm(const string_view sv) { return { sv }; } /** */ -detail::algorithm_param algorithm(jwt::algorithm alg) +inline detail::algorithm_param algorithm(jwt::algorithm alg) { return { alg }; } /** */ -detail::headers_param> +inline detail::headers_param> headers(const param_init_list_t& kvs) { std::map m; @@ -339,7 +339,7 @@ headers(MappingConcept&& mc) /** */ -detail::verify_param +inline detail::verify_param verify(bool v) { return { v }; @@ -347,7 +347,7 @@ verify(bool v) /** */ -detail::leeway_param +inline detail::leeway_param leeway(uint32_t l) { return { l }; @@ -355,7 +355,7 @@ leeway(uint32_t l) /** */ -detail::algorithms_param> +inline detail::algorithms_param> algorithms(const param_seq_list_t& seq) { std::vector vec; @@ -375,7 +375,7 @@ algorithms(SequenceConcept&& sc) /** */ -detail::audience_param +inline detail::audience_param aud(const jwt::string_view aud) { return { aud.data() }; @@ -383,7 +383,7 @@ aud(const jwt::string_view aud) /** */ -detail::issuer_param +inline detail::issuer_param issuer(const jwt::string_view iss) { return { iss.data() }; @@ -391,7 +391,7 @@ issuer(const jwt::string_view iss) /** */ -detail::subject_param +inline detail::subject_param sub(const jwt::string_view subj) { return { subj.data() }; @@ -399,7 +399,7 @@ sub(const jwt::string_view subj) /** */ -detail::validate_iat_param +inline detail::validate_iat_param validate_iat(bool v) { return { v }; @@ -407,7 +407,7 @@ validate_iat(bool v) /** */ -detail::validate_jti_param +inline detail::validate_jti_param validate_jti(bool v) { return { v }; @@ -415,7 +415,7 @@ validate_jti(bool v) /** */ -detail::nbf_param +inline detail::nbf_param nbf(const system_time_t tp) { return { tp }; @@ -423,7 +423,7 @@ nbf(const system_time_t tp) /** */ -detail::nbf_param +inline detail::nbf_param nbf(const uint64_t epoch) { return { epoch }; From 34fdb34b44be980349043509d3594716a8bce139 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Mon, 21 May 2018 14:06:48 +0200 Subject: [PATCH 08/79] Minor to make the code compile with -pedantic-errors flag in g++ --- include/jwt/algorithm.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/jwt/algorithm.hpp b/include/jwt/algorithm.hpp index e778a6a..8aa528e 100644 --- a/include/jwt/algorithm.hpp +++ b/include/jwt/algorithm.hpp @@ -294,7 +294,7 @@ inline void ec_sig_deletor(ECDSA_SIG* ptr) inline void ev_pkey_deletor(EVP_PKEY* ptr) { if (ptr) EVP_PKEY_free(ptr); -}; +} /// Useful typedefs using bio_deletor_t = decltype(&bio_deletor); From 077e6f3f07ec113d2ae24384d1b10870c059d04d Mon Sep 17 00:00:00 2001 From: Arun M Date: Tue, 22 May 2018 18:07:19 +0530 Subject: [PATCH 09/79] ES256/384 signature verification fails #20 --- tests/test_jwt_es.cc | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/test_jwt_es.cc b/tests/test_jwt_es.cc index 3390d84..9064d2d 100644 --- a/tests/test_jwt_es.cc +++ b/tests/test_jwt_es.cc @@ -112,6 +112,32 @@ TEST (ESAlgo, ES512EncodingDecodingTest) EXPECT_EQ (dec_obj.header().algo(), jwt::algorithm::ES512); } +TEST (ESAlgo, ES384EncodingDecodingValidTest) +{ + using namespace jwt::params; + + std::string key = read_from_file(EC384_PRIV_KEY); + ASSERT_TRUE (key.length()); + + jwt::jwt_object obj{algorithm("ES384"), secret(key)}; + + obj.add_claim("iss", "arun.muralidharan") + .add_claim("aud", "all") + .add_claim("exp", 4682665886) // Expires on Sunday, May 22, 2118 12:31:26 PM GMT + ; + + auto enc_str = obj.signature(); + + key = read_from_file(EC384_PUB_KEY); + ASSERT_TRUE (key.length()); + + auto dec_obj = jwt::decode(enc_str, algorithms({"es384"}), verify(true), secret(key)); + + EXPECT_EQ (dec_obj.header().algo(), jwt::algorithm::ES384); + EXPECT_TRUE (dec_obj.has_claim("exp")); + EXPECT_TRUE (obj.payload().has_claim_with_value("exp", 4682665886)); +} + int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); From 00343347b289c023912ece7132e3859d9d689b91 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Wed, 30 May 2018 22:44:38 +0200 Subject: [PATCH 10/79] Fixed many warnings that appear due to assert not being executed in release mode. --- examples/simple_ex2.cc | 6 ++---- include/jwt/algorithm.hpp | 6 +++++- include/jwt/impl/error_codes.ipp | 6 +++--- include/jwt/jwt.hpp | 4 +++- 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/examples/simple_ex2.cc b/examples/simple_ex2.cc index bdc70d1..3804904 100644 --- a/examples/simple_ex2.cc +++ b/examples/simple_ex2.cc @@ -37,12 +37,10 @@ int main() { //Using `add_claim` with extra features. //Check return status and overwrite - bool ret = obj.payload().add_claim("sub", "new test", false/*overwrite*/); - assert (not ret); + assert (not obj.payload().add_claim("sub", "new test", false/*overwrite*/)); // Overwrite an existing claim - ret = obj.payload().add_claim("sub", "new test", true/*overwrite*/); - assert ( ret ); + assert (obj.payload().add_claim("sub", "new test", true/*overwrite*/)); assert (obj.payload().has_claim_with_value("sub", "new test")); diff --git a/include/jwt/algorithm.hpp b/include/jwt/algorithm.hpp index 8aa528e..b013a39 100644 --- a/include/jwt/algorithm.hpp +++ b/include/jwt/algorithm.hpp @@ -211,6 +211,7 @@ enum class algorithm ES256, ES384, ES512, + UNKN, TERM, }; @@ -233,9 +234,10 @@ inline jwt::string_view alg_to_str(enum algorithm alg) noexcept case algorithm::ES512: return "ES512"; case algorithm::TERM: return "TERM"; case algorithm::NONE: return "NONE"; + case algorithm::UNKN: return "UNKN"; default: assert (0 && "Unknown Algorithm"); }; - + return "UNKN"; assert (0 && "Code not reached"); } @@ -258,6 +260,8 @@ inline enum algorithm str_to_alg(const jwt::string_view alg) noexcept if (!strcasecmp(alg.data(), "es384")) return algorithm::ES384; if (!strcasecmp(alg.data(), "es512")) return algorithm::ES512; + return algorithm::UNKN; + assert (0 && "Code not reached"); } diff --git a/include/jwt/impl/error_codes.ipp b/include/jwt/impl/error_codes.ipp index c4f6b43..4118d32 100644 --- a/include/jwt/impl/error_codes.ipp +++ b/include/jwt/impl/error_codes.ipp @@ -49,7 +49,7 @@ struct AlgorithmErrCategory: std::error_category case AlgorithmErrc::NoneAlgorithmUsed: return "none algorithm used"; }; - + return "unknown algorithm error"; assert (0 && "Code not reached"); } }; @@ -86,7 +86,7 @@ struct DecodeErrorCategory: std::error_category case DecodeErrc::KeyNotRequiredForNoneAlg: return "key not required for NONE algorithm"; }; - + return "unknown decode error"; assert (0 && "Code not reached"); } }; @@ -125,7 +125,7 @@ struct VerificationErrorCategory: std::error_category case VerificationErrc::TypeConversionError: return "type conversion error"; }; - + return "unknown verification error"; assert (0 && "Code not reached"); } }; diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index de540b5..1eb28a4 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -64,6 +64,8 @@ inline enum type str_to_type(const jwt::string_view typ) noexcept if (!strcasecmp(typ.data(), "jwt")) return type::JWT; + throw std::runtime_error("Unknown token type"); + assert (0 && "Code not reached"); } @@ -121,7 +123,7 @@ inline jwt::string_view reg_claims_to_str(enum registered_claims claim) noexcept case registered_claims::jti: return "jti"; default: assert (0 && "Not a registered claim"); }; - + return ""; assert (0 && "Code not reached"); } From bef9e9d55308d406e0ae51bfa5e84d477d662b6a Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Thu, 31 May 2018 01:49:47 +0200 Subject: [PATCH 11/79] Fix a major error in error_code category checking implementations. Errors some times don't throw exceptions due to implementation differences. --- include/jwt/impl/jwt.ipp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 9ce3ef8..ee1a1de 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -761,7 +761,8 @@ void jwt_throw_exception(const std::error_code& ec) { const auto& cat = ec.category(); - if (&cat == &theVerificationErrorCategory) + if (&cat == &theVerificationErrorCategory || + std::string(cat.name()) == std::string(theVerificationErrorCategory.name())) { switch (static_cast(ec.value())) { @@ -810,7 +811,8 @@ void jwt_throw_exception(const std::error_code& ec) }; } - if (&cat == &theDecodeErrorCategory) + if (&cat == &theDecodeErrorCategory || + std::string(cat.name()) == std::string(theDecodeErrorCategory.name())) { switch (static_cast(ec.value())) { @@ -836,7 +838,8 @@ void jwt_throw_exception(const std::error_code& ec) assert (0 && "Unknown error code"); } - if (&cat == &theAlgorithmErrCategory) + if (&cat == &theAlgorithmErrCategory || + std::string(cat.name()) == std::string(theAlgorithmErrCategory.name())) { switch (static_cast(ec.value())) { From 87dcef903f48a8c33df0bd9658d775d6d5db1918 Mon Sep 17 00:00:00 2001 From: Arun M Date: Thu, 31 May 2018 20:36:07 +0530 Subject: [PATCH 12/79] Why does the existence of a signature algorithm entail a required verification? #24 --- include/jwt/impl/jwt.ipp | 48 +++++++++---------- tests/test_jwt_decode.cc | 8 ++-- .../test_jwt_decode_verifiy_with_exception.cc | 2 +- tests/test_jwt_encode.cc | 2 +- 4 files changed, 30 insertions(+), 30 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index ee1a1de..f1b9ec7 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -703,34 +703,34 @@ jwt_object decode(const jwt::string_view enc_str, } if (ec) return obj; - } - //Verify the signature only if some algorithm was used - if (obj.header().algo() != algorithm::NONE) - { - if (!dparams.has_secret) { - ec = DecodeErrc::KeyNotPresent; - return obj; - } - jwt_signature jsign{dparams.secret}; + //Verify the signature only if some algorithm was used + if (obj.header().algo() != algorithm::NONE) + { + if (!dparams.has_secret) { + ec = DecodeErrc::KeyNotPresent; + return obj; + } + jwt_signature jsign{dparams.secret}; - // Length of the encoded header and payload only. - // Addition of '1' to account for the '.' character. - auto l = parts[0].length() + 1 + parts[1].length(); - - //MemoryAllocationError is not caught - verify_result_t res = jsign.verify(obj.header(), enc_str.substr(0, l), parts[2]); - if (res.second) { - ec = res.second; - return obj; - } + // Length of the encoded header and payload only. + // Addition of '1' to account for the '.' character. + auto l = parts[0].length() + 1 + parts[1].length(); + + //MemoryAllocationError is not caught + verify_result_t res = jsign.verify(obj.header(), enc_str.substr(0, l), parts[2]); + if (res.second) { + ec = res.second; + return obj; + } - if (!res.first) { - ec = VerificationErrc::InvalidSignature; - return obj; + if (!res.first) { + ec = VerificationErrc::InvalidSignature; + return obj; + } + } else { + ec = AlgorithmErrc::NoneAlgorithmUsed; } - } else { - ec = AlgorithmErrc::NoneAlgorithmUsed; } return obj; diff --git a/tests/test_jwt_decode.cc b/tests/test_jwt_decode.cc index 4d8e4cb..b84e9e9 100644 --- a/tests/test_jwt_decode.cc +++ b/tests/test_jwt_decode.cc @@ -19,10 +19,10 @@ TEST (DecodeTest, DecodeNoneAlgSign) { using namespace jwt::params; const char* enc_str = - "eyJhbGciOiJOT05FIiwidHlwIjoiSldUIn0.eyJhdWQiOiJyaWZ0LmlvIiwiZXhwIjoxNTEzODYzMzcxLCJzdWIiOiJub3RoaW5nIG11Y2gifQ."; + "eyJhbGciOiJOT05FIiwidHlwIjoiSldUIn0.eyJhdWQiOiJyaWZ0LmlvIiwiZXhwIjo0NTEzODYzMzcxLCJzdWIiOiJub3RoaW5nIG11Y2gifQ."; std::error_code ec; - auto obj = jwt::decode(enc_str, algorithms({"none"}), ec, verify(false)); + auto obj = jwt::decode(enc_str, algorithms({"none"}), ec, verify(true)); EXPECT_TRUE (ec); EXPECT_EQ (ec.value(), static_cast(jwt::AlgorithmErrc::NoneAlgorithmUsed)); @@ -34,7 +34,7 @@ TEST (DecodeTest, DecodeNoneAlgSign) EXPECT_TRUE (obj.has_claim("aud")); EXPECT_TRUE (obj.has_claim("exp")); - EXPECT_EQ (obj.payload().get_claim_value("exp"), static_cast(1513863371)); + EXPECT_EQ (obj.payload().get_claim_value("exp"), static_cast(4513863371)); } TEST (DecodeTest, DecodeWrongAlgo) @@ -111,7 +111,7 @@ TEST (DecodeTest, SecretKeyNotPassed) "jk7bRQKTLvs1RcuvMc2B_rt6WBYPoVPirYi_QRBPiuk"; std::error_code ec; - auto obj = jwt::decode(enc_str, algorithms({"none", "hs256"}), ec, verify(false)); + auto obj = jwt::decode(enc_str, algorithms({"none", "hs256"}), ec, verify(true)); ASSERT_TRUE (ec); EXPECT_EQ (ec.value(), static_cast(jwt::DecodeErrc::KeyNotPresent)); diff --git a/tests/test_jwt_decode_verifiy_with_exception.cc b/tests/test_jwt_decode_verifiy_with_exception.cc index ec0ce9a..5c52a76 100644 --- a/tests/test_jwt_decode_verifiy_with_exception.cc +++ b/tests/test_jwt_decode_verifiy_with_exception.cc @@ -160,7 +160,7 @@ TEST (DecodeVerifyExp, KeyNotPresentTest) "eyJpYXQiOjE1MTM4NjIzNzEsImlkIjoiYS1iLWMtZC1lLWYtMS0yLTMiLCJpc3MiOiJhcnVuLm11cmFsaWRoYXJhbiIsInN1YiI6ImFkbWluIn0." "jk7bRQKTLvs1RcuvMc2B_rt6WBYPoVPirYi_QRBPiuk"; - EXPECT_THROW (jwt::decode(enc_str, algorithms({"none", "hs256"}), verify(false)), + EXPECT_THROW (jwt::decode(enc_str, algorithms({"none", "hs256"}), verify(true)), jwt::KeyNotPresentError); } diff --git a/tests/test_jwt_encode.cc b/tests/test_jwt_encode.cc index ccb7584..a6bfcdd 100644 --- a/tests/test_jwt_encode.cc +++ b/tests/test_jwt_encode.cc @@ -286,7 +286,7 @@ TEST (EncodeTest, HeaderParamTest) std::error_code ec; auto enc_str = obj.signature(); - auto dec_obj = jwt::decode(enc_str, algorithms({"none"}), ec, verify(false)); + auto dec_obj = jwt::decode(enc_str, algorithms({"none"}), ec, verify(true)); EXPECT_EQ (ec.value(), static_cast(jwt::AlgorithmErrc::NoneAlgorithmUsed)); std::cout << dec_obj.header() << std::endl; From 129731da564fb58cc8380aa19525ce320014585d Mon Sep 17 00:00:00 2001 From: Arun M Date: Sun, 5 Aug 2018 15:10:53 +0530 Subject: [PATCH 13/79] Add option to remove type fromt he jwt_header #26 --- include/jwt/impl/jwt.ipp | 20 +++++++++----------- include/jwt/jwt.hpp | 38 +++++++++++++++++++++++++++++++++++++- tests/test_jwt_decode.cc | 16 ++++++++++++++++ tests/test_jwt_encode.cc | 20 ++++++++++++++++++++ 4 files changed, 82 insertions(+), 12 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index f1b9ec7..bfd36d1 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -85,19 +85,16 @@ inline void jwt_header::decode(const jwt::string_view enc_str, std::error_code& if (alg_ != algorithm::NONE) { auto itr = payload_.find("typ"); - if (itr == payload_.end()) { - ec = DecodeErrc::TypHeaderMiss; - return; - } - const auto& typ = itr.value().get(); + if (itr != payload_.end()) { + const auto& typ = itr.value().get(); + if (strcasecmp(typ.c_str(), "JWT")) { + ec = DecodeErrc::TypMismatch; + return; + } - if (strcasecmp(typ.c_str(), "JWT")) { - ec = DecodeErrc::TypMismatch; - return; + typ_ = str_to_type(typ); } - - typ_ = str_to_type(typ); } else { //TODO: } @@ -107,7 +104,8 @@ inline void jwt_header::decode(const jwt::string_view enc_str, std::error_code& auto ret = headers_.insert(it.key()); if (!ret.second) { ec = DecodeErrc::DuplClaims; - break; + //ATTN: Dont stop the decode here + //Not a hard error. } } diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index 1eb28a4..728dc5d 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -51,7 +51,8 @@ namespace jwt { */ enum class type { - JWT = 0, + NONE = 0, + JWT = 1, }; /** @@ -63,6 +64,7 @@ inline enum type str_to_type(const jwt::string_view typ) noexcept assert (typ.length() && "Empty type string"); if (!strcasecmp(typ.data(), "jwt")) return type::JWT; + else if(!strcasecmp(typ.data(), "none")) return type::NONE; throw std::runtime_error("Unknown token type"); @@ -410,6 +412,40 @@ struct jwt_header: write_interface overwrite); } + /** + * Remove the header from JWT. + * NOTE: Special handling for removing type field + * from header. The typ_ is set to NONE when removed. + */ + bool remove_header(const jwt::string_view hname) + { + if (!strcasecmp(hname.data(), "typ")) { + typ_ = type::NONE; + payload_.erase(hname.data()); + return true; + } + + auto itr = headers_.find(hname); + if (itr == std::end(headers_)) { + return false; + } + payload_.erase(hname.data()); + headers_.erase(hname.data()); + + return true; + } + + /** + * Checks if header with the given name + * is present or not. + */ + bool has_header(const jwt::string_view hname) + { + if (!strcasecmp(hname.data(), "typ")) return typ_ != type::NONE; + return headers_.find(hname) != std::end(headers_); + } + + /** * Get the URL safe base64 encoded string * of the header. diff --git a/tests/test_jwt_decode.cc b/tests/test_jwt_decode.cc index b84e9e9..1bb957f 100644 --- a/tests/test_jwt_decode.cc +++ b/tests/test_jwt_decode.cc @@ -156,6 +156,22 @@ TEST (DecodeTest, DecodeHS512) EXPECT_TRUE (obj.payload().has_claim_with_value("sub", "nothing much")); } +TEST (DecodeTest, TypHeaderMiss) +{ + using namespace jwt::params; + + const char* enc_str = + "eyJhbGciOiJIUzI1NiJ9." + "eyJleHAiOjE1MzM0NjE1NTMsImlhdCI6MTUxMzg2MjM3MSwiaWQiOiJhLWItYy1kLWUtZi0xLTItMyIsImlzcyI6ImFydW4ubXVyYWxpZGhhcmFuIiwic3ViIjoiYWRtaW4ifQ." + "pMWBLSWl1p4V958lfe_6ZhvgFMOQv9Eq5mlndVKFKkA"; + + std::error_code ec; + auto obj = jwt::decode(enc_str, algorithms({"none", "hs256"}), ec, verify(false)); + std::cout << "Decode header: " << obj.header() << std::endl; + + EXPECT_FALSE (ec); +} + int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/tests/test_jwt_encode.cc b/tests/test_jwt_encode.cc index a6bfcdd..f3c2976 100644 --- a/tests/test_jwt_encode.cc +++ b/tests/test_jwt_encode.cc @@ -25,6 +25,26 @@ TEST (EncodeTest, TestRemoveClaim) EXPECT_FALSE (obj.has_claim("sub")); } +TEST (EncodeTest, TestRemoveTypHeader) +{ + using namespace jwt::params; + + jwt::jwt_object obj{algorithm("hs256"), secret("secret")}; + + obj.add_claim("iss", "arun.muralidharan") + .add_claim("sub", "admin") + .add_claim("id", "a-b-c-d-e-f-1-2-3") + .add_claim("iat", 1513862371) + .add_claim("exp", std::chrono::system_clock::now()); + + EXPECT_TRUE (obj.header().has_header("typ")); + obj.header().remove_header("typ"); + EXPECT_FALSE (obj.header().has_header("typ")); + + std::cout << "Header: " << obj.header() << '\n'; + std::cout << "Signature: " << obj.signature() << '\n'; +} + TEST (EncodeTest, StrEncodeHS256_1) { using namespace jwt::params; From e5ecca4f388bac4bc894a67ccb63844a2c54843b Mon Sep 17 00:00:00 2001 From: Arun M Date: Sat, 29 Sep 2018 00:24:08 +0530 Subject: [PATCH 14/79] 'str_to_type' has a non-throwing exception specification but can still throw #31 --- include/jwt/jwt.hpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index 728dc5d..b6dae3d 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -66,9 +66,8 @@ inline enum type str_to_type(const jwt::string_view typ) noexcept if (!strcasecmp(typ.data(), "jwt")) return type::JWT; else if(!strcasecmp(typ.data(), "none")) return type::NONE; - throw std::runtime_error("Unknown token type"); - assert (0 && "Code not reached"); + return type::NONE; } From 64de7b6f1d006867b29d18720c483089adf9e05a Mon Sep 17 00:00:00 2001 From: Arun M Date: Wed, 3 Oct 2018 22:07:08 +0530 Subject: [PATCH 15/79] Ptential Fix for VS2015 compile fail #27 --- include/jwt/algorithm.hpp | 5 ++-- include/jwt/base64.hpp | 7 +++--- include/jwt/config.hpp | 51 +++++++++++++++++++++++++++++++++++++++ include/jwt/impl/jwt.ipp | 1 + include/jwt/jwt.hpp | 39 +++++++++++++++--------------- 5 files changed, 78 insertions(+), 25 deletions(-) create mode 100644 include/jwt/config.hpp diff --git a/include/jwt/algorithm.hpp b/include/jwt/algorithm.hpp index b013a39..9abe20c 100644 --- a/include/jwt/algorithm.hpp +++ b/include/jwt/algorithm.hpp @@ -47,6 +47,7 @@ SOFTWARE. #include "jwt/string_view.hpp" #include "jwt/error_codes.hpp" #include "jwt/base64.hpp" +#include "jwt/config.hpp" namespace jwt { @@ -220,7 +221,7 @@ enum class algorithm * Convert the algorithm enum class type to * its stringified form. */ -inline jwt::string_view alg_to_str(enum algorithm alg) noexcept +inline jwt::string_view alg_to_str(SCOPED_ENUM algorithm alg) noexcept { switch (alg) { case algorithm::HS256: return "HS256"; @@ -245,7 +246,7 @@ inline jwt::string_view alg_to_str(enum algorithm alg) noexcept * Convert stringified algorithm to enum class. * The string comparison is case insesitive. */ -inline enum algorithm str_to_alg(const jwt::string_view alg) noexcept +inline SCOPED_ENUM algorithm str_to_alg(const jwt::string_view alg) noexcept { if (!alg.length()) return algorithm::NONE; diff --git a/include/jwt/base64.hpp b/include/jwt/base64.hpp index 8965cb3..1f2e921 100644 --- a/include/jwt/base64.hpp +++ b/include/jwt/base64.hpp @@ -27,6 +27,7 @@ SOFTWARE. #include #include #include +#include "jwt/config.hpp" #include "jwt/string_view.hpp" namespace jwt { @@ -61,8 +62,7 @@ class EMap public: constexpr char at(size_t pos) const noexcept { - assert (pos < chars_.size()); - return chars_.at(pos); + return X_ASSERT(pos < chars_.size()), chars_.at(pos); } private: @@ -155,8 +155,7 @@ class DMap public: constexpr char at(size_t pos) const noexcept { - assert (pos < map_.size()); - return map_[pos]; + return X_ASSERT(pos < map_.size()), map_[pos]; } private: diff --git a/include/jwt/config.hpp b/include/jwt/config.hpp new file mode 100644 index 0000000..6370510 --- /dev/null +++ b/include/jwt/config.hpp @@ -0,0 +1,51 @@ +/* + Copyright (c) 2018 Arun Muralidharan + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ +#ifndef CPP_JWT_CONFIG_HPP +#define CPP_JWT_CONFIG_HPP + +#ifdef _MSC_VER +#define strncasecmp _strnicmp +#define strcasecmp _stricmp +#endif + +// To hack around Visual Studio error: +// error C3431: 'algorithm': a scoped enumeration cannot be redeclared as an unscoped enumeration +#ifdef _MSC_VER +#define SCOPED_ENUM enum class +#else +#define SCOPED_ENUM enum +#endif + +// To hack around Visual Studio error +// error C3249: illegal statement or sub-expression for 'constexpr' function +// Doesn't allow assert to be part of constexpr functions. +// Copied the solution as described in: +// https://akrzemi1.wordpress.com/2017/05/18/asserts-in-constexpr-functions/ +#if defined NDEBUG +# define X_ASSERT(CHECK) void(0) +#else +# define X_ASSERT(CHECK) \ + ( (CHECK) ? void(0) : []{assert(!#CHECK);}() ) +#endif + + +#endif diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index bfd36d1..8e3649b 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -23,6 +23,7 @@ SOFTWARE. #ifndef JWT_IPP #define JWT_IPP +#include "jwt/config.hpp" #include "jwt/detail/meta.hpp" #include diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index b6dae3d..76eacdd 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -32,6 +32,7 @@ SOFTWARE. #include #include "jwt/base64.hpp" +#include "jwt/config.hpp" #include "jwt/algorithm.hpp" #include "jwt/string_view.hpp" #include "jwt/parameters.hpp" @@ -75,7 +76,7 @@ inline enum type str_to_type(const jwt::string_view typ) noexcept * Converts an instance of type `enum class type` * to its string equivalent. */ -inline jwt::string_view type_to_str(enum type typ) +inline jwt::string_view type_to_str(SCOPED_ENUM type typ) { switch (typ) { case type::JWT: return "JWT"; @@ -112,7 +113,7 @@ enum class registered_claims * Converts an instance of type `enum class registered_claims` * to its string equivalent representation. */ -inline jwt::string_view reg_claims_to_str(enum registered_claims claim) noexcept +inline jwt::string_view reg_claims_to_str(SCOPED_ENUM registered_claims claim) noexcept { switch (claim) { case registered_claims::expiration: return "exp"; @@ -296,7 +297,7 @@ struct jwt_header: write_interface * Constructor taking specified algorithm type * and JWT type. */ - jwt_header(enum algorithm alg, enum type typ = type::JWT) + jwt_header(SCOPED_ENUM algorithm alg, SCOPED_ENUM type typ = type::JWT) : alg_(alg) , typ_(typ) { @@ -326,7 +327,7 @@ struct jwt_header: write_interface /** * Set the algorithm. */ - void algo(enum algorithm alg) + void algo(SCOPED_ENUM algorithm alg) { alg_ = alg; payload_["alg"] = alg_to_str(alg_).to_string(); @@ -344,7 +345,7 @@ struct jwt_header: write_interface /** * Get the algorithm. */ - enum algorithm algo() const noexcept + SCOPED_ENUM algorithm algo() const noexcept { return alg_; } @@ -356,7 +357,7 @@ struct jwt_header: write_interface /** * Set the JWT type. */ - void typ(enum type typ) noexcept + void typ(SCOPED_ENUM type typ) noexcept { typ_ = typ; payload_["typ"] = type_to_str(typ_).to_string(); @@ -374,7 +375,7 @@ struct jwt_header: write_interface /** * Get the JWT type. */ - enum type typ() const noexcept + SCOPED_ENUM type typ() const noexcept { return typ_; } @@ -489,10 +490,10 @@ struct jwt_header: write_interface private: // Data members /// The Algorithm to use for signature creation - enum algorithm alg_ = algorithm::NONE; + SCOPED_ENUM algorithm alg_ = algorithm::NONE; /// The type of header - enum type typ_ = type::JWT; + SCOPED_ENUM type typ_ = type::JWT; // The JSON payload object json_t payload_; @@ -602,7 +603,7 @@ struct jwt_payload: write_interface !std::is_same, system_time_t>::value || !std::is_same, jwt::string_view>::value >> - bool add_claim(enum registered_claims cname, T&& cvalue, bool overwrite=false) + bool add_claim(SCOPED_ENUM registered_claims cname, T&& cvalue, bool overwrite=false) { return add_claim( reg_claims_to_str(cname), @@ -616,7 +617,7 @@ struct jwt_payload: write_interface * This overload takes `registered_claims` as the claim name and * `system_time_t` as the claim value type. */ - bool add_claim(enum registered_claims cname, system_time_t tp, bool overwrite=false) + bool add_claim(SCOPED_ENUM registered_claims cname, system_time_t tp, bool overwrite=false) { return add_claim( reg_claims_to_str(cname), @@ -631,7 +632,7 @@ struct jwt_payload: write_interface * This overload takes `registered_claims` as the claim name and * `jwt::string_view` as the claim value type. */ - bool add_claim(enum registered_claims cname, jwt::string_view cvalue, bool overwrite=false) + bool add_claim(SCOPED_ENUM registered_claims cname, jwt::string_view cvalue, bool overwrite=false) { return add_claim( reg_claims_to_str(cname), @@ -664,7 +665,7 @@ struct jwt_payload: write_interface * JSON library will throw an exception. */ template - decltype(auto) get_claim_value(enum registered_claims cname) const + decltype(auto) get_claim_value(SCOPED_ENUM registered_claims cname) const { return get_claim_value(reg_claims_to_str(cname)); } @@ -688,7 +689,7 @@ struct jwt_payload: write_interface * Overload which takes the claim name as an instance * of `registered_claims` type. */ - bool remove_claim(enum registered_claims cname) + bool remove_claim(SCOPED_ENUM registered_claims cname) { return remove_claim(reg_claims_to_str(cname)); } @@ -712,7 +713,7 @@ struct jwt_payload: write_interface * Overload which takes the claim name as an instance * of `registered_claims` type. */ - bool has_claim(enum registered_claims cname) const noexcept + bool has_claim(SCOPED_ENUM registered_claims cname) const noexcept { return has_claim(reg_claims_to_str(cname)); } @@ -737,7 +738,7 @@ struct jwt_payload: write_interface * type `registered_claims`. */ template - bool has_claim_with_value(const enum registered_claims cname, T&& value) const + bool has_claim_with_value(const SCOPED_ENUM registered_claims cname, T&& value) const { return has_claim_with_value(reg_claims_to_str(cname), std::forward(value)); } @@ -1014,7 +1015,7 @@ class jwt_object * @note: See `jwt_payload::add_claim` for more details. */ template - jwt_object& add_claim(enum registered_claims cname, T&& value) + jwt_object& add_claim(SCOPED_ENUM registered_claims cname, T&& value) { return add_claim(reg_claims_to_str(cname), std::forward(value)); } @@ -1031,7 +1032,7 @@ class jwt_object * * @note: See `jwt_payload::remove_claim` for more details. */ - jwt_object& remove_claim(enum registered_claims cname) + jwt_object& remove_claim(SCOPED_ENUM registered_claims cname) { return remove_claim(reg_claims_to_str(cname)); } @@ -1053,7 +1054,7 @@ class jwt_object * * @note: See `jwt_payload::has_claim` for more details. */ - bool has_claim(enum registered_claims cname) const noexcept + bool has_claim(SCOPED_ENUM registered_claims cname) const noexcept { return payload().has_claim(cname); } From 8cb5ea3d5e4eae108a1468703896160c744b361a Mon Sep 17 00:00:00 2001 From: Matt Eastman Date: Wed, 3 Oct 2018 17:24:11 -0500 Subject: [PATCH 16/79] Fix out of bounds read in base64_decode --- include/jwt/base64.hpp | 2 +- tests/test_jwt_decode.cc | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/include/jwt/base64.hpp b/include/jwt/base64.hpp index 1f2e921..3a05b5f 100644 --- a/include/jwt/base64.hpp +++ b/include/jwt/base64.hpp @@ -200,7 +200,7 @@ inline std::string base64_decode(const char* in, size_t len) constexpr static const DMap dmap{}; - while (dmap.at(in[bytes_rem - 1]) == -1) { bytes_rem--; } + while (bytes_rem > 0 && dmap.at(in[bytes_rem - 1]) == -1) { bytes_rem--; } while (bytes_rem > 4) { diff --git a/tests/test_jwt_decode.cc b/tests/test_jwt_decode.cc index 1bb957f..a63410c 100644 --- a/tests/test_jwt_decode.cc +++ b/tests/test_jwt_decode.cc @@ -64,6 +64,20 @@ TEST (DecodeTest, DecodeInvalidHeader) } +TEST (DecodeTest, DecodeEmptyHeader) +{ + using namespace jwt::params; + + const char* enc_str = + ".eyJhdWQiOiJyaWZ0LmlvIiwiZXhwIjoxNTEzODYzMzcxLCJzdWIiOiJub3RoaW5nIG11Y2gifQ."; + + std::error_code ec; + auto obj = jwt::decode(enc_str, algorithms({"hs256"}), ec, secret(""), verify(true)); + ASSERT_TRUE (ec); + EXPECT_EQ (ec.value(), static_cast(jwt::DecodeErrc::JsonParseError)); + +} + TEST (DecodeTest, DecodeInvalidPayload) { using namespace jwt::params; From 043c8429d47e75e41658868daadc58eba0a50526 Mon Sep 17 00:00:00 2001 From: Matt Frantz Date: Wed, 24 Oct 2018 17:40:11 -0700 Subject: [PATCH 17/79] issue-33: Add test showing how to invoke move ctor --- tests/CMakeLists.txt | 3 +++ tests/test_jwt_object.cc | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 tests/test_jwt_object.cc diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c27feb2..c52e256 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -5,6 +5,9 @@ link_directories(${OPENSSL_LIBRARIES}) SET(CERT_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/certs") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DCERT_ROOT_DIR=\"\\\"${CERT_ROOT_DIR}\\\"\"") +add_executable(test_jwt_object test_jwt_object.cc) +target_link_libraries(test_jwt_object ssl crypto gtest) + add_executable(test_jwt_encode test_jwt_encode.cc) target_link_libraries(test_jwt_encode ssl crypto gtest) diff --git a/tests/test_jwt_object.cc b/tests/test_jwt_object.cc new file mode 100644 index 0000000..5b19955 --- /dev/null +++ b/tests/test_jwt_object.cc @@ -0,0 +1,35 @@ +#include "gtest/gtest.h" +#include "jwt/jwt.hpp" + +namespace { + +struct Wrapper +{ + // The std::move here is required to resolve to the move ctor + // rather than to the universal reference ctor. + Wrapper(jwt::jwt_object&& obj) : object{std::move(obj)} {} + jwt::jwt_object object; +}; + +} // END namespace + +TEST (ObjectTest, MoveConstructor) +{ + using namespace jwt::params; + + jwt::jwt_object obj{algorithm("hs256"), secret("secret")}; + + obj.add_claim("iss", "arun.muralidharan"); + + auto wrapper = Wrapper{std::move(obj)}; + + EXPECT_EQ(wrapper.object.header().algo(), jwt::algorithm::HS256); + EXPECT_EQ(wrapper.object.secret(), "secret"); + EXPECT_TRUE(wrapper.object.payload().has_claim_with_value("iss", "arun.muralidharan")); +} + +int main(int argc, char **argv) +{ + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From 1e588256f44202d7f2fa606dfdc5718e9741c79b Mon Sep 17 00:00:00 2001 From: Arun M Date: Sat, 27 Oct 2018 12:07:06 +0530 Subject: [PATCH 18/79] Narrowing errors compiling for ARM #36 --- include/jwt/base64.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/jwt/base64.hpp b/include/jwt/base64.hpp index 1f2e921..e3baf6e 100644 --- a/include/jwt/base64.hpp +++ b/include/jwt/base64.hpp @@ -159,7 +159,7 @@ class DMap } private: - std::array map_ = {{ + std::array map_ = {{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0-15 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 16-31 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, // 32-47 From 1b105f47727099bb577857b436460ea877c745c6 Mon Sep 17 00:00:00 2001 From: Matt Frantz Date: Thu, 1 Nov 2018 13:28:49 -0700 Subject: [PATCH 19/79] SFINAE guard on jwt_object's universal reference constructor This allows the move constructor to be preferred in some cases. --- include/jwt/impl/jwt.ipp | 4 +++- include/jwt/jwt.hpp | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 8e3649b..e5474e3 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -290,7 +290,9 @@ jwt_signature::get_verify_algorithm_impl(const jwt_header& hdr) const noexcept // template -jwt_object::jwt_object(First&& first, Rest&&... rest) +jwt_object::jwt_object( + std::enable_if_t::value, First>&& first, + Rest&&... rest) { static_assert (detail::meta::is_parameter_concept::value && detail::meta::are_all_params::value, diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index 76eacdd..fbb496e 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -889,7 +889,7 @@ class jwt_object * to populate header. Not much useful unless JWE is supported. */ template - jwt_object(First&& first, Rest&&... rest); + jwt_object(std::enable_if_t::value, First>&& first, Rest&&... rest); public: // Exposed static APIs /** From 1cbc5eb5a54c45b79399483c4357e7e47100f474 Mon Sep 17 00:00:00 2001 From: Arun M Date: Tue, 20 Nov 2018 19:08:08 +0530 Subject: [PATCH 20/79] compile error with master #37 --- include/jwt/impl/jwt.ipp | 6 +++--- include/jwt/jwt.hpp | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index e5474e3..5e17936 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -289,10 +289,10 @@ jwt_signature::get_verify_algorithm_impl(const jwt_header& hdr) const noexcept // -template +template jwt_object::jwt_object( - std::enable_if_t::value, First>&& first, - Rest&&... rest) + First&& first, Rest&&... rest) { static_assert (detail::meta::is_parameter_concept::value && detail::meta::are_all_params::value, diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index fbb496e..c96edcb 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -888,8 +888,9 @@ class jwt_object * containers which models `MappingConcept` (see `meta::is_mapping_concept`) * to populate header. Not much useful unless JWE is supported. */ - template - jwt_object(std::enable_if_t::value, First>&& first, Rest&&... rest); + template ::value>> + jwt_object(First&& first, Rest&&... rest); public: // Exposed static APIs /** From 0b68fd46fb33d3cf81889c26b560f1051d34234d Mon Sep 17 00:00:00 2001 From: Huang-Ming Huang Date: Mon, 11 Feb 2019 14:10:38 -0600 Subject: [PATCH 21/79] Some cmake improvements --- CMakeLists.txt | 8 ++++++-- README.md | 2 +- cmake_command | 2 +- examples/CMakeLists.txt | 11 +++++++---- tests/CMakeLists.txt | 22 ++++++++++++++-------- 5 files changed, 29 insertions(+), 16 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 390fa77..e4d6793 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,9 +10,13 @@ SET( CMAKE_CXX_FLAGS "-std=c++14 -Wall" ) include_directories (include) -#find_package(OpenSSL REQUIRED) +find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) -link_directories(${OPENSSL_LIBRARIES}) + +find_package(GTest REQUIRED) +include_directories(${GTEST_INCLUDE_DIRS}) + +enable_testing() # Recurse into the "Hello" and "Demo" subdirectories. This does not actually # cause another cmake executable to run. The same process will walk through diff --git a/README.md b/README.md index 451c952..7c21a03 100644 --- a/README.md +++ b/README.md @@ -214,7 +214,7 @@ This is a header only library, so you can just add it to your include path and s For example one can run cmake like: ``` -cmake -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl/1.0.2j/ -DOPENSSL_LIBRARIES=/usr/local/Cellar/openssl/1.0.2j/lib/ -DOPENSSL_INCLUDE_DIR=/usr/local/Cellar/openssl/1.0.2j/include/ +cmake -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl/1.0.2j -DGTEST_ROOT=$HOME/googletest ``` ## Parameters diff --git a/cmake_command b/cmake_command index 8fc16f6..507352d 100644 --- a/cmake_command +++ b/cmake_command @@ -1 +1 @@ -cmake -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl/1.0.2j/ -DOPENSSL_LIBRARIES=/usr/local/Cellar/openssl/1.0.2j/lib/ -DOPENSSL_INCLUDE_DIR=/usr/local/Cellar/openssl/1.0.2j/include/ +cmake -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl/1.0.2j -DGTEST_ROOT=$HOME/googletest \ No newline at end of file diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 281e87e..9180a01 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,15 +1,18 @@ include_directories(${OPENSSL_INCLUDE_DIR}) -link_directories(${OPENSSL_LIBRARIES}) SET(CERT_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/rsa_256") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DCERT_ROOT_DIR=\"\\\"${CERT_ROOT_DIR}\\\"\"") add_executable(simple_ex1 simple_ex1.cc) -target_link_libraries(simple_ex1 ssl crypto gtest) +target_link_libraries(simple_ex1 ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME simple_ex1 COMMAND ./simple_ex1 WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(simple_ex2 simple_ex2.cc) -target_link_libraries(simple_ex2 ssl crypto gtest) +target_link_libraries(simple_ex2 ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME simple_ex2 COMMAND ./simple_ex2 WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(simple_ex3_rsa simple_ex3_rsa.cc) -target_link_libraries(simple_ex3_rsa ssl crypto gtest) +target_link_libraries(simple_ex3_rsa ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME simple_ex3_rsa COMMAND ./simple_ex3_rsa WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c52e256..1ee5201 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,27 +1,33 @@ include_directories(${OPENSSL_INCLUDE_DIR}) -link_directories(${OPENSSL_LIBRARIES}) SET(CERT_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/certs") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DCERT_ROOT_DIR=\"\\\"${CERT_ROOT_DIR}\\\"\"") add_executable(test_jwt_object test_jwt_object.cc) -target_link_libraries(test_jwt_object ssl crypto gtest) +target_link_libraries(test_jwt_object ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_object COMMAND ./test_jwt_object WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_encode test_jwt_encode.cc) -target_link_libraries(test_jwt_encode ssl crypto gtest) +target_link_libraries(test_jwt_encode ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_encode COMMAND ./test_jwt_encode WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_decode test_jwt_decode.cc) -target_link_libraries(test_jwt_decode ssl crypto gtest) +target_link_libraries(test_jwt_decode ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_decode COMMAND ./test_jwt_decode WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_decode_verifiy test_jwt_decode_verifiy.cc) -target_link_libraries(test_jwt_decode_verifiy ssl crypto gtest) +target_link_libraries(test_jwt_decode_verifiy ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_decode_verifiy COMMAND ./test_jwt_decode_verifiy WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_decode_verifiy_with_exception test_jwt_decode_verifiy_with_exception.cc) -target_link_libraries(test_jwt_decode_verifiy_with_exception ssl crypto gtest) +target_link_libraries(test_jwt_decode_verifiy_with_exception ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_decode_verifiy_with_exception COMMAND ./test_jwt_decode_verifiy_with_exception WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_rsa test_jwt_rsa.cc) -target_link_libraries(test_jwt_rsa ssl crypto gtest) +target_link_libraries(test_jwt_rsa ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES} ) +add_test(NAME test_jwt_rsa COMMAND ./test_jwt_rsa WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_es test_jwt_es.cc) -target_link_libraries(test_jwt_es ssl crypto gtest) +target_link_libraries(test_jwt_es ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_es COMMAND ./test_jwt_es WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) From 74b7b344c6d2ff97a752bbdc8247a82529801832 Mon Sep 17 00:00:00 2001 From: Huang-Ming Huang Date: Sat, 16 Feb 2019 15:36:12 -0600 Subject: [PATCH 22/79] Add api to supply secret based on decoded payload --- include/jwt/impl/jwt.ipp | 14 ++++++++++++-- include/jwt/jwt.hpp | 5 ++++- include/jwt/parameters.hpp | 16 ++++++++++++++++ tests/test_jwt_es.cc | 9 +++++++++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 5e17936..197a614 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -544,6 +544,14 @@ void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::secret jwt_object::set_decode_params(dparams, std::forward(args)...); } +template +void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::secret_function_param&& s, Rest&&... args) +{ + dparams.secret = s.get(*dparams.payload_ptr); + dparams.has_secret = true; + jwt_object::set_decode_params(dparams, std::forward(args)...); +} + template void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::leeway_param l, Rest&&... args) { @@ -650,10 +658,11 @@ jwt_object decode(const jwt::string_view enc_str, //Validate JTI bool validate_jti = false; + const jwt_payload* payload_ptr = 0; }; decode_params dparams{}; - jwt_object::set_decode_params(dparams, std::forward(args)...); + //Signature must have atleast 2 dots auto dot_cnt = std::count_if(std::begin(enc_str), std::end(enc_str), @@ -695,7 +704,8 @@ jwt_object decode(const jwt::string_view enc_str, return obj; } obj.payload(std::move(payload)); - + dparams.payload_ptr = & obj.payload(); + jwt_object::set_decode_params(dparams, std::forward(args)...); if (dparams.verify) { try { ec = obj.verify(dparams, algos); diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index c96edcb..36dac5f 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -82,7 +82,7 @@ inline jwt::string_view type_to_str(SCOPED_ENUM type typ) case type::JWT: return "JWT"; default: assert (0 && "Unknown type"); }; - + __builtin_unreachable(); assert (0 && "Code not reached"); } @@ -1121,6 +1121,9 @@ class jwt_object template static void set_decode_params(DecodeParams& dparams, params::detail::secret_param s, Rest&&... args); + template + static void set_decode_params(DecodeParams& dparams, params::detail::secret_function_param&& s, Rest&&... args); + template static void set_decode_params(DecodeParams& dparams, params::detail::leeway_param l, Rest&&... args); diff --git a/include/jwt/parameters.hpp b/include/jwt/parameters.hpp index b444e6e..9b94171 100644 --- a/include/jwt/parameters.hpp +++ b/include/jwt/parameters.hpp @@ -84,6 +84,15 @@ struct secret_param string_view secret_; }; +template +struct secret_function_param +{ + T get() const { return fun_; } + template + std::string get(U&& u) const { return fun_(u);} + T fun_; +}; + /** * Parameter for providing the algorithm to use. * The parameter can accept either the string representation @@ -297,6 +306,13 @@ inline detail::secret_param secret(const string_view sv) return { sv }; } +template +inline std::enable_if_t::value, detail::secret_function_param> +secret(T&& fun) +{ + return detail::secret_function_param{ fun }; +} + /** */ inline detail::algorithm_param algorithm(const string_view sv) diff --git a/tests/test_jwt_es.cc b/tests/test_jwt_es.cc index 9064d2d..085cfd1 100644 --- a/tests/test_jwt_es.cc +++ b/tests/test_jwt_es.cc @@ -136,6 +136,15 @@ TEST (ESAlgo, ES384EncodingDecodingValidTest) EXPECT_EQ (dec_obj.header().algo(), jwt::algorithm::ES384); EXPECT_TRUE (dec_obj.has_claim("exp")); EXPECT_TRUE (obj.payload().has_claim_with_value("exp", 4682665886)); + + std::map keystore{{"arun.muralidharan", key}}; + + auto l = [&keystore](const jwt::jwt_payload& payload){ + auto iss = payload.get_claim_value("iss"); + return keystore[iss]; + }; + auto dec_obj2 = jwt::decode(enc_str, algorithms({"es384"}), verify(true), secret(l)); + EXPECT_EQ (dec_obj2.header().algo(), jwt::algorithm::ES384); } int main(int argc, char* argv[]) { From ff21be29478d379e9aeb9d9c3ffef6bc9f864848 Mon Sep 17 00:00:00 2001 From: Matt Powley Date: Thu, 21 Mar 2019 12:31:02 +0000 Subject: [PATCH 23/79] '__builtin_unreachable' is not available on Windows Replaced with macro that inserts Windows equivalent --- include/jwt/algorithm.hpp | 5 ++-- include/jwt/assertions.hpp | 51 ++++++++++++++++++++++++++++++++++++++ include/jwt/jwt.hpp | 9 ++++--- 3 files changed, 59 insertions(+), 6 deletions(-) create mode 100644 include/jwt/assertions.hpp diff --git a/include/jwt/algorithm.hpp b/include/jwt/algorithm.hpp index 9abe20c..eba497b 100644 --- a/include/jwt/algorithm.hpp +++ b/include/jwt/algorithm.hpp @@ -43,6 +43,7 @@ SOFTWARE. #include #include +#include "jwt/assertions.hpp" #include "jwt/exceptions.hpp" #include "jwt/string_view.hpp" #include "jwt/error_codes.hpp" @@ -239,7 +240,7 @@ inline jwt::string_view alg_to_str(SCOPED_ENUM algorithm alg) noexcept default: assert (0 && "Unknown Algorithm"); }; return "UNKN"; - assert (0 && "Code not reached"); + JWT_NOT_REACHED("Code not reached"); } /** @@ -263,7 +264,7 @@ inline SCOPED_ENUM algorithm str_to_alg(const jwt::string_view alg) noexcept return algorithm::UNKN; - assert (0 && "Code not reached"); + JWT_NOT_REACHED("Code not reached"); } /** diff --git a/include/jwt/assertions.hpp b/include/jwt/assertions.hpp new file mode 100644 index 0000000..1fa0fd1 --- /dev/null +++ b/include/jwt/assertions.hpp @@ -0,0 +1,51 @@ +/* +Copyright (c) 2017 Arun Muralidharan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + */ + +#ifndef CPP_JWT_ASSERTIONS_HPP +#define CPP_JWT_ASSERTIONS_HPP + +#include + +namespace jwt { + +#if defined(__clang__) +# define JWT_NOT_REACHED_MARKER() __builtin_unreachable() +#elif defined(__GNUC__) +# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) +# define JWT_NOT_REACHED_MARKER() __builtin_unreachable() +# endif +#elif defined(_MSC_VER) +# define JWT_NOT_REACHED_MARKER() __assume(0) +#endif + +#if defined(DEBUG) +# define JWT_NOT_REACHED(reason) do { \ + assert (0 && reason); \ + JWT_NOT_REACHED_MARKER(); \ + } while (0) +#else +# define JWT_NOT_REACHED(reason) JWT_NOT_REACHED_MARKER() +#endif + +} // END namespace jwt + +#endif diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index 36dac5f..7cc0ecc 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -31,6 +31,7 @@ SOFTWARE. #include #include +#include "jwt/assertions.hpp" #include "jwt/base64.hpp" #include "jwt/config.hpp" #include "jwt/algorithm.hpp" @@ -67,7 +68,7 @@ inline enum type str_to_type(const jwt::string_view typ) noexcept if (!strcasecmp(typ.data(), "jwt")) return type::JWT; else if(!strcasecmp(typ.data(), "none")) return type::NONE; - assert (0 && "Code not reached"); + JWT_NOT_REACHED("Code not reached"); return type::NONE; } @@ -82,8 +83,8 @@ inline jwt::string_view type_to_str(SCOPED_ENUM type typ) case type::JWT: return "JWT"; default: assert (0 && "Unknown type"); }; - __builtin_unreachable(); - assert (0 && "Code not reached"); + + JWT_NOT_REACHED("Code not reached"); } @@ -125,8 +126,8 @@ inline jwt::string_view reg_claims_to_str(SCOPED_ENUM registered_claims claim) n case registered_claims::jti: return "jti"; default: assert (0 && "Not a registered claim"); }; + JWT_NOT_REACHED("Code not reached"); return ""; - assert (0 && "Code not reached"); } /** From 31df3b8bd4f11f0d7470b2aeca9bcf4ffa491163 Mon Sep 17 00:00:00 2001 From: leoTlr Date: Thu, 4 Apr 2019 00:24:25 +0200 Subject: [PATCH 24/79] compile with -Wextra --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e4d6793..07810da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ cmake_minimum_required (VERSION 2.8.11) project (cpp-jwt) #SET (CMAKE_CXX_COMPILER /usr/local/bin/g++) -SET( CMAKE_CXX_FLAGS "-std=c++14 -Wall" ) +SET( CMAKE_CXX_FLAGS "-std=c++14 -Wall -Wextra" ) include_directories (include) From a3a0d9c0ec9f30887aa06157b6b1804d0c6098c7 Mon Sep 17 00:00:00 2001 From: leoTlr Date: Thu, 4 Apr 2019 00:26:54 +0200 Subject: [PATCH 25/79] prevent -Wunused-parameter warning with gcc 8.2.1 --- include/jwt/impl/jwt.ipp | 1 + 1 file changed, 1 insertion(+) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 197a614..01b0881 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -607,6 +607,7 @@ void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::valida template void jwt_object::set_decode_params(DecodeParams& dparams) { + (void) dparams; // prevent -Wunused-parameter with gcc return; } From 4234eea1bf9e7929a508aea2839f5f7fbb579bc1 Mon Sep 17 00:00:00 2001 From: leoTlr Date: Thu, 4 Apr 2019 00:27:39 +0200 Subject: [PATCH 26/79] prevent -Wimplicit-fallthrough= warning with gcc 8.2.1 --- include/jwt/base64.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/jwt/base64.hpp b/include/jwt/base64.hpp index 226c1f0..4cb28d7 100644 --- a/include/jwt/base64.hpp +++ b/include/jwt/base64.hpp @@ -229,16 +229,16 @@ inline std::string base64_decode(const char* in, size_t len) const auto fourth = dmap.at(in[3]); result[i + 2] = (third << 6) | fourth; bytes_wr++; - //FALLTHROUGH } + //FALLTHROUGH case 3: { const auto second = dmap.at(in[1]); const auto third = dmap.at(in[2]); result[i + 1] = (second << 4) | (third >> 2); bytes_wr++; - //FALLTHROUGH } + //FALLTHROUGH case 2: { const auto first = dmap.at(in[0]); From 602ec562e0b839127087e099383f0af2ca422317 Mon Sep 17 00:00:00 2001 From: Olcay Cabbas Date: Fri, 3 May 2019 09:08:21 +0300 Subject: [PATCH 27/79] Fix for error setw is not defined --- include/jwt/impl/jwt.ipp | 1 + 1 file changed, 1 insertion(+) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 01b0881..1797f4c 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -26,6 +26,7 @@ SOFTWARE. #include "jwt/config.hpp" #include "jwt/detail/meta.hpp" #include +#include namespace jwt { From 1e9667ae0d139a9eb741e30fd17c31373764c0ed Mon Sep 17 00:00:00 2001 From: Arun M Date: Fri, 31 May 2019 00:45:35 +0530 Subject: [PATCH 28/79] update nlohmann json library --- include/jwt/impl/jwt.ipp | 1 + include/jwt/json/json.hpp | 19614 +++++++++++++++++++++++++----------- 2 files changed, 13476 insertions(+), 6139 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 01b0881..1797f4c 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -26,6 +26,7 @@ SOFTWARE. #include "jwt/config.hpp" #include "jwt/detail/meta.hpp" #include +#include namespace jwt { diff --git a/include/jwt/json/json.hpp b/include/jwt/json/json.hpp index d153e7a..c173f4e 100644 --- a/include/jwt/json/json.hpp +++ b/include/jwt/json/json.hpp @@ -1,18 +1,23 @@ /* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ -| | |__ | | | | | | version 2.1.1 +| | |__ | | | | | | version 3.6.1 |_____|_____|_____|_|___| https://github.com/nlohmann/json + Licensed under the MIT License . -Copyright (c) 2013-2017 Niels Lohmann . +SPDX-License-Identifier: MIT +Copyright (c) 2013-2019 Niels Lohmann . + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,143 +27,87 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#ifndef NLOHMANN_JSON_HPP -#define NLOHMANN_JSON_HPP +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ -#include // all_of, copy, fill, find, for_each, generate_n, none_of, remove, reverse, transform -#include // array +#define NLOHMANN_JSON_VERSION_MAJOR 3 +#define NLOHMANN_JSON_VERSION_MINOR 6 +#define NLOHMANN_JSON_VERSION_PATCH 1 + +#include // all_of, find, for_each #include // assert #include // and, not, or -#include // lconv, localeconv -#include // isfinite, labs, ldexp, signbit #include // nullptr_t, ptrdiff_t, size_t -#include // int64_t, uint64_t -#include // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull -#include // memcpy, strlen -#include // forward_list -#include // function, hash, less +#include // hash, less #include // initializer_list -#include // hex -#include // istream, ostream -#include // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator -#include // numeric_limits -#include // locale -#include // map -#include // addressof, allocator, allocator_traits, unique_ptr +#include // istream, ostream +#include // random_access_iterator_tag +#include // unique_ptr #include // accumulate -#include // stringstream -#include // getline, stoi, string, to_string -#include // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type -#include // declval, forward, make_pair, move, pair, swap -#include // valarray +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap #include // vector -// exclude unsupported compilers -#if defined(__clang__) - #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 - #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" - #endif -#elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) - #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 - #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" - #endif -#endif +// #include -// disable float-equal warnings on GCC/clang -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wfloat-equal" -#endif -// disable documentation warnings on clang -#if defined(__clang__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdocumentation" -#endif +#include -// allow for portable deprecation warnings -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #define JSON_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) - #define JSON_DEPRECATED __declspec(deprecated) -#else - #define JSON_DEPRECATED -#endif +// #include -// allow to disable exceptions -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION) - #define JSON_THROW(exception) throw exception - #define JSON_TRY try - #define JSON_CATCH(exception) catch(exception) -#else - #define JSON_THROW(exception) std::abort() - #define JSON_TRY if(true) - #define JSON_CATCH(exception) if(false) -#endif -// manual branch prediction -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #define JSON_LIKELY(x) __builtin_expect(!!(x), 1) - #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0) -#else - #define JSON_LIKELY(x) x - #define JSON_UNLIKELY(x) x -#endif +#include // transform +#include // array +#include // and, not +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray -// cpp language standard detection -#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 -#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) - #define JSON_HAS_CPP_14 -#endif +// #include -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ -template -struct adl_serializer; -// forward declaration of basic_json (required to split the class) -template class ObjectType = - std::map, - template class ArrayType = std::vector, - class StringType = std::string, class BooleanType = bool, - class NumberIntegerType = std::int64_t, - class NumberUnsignedType = std::uint64_t, - class NumberFloatType = double, - template class AllocatorType = std::allocator, - template class JSONSerializer = - adl_serializer> -class basic_json; +#include // exception +#include // runtime_error +#include // to_string -// Ugly macros to avoid uglier copy-paste when specializing basic_json -// This is only temporary and will be removed in 3.0 +// #include -#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ - template class ObjectType, \ - template class ArrayType, \ - class StringType, class BooleanType, class NumberIntegerType, \ - class NumberUnsignedType, class NumberFloatType, \ - template class AllocatorType, \ - template class JSONSerializer> -#define NLOHMANN_BASIC_JSON_TPL \ - basic_json +#include // size_t +namespace nlohmann +{ +namespace detail +{ +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; -/*! -@brief unnamed namespace with internal helper functions -This namespace collects some functions that could not be defined inside the -@ref basic_json class. -@since version 2.1.0 -*/ + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ namespace detail { //////////////// @@ -167,10 +116,12 @@ namespace detail /*! @brief general exception of the @ref basic_json class + This class is an extension of `std::exception` objects with a member @a id for exception ids. It is used as the base class for all exceptions thrown by the @ref basic_json class. This class can hence be used as "wildcard" to catch exceptions. + Subclasses: - @ref parse_error for exceptions indicating a parse error - @ref invalid_iterator for exceptions indicating errors with iterators @@ -178,14 +129,17 @@ exceptions. a wrong type - @ref out_of_range for exceptions indicating access out of the defined range - @ref other_error for exceptions indicating other library errors + @internal @note To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor. @endinternal + @liveexample{The following code shows how arbitrary library exceptions can be caught.,exception} + @since version 3.0.0 */ class exception : public std::exception @@ -215,12 +169,16 @@ class exception : public std::exception /*! @brief exception indicating a parse error -This excpetion is thrown by the library when a parse error occurs. Parse errors + +This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. + Member @a byte holds the byte index of the last read character in the input file. + Exceptions have ids 1xx. + name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. @@ -228,24 +186,29 @@ json.exception.parse_error.102 | parse error at 14: missing or wrong low surroga json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. -json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number wihtout a leading `0`. +json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. -json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xf8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. +json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. +json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). + @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). + @liveexample{The following code shows how a `parse_error` exception can be caught.,parse_error} -@sa @ref exception for the base class of the library exceptions -@sa @ref invalid_iterator for exceptions indicating errors with iterators -@sa @ref type_error for exceptions indicating executing a member function with + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with a wrong type -@sa @ref out_of_range for exceptions indicating access out of the defined range -@sa @ref other_error for exceptions indicating other library errors +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + @since version 3.0.0 */ class parse_error : public exception @@ -254,22 +217,32 @@ class parse_error : public exception /*! @brief create a parse error exception @param[in] id_ the id of the exception - @param[in] byte_ the byte index where the error occurred (or 0 if the - position cannot be determined) + @param[in] pos the position where the error occurred (or with + chars_read_total=0 if the position cannot be + determined) @param[in] what_arg the explanatory string @return parse_error object */ + static parse_error create(int id_, const position_t& pos, const std::string& what_arg) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + position_string(pos) + ": " + what_arg; + return parse_error(id_, pos.chars_read_total, w.c_str()); + } + static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) { std::string w = exception::name("parse_error", id_) + "parse error" + - (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") + + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + ": " + what_arg; return parse_error(id_, byte_, w.c_str()); } /*! @brief byte index of the parse error + The byte index of the last read character in the input file. + @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). @@ -279,13 +252,22 @@ class parse_error : public exception private: parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {} + + static std::string position_string(const position_t& pos) + { + return " at line " + std::to_string(pos.lines_read + 1) + + ", column " + std::to_string(pos.chars_read_current_line); + } }; /*! @brief exception indicating errors with iterators + This exception is thrown if iterators passed to a library function do not match the expected semantics. + Exceptions have ids 2xx. + name / id | example message | description ----------------------------------- | --------------- | ------------------------- json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. @@ -302,14 +284,17 @@ json.exception.invalid_iterator.211 | passed iterators may not belong to contain json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). + @liveexample{The following code shows how an `invalid_iterator` exception can be caught.,invalid_iterator} -@sa @ref exception for the base class of the library exceptions -@sa @ref parse_error for exceptions indicating a parse error -@sa @ref type_error for exceptions indicating executing a member function with + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref type_error for exceptions indicating executing a member function with a wrong type -@sa @ref out_of_range for exceptions indicating access out of the defined range -@sa @ref other_error for exceptions indicating other library errors +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + @since version 3.0.0 */ class invalid_iterator : public exception @@ -328,14 +313,17 @@ class invalid_iterator : public exception /*! @brief exception indicating executing a member function with a wrong type + This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. + Exceptions have ids 3xx. + name / id | example message | description ----------------------------- | --------------- | ------------------------- json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. -json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&. +json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. @@ -348,13 +336,18 @@ json.exception.type_error.312 | cannot use update() with string | The @ref updat json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. +json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | +json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | + @liveexample{The following code shows how a `type_error` exception can be caught.,type_error} -@sa @ref exception for the base class of the library exceptions -@sa @ref parse_error for exceptions indicating a parse error -@sa @ref invalid_iterator for exceptions indicating errors with iterators -@sa @ref out_of_range for exceptions indicating access out of the defined range -@sa @ref other_error for exceptions indicating other library errors + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + @since version 3.0.0 */ class type_error : public exception @@ -372,10 +365,13 @@ class type_error : public exception /*! @brief exception indicating access out of the defined range + This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. + Exceptions have ids 4xx. + name / id | example message | description ------------------------------- | --------------- | ------------------------- json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. @@ -384,14 +380,20 @@ json.exception.out_of_range.403 | key 'foo' not found | The provided key was not json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. +json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. | +json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | +json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | + @liveexample{The following code shows how an `out_of_range` exception can be caught.,out_of_range} -@sa @ref exception for the base class of the library exceptions -@sa @ref parse_error for exceptions indicating a parse error -@sa @ref invalid_iterator for exceptions indicating errors with iterators -@sa @ref type_error for exceptions indicating executing a member function with + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with a wrong type -@sa @ref other_error for exceptions indicating other library errors +@sa - @ref other_error for exceptions indicating other library errors + @since version 3.0.0 */ class out_of_range : public exception @@ -409,21 +411,26 @@ class out_of_range : public exception /*! @brief exception indicating other library errors + This exception is thrown in case of errors that cannot be classified with the other exception types. + Exceptions have ids 5xx. + name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. -json.exception.other_error.502 | invalid object size for conversion | Some conversions to user-defined types impose constraints on the object size (e.g. std::pair) -@sa @ref exception for the base class of the library exceptions -@sa @ref parse_error for exceptions indicating a parse error -@sa @ref invalid_iterator for exceptions indicating errors with iterators -@sa @ref type_error for exceptions indicating executing a member function with + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with a wrong type -@sa @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref out_of_range for exceptions indicating access out of the defined range + @liveexample{The following code shows how an `other_error` exception can be caught.,other_error} + @since version 3.0.0 */ class other_error : public exception @@ -438,91 +445,186 @@ class other_error : public exception private: other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; +} // namespace detail +} // namespace nlohmann +// #include -/////////////////////////// -// JSON type enumeration // -/////////////////////////// +#include // pair -/*! -@brief the JSON type enumeration -This enumeration collects the different JSON types. It is internally used to -distinguish the stored values, and the functions @ref basic_json::is_null(), -@ref basic_json::is_object(), @ref basic_json::is_array(), -@ref basic_json::is_string(), @ref basic_json::is_boolean(), -@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), -@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), -@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and -@ref basic_json::is_structured() rely on it. -@note There are three enumeration entries (number_integer, number_unsigned, and -number_float), because the library distinguishes these three types for numbers: -@ref basic_json::number_unsigned_t is used for unsigned integers, -@ref basic_json::number_integer_t is used for signed integers, and -@ref basic_json::number_float_t is used for floating-point numbers or to -approximate integers which do not fit in the limits of their respective type. -@sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON -value with the default value for a given type -@since version 1.0.0 -*/ -enum class value_t : uint8_t -{ - null, ///< null value - object, ///< object (unordered set of name/value pairs) - array, ///< array (ordered collection of values) - string, ///< string value - boolean, ///< boolean value - number_integer, ///< number value (signed integer) - number_unsigned, ///< number value (unsigned integer) - number_float, ///< number value (floating-point) - discarded ///< discarded by the the parser callback function -}; +// This file contains all internal macro definitions +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them -/*! -@brief comparison operator for JSON types -Returns an ordering that is similar to Python: -- order: null < boolean < number < object < array < string -- furthermore, each type is not smaller than itself -@since version 1.0.0 -*/ -inline bool operator<(const value_t lhs, const value_t rhs) noexcept -{ - static constexpr std::array order = {{ - 0, // null - 3, // object - 4, // array - 5, // string - 1, // boolean - 2, // integer - 2, // unsigned - 2, // float - } - }; +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif - // discarded values are not comparable - return lhs != value_t::discarded and rhs != value_t::discarded and - order[static_cast(lhs)] < order[static_cast(rhs)]; -} +// C++ language standard detection +#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 +#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 +#endif +// disable float-equal warnings on GCC/clang +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" +#endif -///////////// -// helpers // -///////////// +// disable documentation warnings on clang +#if defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdocumentation" +#endif -template struct is_basic_json : std::false_type {}; +// allow for portable deprecation warnings +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #define JSON_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) + #define JSON_DEPRECATED __declspec(deprecated) +#else + #define JSON_DEPRECATED +#endif -NLOHMANN_BASIC_JSON_TPL_DECLARATION -struct is_basic_json : std::true_type {}; +// allow for portable nodiscard warnings +#if defined(__has_cpp_attribute) + #if __has_cpp_attribute(nodiscard) + #if defined(__clang__) && !defined(JSON_HAS_CPP_17) // issue #1535 + #define JSON_NODISCARD + #else + #define JSON_NODISCARD [[nodiscard]] + #endif + #elif __has_cpp_attribute(gnu::warn_unused_result) + #define JSON_NODISCARD [[gnu::warn_unused_result]] + #else + #define JSON_NODISCARD + #endif +#else + #define JSON_NODISCARD +#endif -// alias templates to reduce boilerplate -template -using enable_if_t = typename std::enable_if::type; +// allow to disable exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif -template -using uncvref_t = typename std::remove_cv::type>::type; +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif -// implementation of C++14 index_sequence and affiliates -// source: https://stackoverflow.com/a/32223343 +// manual branch prediction +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #define JSON_LIKELY(x) __builtin_expect(x, 1) + #define JSON_UNLIKELY(x) __builtin_expect(x, 0) +#else + #define JSON_LIKELY(x) x + #define JSON_UNLIKELY(x) x +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// #include + + +#include // not +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type + +namespace nlohmann +{ +namespace detail +{ +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +template +using uncvref_t = typename std::remove_cv::type>::type; + +// implementation of C++14 index_sequence and affiliates +// source: https://stackoverflow.com/a/32223343 template struct index_sequence { @@ -539,581 +641,778 @@ struct merge_and_renumber; template struct merge_and_renumber, index_sequence> - : index_sequence < I1..., (sizeof...(I1) + I2)... > - {}; + : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; template struct make_index_sequence : merge_and_renumber < typename make_index_sequence < N / 2 >::type, - typename make_index_sequence < N - N / 2 >::type > -{}; + typename make_index_sequence < N - N / 2 >::type > {}; -template<> struct make_index_sequence<0> : index_sequence<> { }; -template<> struct make_index_sequence<1> : index_sequence<0> { }; +template<> struct make_index_sequence<0> : index_sequence<> {}; +template<> struct make_index_sequence<1> : index_sequence<0> {}; template using index_sequence_for = make_index_sequence; -/* -Implementation of two C++17 constructs: conjunction, negation. This is needed -to avoid evaluating all the traits in a condition -For example: not std::is_same::value and has_value_type::value -will not compile when T = void (on MSVC at least). Whereas -conjunction>, has_value_type>::value will -stop evaluating if negation<...>::value == false -Please note that those constructs must be used with caution, since symbols can -become very long quickly (which can slow down compilation and cause MSVC -internal compiler errors). Only use it when you have to (see example ahead). -*/ -template struct conjunction : std::true_type {}; -template struct conjunction : B1 {}; -template -struct conjunction : std::conditional, B1>::type {}; - -template struct negation : std::integral_constant < bool, !B::value > {}; - // dispatch utility (taken from ranges-v3) template struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; -////////////////// -// constructors // -////////////////// +template +constexpr T static_const::value; +} // namespace detail +} // namespace nlohmann -template struct external_constructor; +// #include -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept - { - j.m_type = value_t::boolean; - j.m_value = b; - j.assert_invariant(); - } -}; -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) - { - j.m_type = value_t::string; - j.m_value = s; - j.assert_invariant(); - } +#include // not +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval - template - static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) - { - j.m_type = value_t::string; - j.m_value = std::move(s); - j.assert_invariant(); - } -}; +// #include -template<> -struct external_constructor + +#include // random_access_iterator_tag + +// #include + + +namespace nlohmann { - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept - { - j.m_type = value_t::number_float; - j.m_value = val; - j.assert_invariant(); - } +namespace detail +{ +template struct make_void +{ + using type = void; }; +template using void_t = typename make_void::type; +} // namespace detail +} // namespace nlohmann -template<> -struct external_constructor +// #include + + +namespace nlohmann { - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept - { - j.m_type = value_t::number_unsigned; - j.m_value = val; - j.assert_invariant(); - } +namespace detail +{ +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; }; -template<> -struct external_constructor +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits { - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept - { - j.m_type = value_t::number_integer; - j.m_value = val; - j.assert_invariant(); - } }; -template<> -struct external_constructor +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types { - template - static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) - { - j.m_type = value_t::array; - j.m_value = arr; - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) - { - j.m_type = value_t::array; - j.m_value = std::move(arr); - j.assert_invariant(); - } - - template::value, - int> = 0> - static void construct(BasicJsonType& j, const CompatibleArrayType& arr) - { - using std::begin; - using std::end; - j.m_type = value_t::array; - j.m_value.array = j.template create(begin(arr), end(arr)); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, const std::vector& arr) - { - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->reserve(arr.size()); - for (bool x : arr) - { - j.m_value.array->push_back(x); - } - j.assert_invariant(); - } - - template::value, int> = 0> - static void construct(BasicJsonType& j, const std::valarray& arr) - { - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->resize(arr.size()); - std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); - j.assert_invariant(); - } }; -template<> -struct external_constructor +template +struct iterator_traits::value>> { - template - static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) - { - j.m_type = value_t::object; - j.m_value = obj; - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) - { - j.m_type = value_t::object; - j.m_value = std::move(obj); - j.assert_invariant(); - } - - template::value, int> = 0> - static void construct(BasicJsonType& j, const CompatibleObjectType& obj) - { - using std::begin; - using std::end; - - j.m_type = value_t::object; - j.m_value.object = j.template create(begin(obj), end(obj)); - j.assert_invariant(); - } + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; }; +} // namespace detail +} // namespace nlohmann +// #include -//////////////////////// -// has_/is_ functions // -//////////////////////// - -/*! -@brief Helper to determine whether there's a key_type for T. -This helper is used to tell associative containers apart from other containers -such as sequence containers. For instance, `std::map` passes the test as it -contains a `mapped_type`, whereas `std::vector` fails the test. -@sa http://stackoverflow.com/a/7728728/266378 -@since version 1.0.0, overworked in version 2.0.6 -*/ -#define NLOHMANN_JSON_HAS_HELPER(type) \ - template struct has_##type { \ - private: \ - template \ - static int detect(U &&); \ - static void detect(...); \ - public: \ - static constexpr bool value = \ - std::is_integral()))>::value; \ - } +// #include -NLOHMANN_JSON_HAS_HELPER(mapped_type); -NLOHMANN_JSON_HAS_HELPER(key_type); -NLOHMANN_JSON_HAS_HELPER(value_type); -NLOHMANN_JSON_HAS_HELPER(iterator); +// #include -#undef NLOHMANN_JSON_HAS_HELPER +#include -template -struct is_compatible_object_type_impl : std::false_type {}; +// #include -template -struct is_compatible_object_type_impl -{ - static constexpr auto value = - std::is_constructible::value and - std::is_constructible::value; -}; -template -struct is_compatible_object_type +// http://en.cppreference.com/w/cpp/experimental/is_detected +namespace nlohmann { - static auto constexpr value = is_compatible_object_type_impl < - conjunction>, - has_mapped_type, - has_key_type>::value, - typename BasicJsonType::object_t, CompatibleObjectType >::value; -}; - -template -struct is_basic_json_nested_type +namespace detail { - static auto constexpr value = std::is_same::value or - std::is_same::value or - std::is_same::value or - std::is_same::value; -}; - -template -struct is_compatible_array_type +struct nonesuch { - static auto constexpr value = - conjunction>, - negation>, - negation>, - negation>, - has_value_type, - has_iterator>::value; + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; }; -template -struct is_compatible_integer_type_impl : std::false_type {}; - -template -struct is_compatible_integer_type_impl +template class Op, + class... Args> +struct detector { - // is there an assert somewhere on overflows? - using RealLimits = std::numeric_limits; - using CompatibleLimits = std::numeric_limits; - - static constexpr auto value = - std::is_constructible::value and - CompatibleLimits::is_integer and - RealLimits::is_signed == CompatibleLimits::is_signed; + using value_t = std::false_type; + using type = Default; }; -template -struct is_compatible_integer_type +template class Op, class... Args> +struct detector>, Op, Args...> { - static constexpr auto value = - is_compatible_integer_type_impl < - std::is_integral::value and - not std::is_same::value, - RealIntegerType, CompatibleNumberIntegerType > ::value; + using value_t = std::true_type; + using type = Op; }; +template