MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
test_jsonutils.cpp File Reference
#include <cmath>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <catch2/catch_test_macros.hpp>
#include "mxl-internal/JsonUtils.hpp"
Include dependency graph for test_jsonutils.cpp:

Go to the source code of this file.

Classes

struct  JsonLimits
 Limits applied by parseJson(). More...

Functions

template<std::integral T>
T jsonToInteger (picojson::value const &value, std::string_view name)
std::string parseJson (picojson::value &out, std::string_view text, JsonLimits const &limits={})
 TEST_CASE ("jsonToInteger : converts whole numbers in range", "[json]")
 TEST_CASE ("jsonToInteger : rejects values that do not convert exactly", "[json]")
 TEST_CASE ("parseJson : accepts a valid document", "[json]")
 TEST_CASE ("parseJson : limits the container size", "[json]")
 TEST_CASE ("parseJson : limits the input size", "[json]")
 TEST_CASE ("parseJson : limits the nesting depth", "[json]")
 TEST_CASE ("parseJson : rejects duplicate keys", "[json]")
 TEST_CASE ("parseJson : rejects syntax errors and trailing content", "[json]")
 TEST_CASE ("parseJson : reports a number out of double range as an error", "[json]")

Function Documentation

◆ jsonToInteger()

template<std::integral T>
T mxl::lib::jsonToInteger ( picojson::value const & value,
std::string_view name )
inline

Convert a JSON number to the integer type T.

Converting a double that is outside the range of an integer type is undefined behavior in C++, so the value is checked before the conversion.

Parameters
valueThe JSON value.
nameThe field name, used in the error message.
Returns
The value as T.
Exceptions
std::invalid_argumentIf the value is not a number, not a whole number, or outside the range of T.

Definition at line 236 of file JsonUtils.hpp.

237 {
238 if (!value.is<double>())
239 {
240 throw std::invalid_argument{fmt::format("'{}' must be a number.", name)};
241 }
242
243 auto const number = value.get<double>();
244
245 // 2^digits is the first value past the range of T. It is exact as a double, while numeric_limits<T>::max() may
246 // round up to it.
247 auto const upper = std::ldexp(1.0, std::numeric_limits<T>::digits);
248 auto const lower = std::numeric_limits<T>::is_signed ? -upper : 0.0;
249 if ((std::trunc(number) != number) || (number < lower) || (number >= upper))
250 {
251 throw std::invalid_argument{fmt::format(
252 "'{}' must be a whole number between {} and {}, got {}.", name, std::numeric_limits<T>::min(), std::numeric_limits<T>::max(), number)};
253 }
254 return static_cast<T>(number);
255 }

◆ parseJson()

std::string mxl::lib::parseJson ( picojson::value & out,
std::string_view text,
JsonLimits const & limits = {} )
inline

Parse a JSON document with the limits in limits.

Unlike picojson::parse(value&, std::string const&), this rejects any content after the first value other than whitespace, and rejects objects with duplicate keys.

Parameters
outReceives the parsed value. Its content is unspecified on error.
textThe JSON document.
limitsThe limits to apply.
Returns
An empty string on success, otherwise a description of the error.

Definition at line 193 of file JsonUtils.hpp.

193 {})
194 {
195 if (text.size() > limits.maxInputSize)
196 {
197 return fmt::format("JSON input has {} bytes, the limit is {}.", text.size(), limits.maxInputSize);
198 }
199
200 auto limitError = std::string{};
201 auto syntaxError = std::string{};
202 auto ctx = detail::LimitedJsonParseContext{&out, limits, limitError, 0U};
203 auto const end = picojson::_parse(ctx, text.begin(), text.end(), &syntaxError);
204 if (!limitError.empty())
205 {
206 return limitError;
207 }
208 if (!syntaxError.empty())
209 {
210 return syntaxError;
211 }
212
213 auto const isWhitespace = [](char c) noexcept
214 {
215 return (c == ' ') || (c == '\t') || (c == '\n') || (c == '\r');
216 };
217 if (!std::all_of(end, text.end(), isWhitespace))
218 {
219 return "Unexpected content after the JSON value.";
220 }
221 return {};
222 }

