Skip to content

Commit 181ac51

Browse files
reject non-integer JSON numbers where an integer is expected (#1240)
nlohmann's get<int>() converts with a plain static_cast, so JSON numbers read as integers were truncated (2.5 -> 2), wrapped (5000000000, or a Groot2 hook uid + 65536 landing on another node) or cast out of range (1e300, undefined behavior). Read them through the internal helper BT::details::JsonToInteger<T>, which rejects lossy values with a RuntimeError and accepts in-range floats with no fractional part (100.0), like Any::cast<T>(). Applied to JSON blackboard import, json: vector<int> ports, substitution rule async_delay, and the Groot2 hook requests. Behavior change: int-vector elements, async_delay and Groot2 hook fields that are fractional, NaN, boolean or out of range now throw instead of being silently truncated or wrapped.
1 parent fca5e6c commit 181ac51

9 files changed

Lines changed: 218 additions & 13 deletions

File tree

‎include/behaviortree_cpp/json_export.h‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
#include "behaviortree_cpp/basic_types.h"
44
#include "behaviortree_cpp/utils/safe_any.hpp"
55

6+
#include <limits>
7+
#include <type_traits>
8+
69
// Use the version of nlohmann::json embedded in BT.CPP,
710
// or the system one if BT.CPP was built with USE_VENDORED_JSON=OFF
811
#ifdef BTCPP_SYSTEM_JSON
@@ -250,6 +253,67 @@ inline void RegisterJsonDefinition()
250253
JsonExporter::get().addConverter<T>();
251254
}
252255

256+
namespace details
257+
{
258+
/**
259+
* @brief Read a JSON number that must be representable as the integer T.
260+
* Internal helper, not part of the public API.
261+
*
262+
* json.get<T>() converts a floating point value or an out-of-range integer
263+
* with a plain static_cast, which truncates, wraps, or (for a value outside
264+
* the range of T) is undefined behavior. This throws RuntimeError instead.
265+
* A floating point value with no fractional part (e.g. 100.0) is accepted,
266+
* like Any::cast<T>() does.
267+
*/
268+
template <typename T>
269+
[[nodiscard]] inline T JsonToInteger(const nlohmann::json& value)
270+
{
271+
static_assert(std::is_integral_v<T> && !std::is_same_v<T, bool>);
272+
const auto not_an_integer = [&value]() {
273+
return RuntimeError(StrCat("JSON value [", value.dump(),
274+
"] is not an integer of type ", BT::demangle(typeid(T))));
275+
};
276+
if(value.is_number_unsigned())
277+
{
278+
const auto number = value.get<uint64_t>();
279+
if(number <= static_cast<uint64_t>(std::numeric_limits<T>::max()))
280+
{
281+
return static_cast<T>(number);
282+
}
283+
}
284+
else if(value.is_number_integer())
285+
{
286+
const auto number = value.get<int64_t>();
287+
if constexpr(std::is_signed_v<T>)
288+
{
289+
if(number >= static_cast<int64_t>(std::numeric_limits<T>::min()) &&
290+
number <= static_cast<int64_t>(std::numeric_limits<T>::max()))
291+
{
292+
return static_cast<T>(number);
293+
}
294+
}
295+
else if(number >= 0 && static_cast<uint64_t>(number) <= std::numeric_limits<T>::max())
296+
{
297+
return static_cast<T>(number);
298+
}
299+
}
300+
else if(value.is_number_float())
301+
{
302+
const auto number = value.get<double>();
303+
try
304+
{
305+
SafeAny::details::checkTruncation<double, T>(number);
306+
return static_cast<T>(number);
307+
}
308+
catch(const std::runtime_error&)
309+
{
310+
throw not_an_integer();
311+
}
312+
}
313+
throw not_an_integer();
314+
}
315+
} // namespace details
316+
253317
} // namespace BT
254318

255319
//------------------------------------------------

‎include/behaviortree_cpp/loggers/groot2_protocol.h‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#pragma once
22