◆ TEST_CASE() [1/9]

TEST_CASE ( "jsonToInteger : converts whole numbers in range" ,
"" [json] )

Definition at line 120 of file test_jsonutils.cpp.

120 : converts whole numbers in range", "[json]")
121{
122 REQUIRE(jsonToInteger<std::uint32_t>(number(0.0), "v") == 0U);
123 REQUIRE(jsonToInteger<std::uint32_t>(number(4294967295.0), "v") == UINT32_MAX);
124 REQUIRE(jsonToInteger<std::int64_t>(number(-9223372036854775808.0), "v") == INT64_MIN);
125 REQUIRE(jsonToInteger<std::int64_t>(number(-1001.0), "v") == -1001);
126 REQUIRE(jsonToInteger<std::uint64_t>(number(std::ldexp(1.0, 63)), "v") == (std::uint64_t{1} << 63U));
127}

◆ TEST_CASE() [2/9]

TEST_CASE ( "jsonToInteger : rejects values that do not convert exactly" ,
"" [json] )

Definition at line 129 of file test_jsonutils.cpp.

129 : rejects values that do not convert exactly", "[json]")
130{
131 REQUIRE_THROWS_AS(jsonToInteger<std::uint32_t>(number(1.5), "v"), std::invalid_argument);
132 REQUIRE_THROWS_AS(jsonToInteger<std::uint32_t>(number(-1.0), "v"), std::invalid_argument);
133 REQUIRE_THROWS_AS(jsonToInteger<std::uint32_t>(number(4294967296.0), "v"), std::invalid_argument);
134 REQUIRE_THROWS_AS(jsonToInteger<std::size_t>(number(1e300), "v"), std::invalid_argument);
135 REQUIRE_THROWS_AS(jsonToInteger<std::uint64_t>(number(std::ldexp(1.0, 64)), "v"), std::invalid_argument);
136 REQUIRE_THROWS_AS(jsonToInteger<std::int64_t>(number(std::ldexp(1.0, 63)), "v"), std::invalid_argument);
137 REQUIRE_THROWS_AS(jsonToInteger<std::int64_t>(number(-std::ldexp(1.0, 64)), "v"), std::invalid_argument);
138 REQUIRE_THROWS_AS(jsonToInteger<std::uint32_t>(picojson::value{"12"}, "v"), std::invalid_argument);
139 REQUIRE_THROWS_AS(jsonToInteger<std::uint32_t>(picojson::value{}, "v"), std::invalid_argument);
140}

◆ TEST_CASE() [3/9]

TEST_CASE ( "parseJson : accepts a valid document" ,
"" [json] )

Definition at line 48 of file test_jsonutils.cpp.

48 : accepts a valid document", "[json]")
49{
50 auto value = picojson::value{};
51 REQUIRE(parseJson(value,
52 R"( {"a": [1, "two", true, null], "b": {"c": 2.5}} )"
53 "\n\t")
54 .empty());
55 REQUIRE(value.is<picojson::object>());
56 auto const& root = value.get<picojson::object>();
57 REQUIRE(root.at("a").get<picojson::array>().size() == 4U);
58 REQUIRE(root.at("b").get<picojson::object>().at("c").get<double>() == 2.5);
59}

◆ TEST_CASE() [4/9]

TEST_CASE ( "parseJson : limits the container size" ,
"" [json] )

Definition at line 95 of file test_jsonutils.cpp.