33
#include "behaviortree_cpp/basic_types.h"
4+
#include "behaviortree_cpp/json_export.h"
45
#ifdef BTCPP_SYSTEM_JSON
56
#include <nlohmann/json.hpp>
67
#else
@@ -256,10 +257,11 @@ inline void to_json(nlohmann::json& js, const Hook& bp)
256257
inline void from_json(const nlohmann::json& js, Hook& bp)
257258
{
258259
js.at("enabled").get_to(bp.enabled);
259-
js.at("uid").get_to(bp.node_uid);
260+
bp.node_uid = BT::details::JsonToInteger<uint16_t>(js.at("uid"));
260261
js.at("once").get_to(bp.remove_when_done);
261-
bp.mode = static_cast<Hook::Mode>(js.at("mode").get<int>());
262-
bp.position = static_cast<Hook::Position>(js.at("position").get<int>());
262+
bp.mode = static_cast<Hook::Mode>(BT::details::JsonToInteger<int>(js.at("mode")));
263+
bp.position = static_cast<Hook::Position>(BT::details::JsonToInteger<int>(js.at("positi"
264+
"on")));
263265

264266
const std::string desired_value = js.at("desired_status").get<std::string>();
265267
bp.desired_status = convertFromString<NodeStatus>(desired_value);

‎src/basic_types.cpp‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,18 @@ std::vector<int> convertFromString<std::vector<int>>(StringView str)
318318
if(StartWith(str, "json:"))
319319
{
320320
str.remove_prefix(5);
321-
return nlohmann::json::parse(str).get<std::vector<int>>();
321+
const auto json = nlohmann::json::parse(str);
322+
if(!json.is_array())
323+
{
324+
throw RuntimeError(StrCat("Can't convert string [", str, "] to std::vector<int>"));
325+
}
326+
std::vector<int> output;
327+
output.reserve(json.size());
328+
for(const auto& element : json)
329+
{
330+
output.push_back(details::JsonToInteger<int>(element));
331+
}
332+
return output;
322333
}
323334
auto parts = splitString(str, ';');
324335
std::vector<int> output;

‎src/bt_factory.cpp‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
#include "tinyxml2.h"
1616

17+
#include "behaviortree_cpp/json_export.h"
1718
#include "behaviortree_cpp/utils/shared_library.h"
1819
#include "behaviortree_cpp/utils/wildcards.hpp"
1920
#include "behaviortree_cpp/xml_parsing.h"
@@ -570,7 +571,8 @@ void BehaviorTreeFactory::loadSubstitutionRuleFromJSON(const std::string& json_t
570571
if(test_config.contains("async_delay"))
571572
{
572573
config.async_delay =
573-
std::chrono::milliseconds(test_config["async_delay"].get<int>());
574+
std::chrono::milliseconds(details::JsonToInteger<int>(test_config["async_"
575+
"delay"]));
574576
}
575577
if(test_config.contains("post_script"))
576578
{

‎src/json_export.cpp‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,14 @@ JsonExporter::ExpectedEntry JsonExporter::fromJson(const nlohmann::json& source)
116116
}
117117
if(first_element.is_number_integer())
118118
{
119-
return Entry{ BT::Any(source.get<std::vector<int>>()),
120-
BT::TypeInfo::Create<std::vector<int>>() };
119+
// the type comes from the first element only: check every element
120+
std::vector<int> values;
121+
values.reserve(source.size());
122+
for(const auto& element : source)
123+
{
124+
values.push_back(details::JsonToInteger<int>(element));
125+
}
126+
return Entry{ BT::Any(values), BT::TypeInfo::Create<std::vector<int>>() };
121127
}
122128
if(first_element.is_number_float())
123129
{

‎src/loggers/groot2_publisher.cpp‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -358,8 +358,9 @@ void Groot2Publisher::serverLoop()
358358
}
359359

360360
auto InsertHook = [this](nlohmann::json const& json) {
361-
uint16_t const node_uid = json.at("uid").get<uint16_t>();
362-
Position const pos = static_cast<Position>(json.at("position").get<int>());
361+
uint16_t const node_uid = details::JsonToInteger<uint16_t>(json.at("uid"));
362+
int const position = details::JsonToInteger<int>(json.at("position"));
363+
Position const pos = static_cast<Position>(position);
363364

364365
if(auto hook = getHook(pos, node_uid))
365366
{
@@ -409,9 +410,10 @@ void Groot2Publisher::serverLoop()
409410
}
410411

411412
auto json = nlohmann::json::parse(requestMsg[1].to_string());
412-
const uint16_t node_uid = json.at("uid").get<uint16_t>();
413+
const uint16_t node_uid = details::JsonToInteger<uint16_t>(json.at("uid"));
413414
const std::string status_str = json.at("desired_status").get<std::string>();
414-
auto position = static_cast<Position>(json.at("position").get<int>());
415+
auto position =
416+
static_cast<Position>(details::JsonToInteger<int>(json.at("position")));
415417
const bool remove = json.at("remove_when_done").get<bool>();
416418

417419
NodeStatus desired_status = NodeStatus::SKIPPED;
@@ -450,8 +452,9 @@ void Groot2Publisher::serverLoop()
450452
}
451453

452454
auto json = nlohmann::json::parse(requestMsg[1].to_string());
453-
const uint16_t node_uid = json.at("uid").get<uint16_t>();
454-
auto position = static_cast<Position>(json.at("position").get<int>());
455+
const uint16_t node_uid = details::JsonToInteger<uint16_t>(json.at("uid"));
456+
auto position =
457+
static_cast<Position>(details::JsonToInteger<int>(json.at("position")));
455458

456459
if(!removeHook(position, node_uid))
457460
{

‎tests/gtest_groot2_publisher_integration.cpp‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,40 @@ TEST(Groot2PublisherIntegration, PostHookRunsAfterNodeAndCanBeRemoved)
161161
EXPECT_EQ(tick_count, 2);
162162
}
163163

164+
TEST(Groot2PublisherIntegration, HookRequestRejectsNonIntegerUid)
165+
{
166+
BT::BehaviorTreeFactory factory;
167+
factory.registerSimpleAction("CountAction",
168+
[](BT::TreeNode&) { return BT::NodeStatus::SUCCESS; });
169+
auto tree = factory.createTreeFromText(kHookTreeXml);
170+
auto [publisher, port] = Groot2Test::makePublisher(tree);
171+
Groot2Test::Client client(port);
172+
const auto uid = tree.rootNode()->UID();
173+
174+
// get<uint16_t>() used to wrap uid + 65536 and truncate uid + 0.5 to the uid
175+
// of the node, and to cast 1e300 out of range (undefined behavior).
176+
for(const nlohmann::json bad_uid :
177+
{ nlohmann::json(uid + 65536), nlohmann::json(uid + 0.5), nlohmann::json(1e300) })
178+
{
179+
auto hook = Groot2Test::makeHook(uid, BT::Monitor::Hook::Mode::REPLACE,
180+
BT::Monitor::Hook::Position::PRE);
181+
hook["uid"] = bad_uid;
182+
auto reply = client.rawRequest(BT::Monitor::RequestType::HOOK_INSERT, hook.dump());
183+
ASSERT_EQ(reply.size(), 2);
184+
EXPECT_EQ(reply[0].to_string(), "error") << bad_uid;
185+
186+
const auto remove = nlohmann::json{ { "uid", bad_uid }, { "position", 0 } };
187+
reply = client.rawRequest(BT::Monitor::RequestType::HOOK_REMOVE, remove.dump());
188+
ASSERT_EQ(reply.size(), 2);
189+
EXPECT_EQ(reply[0].to_string(), "error") << bad_uid;
190+
}
191+
192+
auto dump_reply = client.request(BT::Monitor::RequestType::HOOKS_DUMP);
193+
ASSERT_EQ(dump_reply.size(), 2);
194+
EXPECT_TRUE(nlohmann::json::parse(dump_reply[1].to_string()).empty());
195+
EXPECT_EQ(tree.tickExactlyOnce(), BT::NodeStatus::SUCCESS);
196+
}
197+
164198
TEST(Groot2PublisherIntegration, MalformedRequestDoesNotTerminateServer)
165199
{
166200
::testing::FLAGS_gtest_death_test_style = "threadsafe";

‎tests/gtest_json.cpp‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,69 @@ TEST_F(JsonTest, VectorInteger)
271271
}
272272
}
273273

274+
TEST_F(JsonTest, IntegerValuesAreRangeChecked)
275+
{
276+
using nlohmann::json;
277+
BT::JsonExporter& exporter = BT::JsonExporter::get();
278+
279+
ASSERT_EQ(BT::details::JsonToInteger<int>(json(-7)), -7);
280+
ASSERT_EQ(BT::details::JsonToInteger<uint16_t>(json(65535)), 65535);
281+
ASSERT_EQ(BT::details::JsonToInteger<int64_t>(json(INT64_MIN)), INT64_MIN);
282+
ASSERT_EQ(BT::details::JsonToInteger<uint64_t>(json(UINT64_MAX)), UINT64_MAX);
283+
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<uint16_t>(json(65536)),
284+
BT::RuntimeError);
285+
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<uint16_t>(json(-1)),
286+
BT::RuntimeError);
287+
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<int>(json(2.5)),
288+
BT::RuntimeError);
289+
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<int>(json(1e300)),
290+
BT::RuntimeError);
291+
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<int>(json(true)),
292+
BT::RuntimeError);
293+
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<int>(json(std::nan(""))),
294+
BT::RuntimeError);
295+
// A floating point value with no fractional part converts, like Any::cast<int>()
296+
ASSERT_EQ(BT::details::JsonToInteger<int>(json(100.0)), 100);
297+
ASSERT_EQ(BT::details::JsonToInteger<int>(json(-3.0)), -3);
298+
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<uint16_t>(json(65536.0)),
299+
BT::RuntimeError);
300+
{
301+
auto result = exporter.fromJson(json::parse("[1, 2.0]"));
302+
ASSERT_TRUE(result);
303+
ASSERT_EQ(result->first.cast<std::vector<int>>(), (std::vector<int>{ 1, 2 }));
304+
}
305+
306+
// The type of the array is taken from the first element. The other elements
307+
// used to be truncated, wrapped, or cast out of range (undefined behavior).
308+
for(const char* text :
309+
{ "[1, 2.5]", "[1, 1e300]", "[1, 5000000000]", "[1, -3000000000]" })
310+
{
311+
ASSERT_THROW(std::ignore = exporter.fromJson(json::parse(text)), BT::RuntimeError)
312+
<< text;
313+
auto bb = BT::Blackboard::create();
314+
ASSERT_THROW(BT::ImportBlackboardFromJSON(
315+
json::parse(R"({"v":)" + std::string(text) + "}"), *bb),
316+
BT::RuntimeError)
317+
<< text;
318+
}
319+
auto result = exporter.fromJson(json::parse("[1, -2, 2147483647]"));
320+
ASSERT_TRUE(result) << result.error();
321+
ASSERT_EQ(result->first.cast<std::vector<int>>(),
322+
(std::vector<int>{ 1, -2, 2147483647 }));
323+
324+
// Same for the "json:" prefix of a std::vector<int> port
325+
ASSERT_EQ(BT::convertFromString<std::vector<int>>("json:[3, -4]"),
326+
(std::vector<int>{ 3, -4 }));
327+
ASSERT_THROW(std::ignore = BT::convertFromString<std::vector<int>>("json:[1e300]"),
328+
BT::RuntimeError);
329+
ASSERT_THROW(std::ignore = BT::convertFromString<std::vector<int>>("json:[1.5]"),
330+
BT::RuntimeError);
331+
ASSERT_THROW(std::ignore = BT::convertFromString<std::vector<int>>("json:[4294967297]"),
332+
BT::RuntimeError);
333+
ASSERT_THROW(std::ignore = BT::convertFromString<std::vector<int>>("json:{\"a\":1}"),
334+
BT::RuntimeError);
335+
}
336+
274337
TEST_F(JsonTest, VectorSring)
275338
{
276339
BT::JsonExporter& exporter = BT::JsonExporter::get();

‎tests/gtest_substitution.cpp‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,26 @@ TEST(Substitution, ParserRejectsMissingReturnStatusAndScript)
133133
ASSERT_THROW(factory.loadSubstitutionRuleFromJSON(invalid_json), RuntimeError);
134134
}
135135

136+
TEST(Substitution, ParserRejectsNonIntegerAsyncDelay)
137+
{
138+
// async_delay used to be read with get<int>(), which truncates a real
139+
// number and casts an out-of-range one to int (undefined behavior).
140+
for(const char* delay : { "1e300", "2.5", "5000000000" })
141+
{
142+
const std::string json_text = std::string(R"(
143+
{
144+
"TestNodeConfigs": {
145+
"Delayed": { "return_status": "SUCCESS", "async_delay": )") +
146+
delay + R"( }
147+
},
148+
"SubstitutionRules": { "actionA": "Delayed" }
149+
})";
150+
151+
BehaviorTreeFactory factory;
152+
ASSERT_THROW(factory.loadSubstitutionRuleFromJSON(json_text), RuntimeError) << delay;
153+
}
154+
}
155+
136156
TEST(Substitution, ScriptedReturnStatusFromJson)
137157
{
138158
static const char* xml_text = R"(

0 commit comments

Comments
 (0)