95 : limits the container size", "[json]")
96{
97 auto const limits = JsonLimits{};
98 auto value = picojson::value{};
99 REQUIRE(parseJson(value, arrayOf(limits.maxContainerSize)).empty());
100 REQUIRE_FALSE(parseJson(value, arrayOf(limits.maxContainerSize + 1U)).empty());
101 REQUIRE(parseJson(value, objectOf(limits.maxContainerSize)).empty());
102 REQUIRE_FALSE(parseJson(value, objectOf(limits.maxContainerSize + 1U)).empty());
103}
std::size_t size() const noexcept
Returns the total number of writers that are registered in the DomainWatcher.

◆ TEST_CASE() [5/9]

TEST_CASE ( "parseJson : limits the input size" ,
"" [json] )

Definition at line 70 of file test_jsonutils.cpp.

70 : limits the input size", "[json]")
71{
72 auto const limits = JsonLimits{.maxInputSize = 16U};
73 auto value = picojson::value{};
74 REQUIRE(parseJson(value, R"({"a":"12345678"})", limits).empty()); // 16 bytes
75 REQUIRE_FALSE(parseJson(value, R"({"a":"123456789"})", limits).empty());
76
77 // The default limit rejects the 4 MB description string accepted in the security audit.
78 auto const large = R"({"description":")" + std::string(4U * 1024U * 1024U, 'x') + R"("})";
79 REQUIRE_FALSE(parseJson(value, large).empty());
80}
std::string parseJson(picojson::value &out, std::string_view text, JsonLimits const &limits={})

◆ TEST_CASE() [6/9]

TEST_CASE ( "parseJson : limits the nesting depth" ,
"" [json] )

Definition at line 82 of file test_jsonutils.cpp.

82 : limits the nesting depth", "[json]")
83{
84 auto const limits = JsonLimits{};
85 auto value = picojson::value{};
86 REQUIRE(parseJson(value, nestedArrays(limits.maxDepth)).empty());
87 REQUIRE_FALSE(parseJson(value, nestedArrays(limits.maxDepth + 1U)).empty());
88 REQUIRE_FALSE(parseJson(value, R"({"a":)" + nestedArrays(limits.maxDepth) + "}").empty());
89
90 // Deep enough to overflow the stack if picojson recursed into all of it.
91 auto const deep = JsonLimits{.maxInputSize = 1U << 22U};
92 REQUIRE_FALSE(parseJson(value, nestedArrays(1U << 20U), deep).empty());
93}

◆ TEST_CASE() [7/9]

TEST_CASE ( "parseJson : rejects duplicate keys" ,
"" [json] )

Definition at line 105 of file test_jsonutils.cpp.

105 : rejects duplicate keys", "[json]")
106{
107 auto value = picojson::value{};
108 REQUIRE_FALSE(parseJson(value, R"({"a":1,"a":2})").empty());
109 REQUIRE_FALSE(parseJson(value, R"({"b":{"a":1,"a":1}})").empty());
110 REQUIRE(parseJson(value, R"({"a":{"a":1}})").empty());
111}

◆ TEST_CASE() [8/9]

TEST_CASE ( "parseJson : rejects syntax errors and trailing content" ,
"" [json] )

Definition at line 61 of file test_jsonutils.cpp.

61 : rejects syntax errors and trailing content", "[json]")
62{
63 auto value = picojson::value{};
64 REQUIRE_FALSE(parseJson(value, "{ this is not json").empty());
65 REQUIRE_FALSE(parseJson(value, "").empty());
66 REQUIRE_FALSE(parseJson(value, "{} {}").empty());
67 REQUIRE_FALSE(parseJson(value, "{\"a\":1} garbage").empty());
68}

◆ TEST_CASE() [9/9]

TEST_CASE ( "parseJson : reports a number out of double range as an error" ,
"" [json] )

Definition at line 113 of file test_jsonutils.cpp.

113 : reports a number out of double range as an error", "[json]")
114{
115 auto value = picojson::value{};
116 REQUIRE_FALSE(parseJson(value, "[1e400]").empty());
117 REQUIRE_FALSE(parseJson(value, "[-1e400]").empty());
118}