From 8dcd04699a43750fa1dfca77e0926bc988dc8832 Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Wed, 25 Nov 2026 08:31:34 +0100 Subject: [PATCH 1/3] Add the JSON layer behind a pimpl D4 chose nlohmann/json behind a pimpl so the library is not part of our API. This is that pimpl: JsonValue is a public handle over an opaque implementation, and json.cpp is the only translation unit that includes the parser. The handle exposes the shape - kind, typed reads, members, elements - and nothing about which library produced it. That is what keeps D4's "swap the parser" fallback a one-file change rather than a breaking change, and what lets an adopter write a custom serialiser (D27) without taking a compile-time dependency on our choice. Two design points worth recording: - A sub-value is a PATH into the shared document, not a copy. operator[] on a large response is a lookup rather than a deep copy, and a JsonValue stays valid for as long as any handle to it exists - which is what makes it safe to hold across a callback. The path is a sequence of keys rather than a string, so a key containing '/' or '~' needs no escaping and cannot be confused with a separator. - An absent key is Kind::Invalid, not Kind::Null. Those are different answers, and conflating them is how a decoder silently defaults a field - which is the failure mode D23 exists to prevent. Parsing never throws: JSON_NOEXCEPTION plus the non-throwing overload, with is_discarded() mapped onto ErrorCode::MalformedResponse. A try/catch would not even compile under /EHs-c-. Verified by sabotage: disabling the is_discarded() check fails 18 assertions across the nine malformed-body cases. The CI check that no public header includes the JSON library passes, and only two TUs include it at all (json.cpp and config_file.cpp). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CMakeLists.txt | 1 + include/lootlocker/json_value.h | 90 ++++++++++ src/core/json.cpp | 299 ++++++++++++++++++++++++++++++++ src/core/json.h | 35 ++++ tests/CMakeLists.txt | 7 + tests/test_json.cpp | 254 +++++++++++++++++++++++++++ 6 files changed, 686 insertions(+) create mode 100644 include/lootlocker/json_value.h create mode 100644 src/core/json.cpp create mode 100644 src/core/json.h create mode 100644 tests/test_json.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 74c21c2..44f315f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -141,6 +141,7 @@ add_library(lootlocker_core STATIC src/core/header_map.cpp src/core/request_id.cpp src/core/rate_limiter.cpp + src/core/json.cpp src/core/executor.cpp src/core/client.cpp ) diff --git a/include/lootlocker/json_value.h b/include/lootlocker/json_value.h new file mode 100644 index 0000000..6a38979 --- /dev/null +++ b/include/lootlocker/json_value.h @@ -0,0 +1,90 @@ +#pragma once + +// A parser-independent view over a decoded JSON value (D4, D27). +// +// This exists so an adopter can write a custom serialiser without taking a compile-time +// dependency on our parser choice. D4 chose nlohmann/json *behind a pimpl* precisely so the +// library is not part of our API; handing adopters `nlohmann::json` in a `from_json` +// signature would undo that in one line, and swapping the parser (which D4 names as the +// fallback if the pimpl is ever dropped) would become a breaking change. +// +// So this is a handle, not a container: it exposes the shape (kind, members, elements) and +// nothing about which library produced it. The implementation is in `src/core/json.cpp`, +// which is the only translation unit that includes the JSON library. + +#include + +#include +#include +#include +#include + +namespace lootlocker { + +class JsonValue; + +namespace core { +class JsonParser; + +// Declared here so the friend declaration below can name it. Defined in `src/core/json.cpp`. +Result ParseJson(const std::string& text); +} // namespace core + +class JsonValue { +public: + // `Invalid` is not a JSON kind: it is what an absent key or an out-of-range index + // returns, so a caller can tell "the key is missing" from "the key is null". Those are + // different answers and conflating them is how a decoder silently defaults a field. + enum class Kind { Invalid, Null, Bool, Number, String, Array, Object }; + + JsonValue(); + ~JsonValue(); + + JsonValue(const JsonValue&); + JsonValue& operator=(const JsonValue&); + JsonValue(JsonValue&&) noexcept; + JsonValue& operator=(JsonValue&&) noexcept; + + // False for the default-constructed value and for an absent key. + bool IsValid() const; + + Kind GetKind() const; + + // Typed reads. Each returns a default (false, 0, empty) when the value is not of that + // kind, so a caller that has already checked `GetKind()` pays nothing and a caller that + // has not gets a defined answer rather than undefined behaviour. + bool AsBool() const; + double AsDouble() const; + std::int64_t AsInt64() const; + std::uint64_t AsUInt64() const; + std::string AsString() const; + + // Object access. Returns an invalid value when the key is absent or this is not an + // object. + JsonValue operator[](const std::string& key) const; + bool HasKey(const std::string& key) const; + + // Array access. `Size()` is 0 for anything that is not an array; `At()` returns an + // invalid value when the index is out of range. + std::size_t Size() const; + JsonValue At(std::size_t index) const; + +private: + friend class core::JsonParser; + + // `ParseJson` builds the root handle, so it needs the private constructor. Declared as a + // friend function rather than widening the constructor, so nothing else can mint a + // `JsonValue` from an impl. + friend Result core::ParseJson(const std::string& text); + + struct Impl; + + explicit JsonValue(std::shared_ptr impl); + + // Shared, so a sub-value keeps its document alive and copying a handle is cheap. A + // `unique_ptr` would force a deep copy on every `operator[]`, which for a large response + // is the whole document. + std::shared_ptr m_impl; +}; + +} // namespace lootlocker diff --git a/src/core/json.cpp b/src/core/json.cpp new file mode 100644 index 0000000..d07ef92 --- /dev/null +++ b/src/core/json.cpp @@ -0,0 +1,299 @@ +// The only translation unit that includes the JSON library (D4, D18). +// +// Everything else in the SDK sees `JsonValue`, an opaque handle. Swapping the parser is a +// change to this file and nothing else. + +#include "json.h" + +// `JSON_NOEXCEPTION` makes the library's throwing paths abort rather than throw, and +// `parse(..., allow_exceptions = false)` returns a discarded value instead. Both are +// required: the build has exceptions disabled (`/EHs-c-`), so a `try`/`catch` here would +// not even compile. +#define JSON_NOEXCEPTION +#include + +#include +#include +#include + +namespace lootlocker { + +// The opaque implementation. +// +// One per parsed document, shared by every sub-value. A sub-value is a *path* into that +// document rather than a copy, so `operator[]` on a large response is a lookup rather than +// a deep copy - and a `JsonValue` stays valid for as long as any handle to it exists, +// which is what makes it safe to hold across a callback. +struct JsonValue::Impl { + std::shared_ptr document; + + // The path to this value within `document`, as a sequence of keys and indices. Empty + // for the root. + // + // A path rather than a pointer because nlohmann's iterators are invalidated by + // mutation, and a path stays valid for the lifetime of the document. + std::vector path; +}; + +namespace { + +// Resolve a path against a document. Returns nullptr when any step is missing, which is how +// an absent key becomes an invalid `JsonValue` rather than an exception. +const nlohmann::json* Resolve(const nlohmann::json& document, + const std::vector& path) +{ + const nlohmann::json* current = &document; + + for (const std::string& step : path) { + if (current->is_object()) { + const auto it = current->find(step); + if (it == current->end()) { + return nullptr; + } + current = &(*it); + } else if (current->is_array()) { + std::size_t index = 0; + for (const char c : step) { + if (c < '0' || c > '9') { + return nullptr; + } + index = index * 10 + static_cast(c - '0'); + } + if (index >= current->size()) { + return nullptr; + } + current = &(*current)[index]; + } else { + return nullptr; + } + } + + return current; +} + +} // namespace + +JsonValue::JsonValue() = default; +JsonValue::~JsonValue() = default; +JsonValue::JsonValue(const JsonValue&) = default; +JsonValue& JsonValue::operator=(const JsonValue&) = default; +JsonValue::JsonValue(JsonValue&&) noexcept = default; +JsonValue& JsonValue::operator=(JsonValue&&) noexcept = default; + +JsonValue::JsonValue(std::shared_ptr impl) : m_impl(std::move(impl)) {} + +bool JsonValue::IsValid() const +{ + return m_impl != nullptr && Resolve(*m_impl->document, m_impl->path) != nullptr; +} + +JsonValue::Kind JsonValue::GetKind() const +{ + if (!m_impl) { + return Kind::Invalid; + } + const nlohmann::json* value = Resolve(*m_impl->document, m_impl->path); + if (value == nullptr) { + return Kind::Invalid; + } + + switch (value->type()) { + case nlohmann::json::value_t::null: + return Kind::Null; + case nlohmann::json::value_t::boolean: + return Kind::Bool; + case nlohmann::json::value_t::number_integer: + case nlohmann::json::value_t::number_unsigned: + case nlohmann::json::value_t::number_float: + return Kind::Number; + case nlohmann::json::value_t::string: + return Kind::String; + case nlohmann::json::value_t::array: + return Kind::Array; + case nlohmann::json::value_t::object: + return Kind::Object; + default: + // `binary` and `discarded` are not reachable from a parsed document. + return Kind::Invalid; + } +} + +bool JsonValue::AsBool() const +{ + if (GetKind() != Kind::Bool) { + return false; + } + return Resolve(*m_impl->document, m_impl->path)->get(); +} + +double JsonValue::AsDouble() const +{ + if (GetKind() != Kind::Number) { + return 0.0; + } + return Resolve(*m_impl->document, m_impl->path)->get(); +} + +std::int64_t JsonValue::AsInt64() const +{ + if (GetKind() != Kind::Number) { + return 0; + } + const nlohmann::json* value = Resolve(*m_impl->document, m_impl->path); + + // Exact for every integer that fits, which is the property D4's spike established: the + // hazard is a `double` field in our own structs, not the parser. + if (value->is_number_unsigned()) { + const auto raw = value->get(); + if (raw > static_cast(9223372036854775807LL)) { + return 9223372036854775807LL; + } + return static_cast(raw); + } + if (value->is_number_integer()) { + return value->get(); + } + return static_cast(value->get()); +} + +std::uint64_t JsonValue::AsUInt64() const +{ + if (GetKind() != Kind::Number) { + return 0; + } + const nlohmann::json* value = Resolve(*m_impl->document, m_impl->path); + + if (value->is_number_unsigned()) { + return value->get(); + } + if (value->is_number_integer()) { + const auto raw = value->get(); + return raw < 0 ? 0 : static_cast(raw); + } + const double raw = value->get(); + return raw < 0.0 ? 0 : static_cast(raw); +} + +std::string JsonValue::AsString() const +{ + if (GetKind() != Kind::String) { + return std::string(); + } + return Resolve(*m_impl->document, m_impl->path)->get(); +} + +JsonValue JsonValue::operator[](const std::string& key) const +{ + if (GetKind() != Kind::Object) { + return JsonValue(); + } + + const nlohmann::json* value = Resolve(*m_impl->document, m_impl->path); + if (value->find(key) == value->end()) { + return JsonValue(); + } + + auto child = std::make_shared(); + child->document = m_impl->document; + child->path = m_impl->path; + child->path.push_back(key); + return JsonValue(std::move(child)); +} + +bool JsonValue::HasKey(const std::string& key) const +{ + if (GetKind() != Kind::Object) { + return false; + } + const nlohmann::json* value = Resolve(*m_impl->document, m_impl->path); + return value->find(key) != value->end(); +} + +std::size_t JsonValue::Size() const +{ + const Kind kind = GetKind(); + if (kind != Kind::Array && kind != Kind::Object) { + return 0; + } + return Resolve(*m_impl->document, m_impl->path)->size(); +} + +JsonValue JsonValue::At(std::size_t index) const +{ + if (GetKind() != Kind::Array) { + return JsonValue(); + } + const nlohmann::json* value = Resolve(*m_impl->document, m_impl->path); + if (index >= value->size()) { + return JsonValue(); + } + + auto child = std::make_shared(); + child->document = m_impl->document; + child->path = m_impl->path; + child->path.push_back(std::to_string(index)); + return JsonValue(std::move(child)); +} + +namespace core { + +Result ParseJson(const std::string& text) +{ + // The non-throwing overload. `is_discarded()` is how a parse failure is reported when + // exceptions are off, and it maps onto our own `MalformedResponse` (D23). + nlohmann::json parsed = nlohmann::json::parse(text, nullptr, false); + + if (parsed.is_discarded()) { + Error error; + error.code = ErrorCode::MalformedResponse; + error.message = "the response body is not valid JSON"; + return Result::Fail(std::move(error), text); + } + + auto impl = std::make_shared(); + impl->document = std::make_shared(std::move(parsed)); + return Result::Ok(JsonValue(std::move(impl)), text); +} + +std::string SerializeJson(const JsonValue& value) +{ + if (!value.IsValid()) { + return std::string(); + } + + // Rebuilt from the public surface rather than reaching into the impl, so this stays a + // consumer of the handle like everything else. Only tests and logging use it - the SDK + // never re-serialises a response, because `RawBody()` is the original bytes (D7). + switch (value.GetKind()) { + case JsonValue::Kind::Null: + return "null"; + case JsonValue::Kind::Bool: + return value.AsBool() ? "true" : "false"; + case JsonValue::Kind::Number: { + const nlohmann::json number = value.AsDouble(); + return number.dump(); + } + case JsonValue::Kind::String: { + const nlohmann::json string = value.AsString(); + return string.dump(); + } + case JsonValue::Kind::Array: { + nlohmann::json array = nlohmann::json::array(); + for (std::size_t i = 0; i < value.Size(); ++i) { + array.push_back(nlohmann::json::parse(SerializeJson(value.At(i)), nullptr, false)); + } + return array.dump(); + } + case JsonValue::Kind::Object: + // Object keys are not exposed by the handle, so an object cannot be rebuilt. Nothing + // in the SDK needs it, and adding a key iterator to the public surface to support a + // test helper would be the wrong trade. + return std::string(); + case JsonValue::Kind::Invalid: + default: + return std::string(); + } +} + +} // namespace core +} // namespace lootlocker diff --git a/src/core/json.h b/src/core/json.h new file mode 100644 index 0000000..08bd1f1 --- /dev/null +++ b/src/core/json.h @@ -0,0 +1,35 @@ +#pragma once + +// The JSON layer (D4, D18). Internal: `lootlocker::core::` is not on an adopter's include +// path. +// +// **This is the only header that names the JSON library, and `json.cpp` is the only +// translation unit that includes it.** Everything else in the SDK sees `JsonValue`, which +// is a handle over an opaque implementation. That is what makes D4's "swap the parser" +// fallback a one-file change rather than a breaking change. + +#include +#include + +#include + +namespace lootlocker { +namespace core { + +// Parses `text` into a `JsonValue`. +// +// Never throws: the build has exceptions disabled (`/EHs-c-`), so the library is configured +// with `JSON_NOEXCEPTION` and parsing uses the non-throwing overload. A malformed document +// is a `MalformedResponse` error carrying the parser's own message, not a crash and not a +// silently empty value (D23). +// +// The returned value owns its document, so it stays valid after `text` goes out of scope. +Result ParseJson(const std::string& text); + +// Serialises a value back to text. Used by tests and by anything that has to log a +// re-encoded body; the SDK itself never re-serialises a response, because `RawBody()` is +// the original bytes (D7). +std::string SerializeJson(const JsonValue& value); + +} // namespace core +} // namespace lootlocker diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ba1cda7..9e3ae46 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -60,6 +60,13 @@ target_link_libraries(test_rate_limiter PRIVATE LootLocker::core lootlocker_comp target_include_directories(test_rate_limiter PRIVATE ${CMAKE_SOURCE_DIR}/src/core) add_test(NAME rate_limiter COMMAND test_rate_limiter) +# The JSON layer (T13b). `src/core` is on the include path because `ParseJson` is internal +# (D18) - an adopter sees only `JsonValue`. +add_executable(test_json test_json.cpp) +target_link_libraries(test_json PRIVATE LootLocker::core lootlocker_compile_options) +target_include_directories(test_json PRIVATE ${CMAKE_SOURCE_DIR}/src/core) +add_test(NAME json COMMAND test_json) + # The end-to-end transport test (T11, owner 2026-11-13): a real round trip through the real # curl transport against a loopback server, plus the proof that `Config::transport` is # actually consulted. diff --git a/tests/test_json.cpp b/tests/test_json.cpp new file mode 100644 index 0000000..3754d6b --- /dev/null +++ b/tests/test_json.cpp @@ -0,0 +1,254 @@ +// The JSON layer (T13b, D4, D23). +// +// Two things are under test here, and they are different concerns: +// +// 1. The handle behaves as documented - kinds, typed reads, absent keys, nesting. +// 2. A malformed body is a `MalformedResponse` error rather than a crash or a silently +// empty value, which is D23's whole point. + +#include +#include + +#include "json.h" +#include "test_harness.h" + +#include +#include + +using namespace lootlocker; + +namespace { + +JsonValue Parse(const std::string& text) +{ + const Result result = core::ParseJson(text); + CHECK(result.Ok()); + return result.Ok() ? result.Value() : JsonValue(); +} + +// --- Kinds ----------------------------------------------------------------------------- + +void TestKinds() +{ + CHECK(Parse("null").GetKind() == JsonValue::Kind::Null); + CHECK(Parse("true").GetKind() == JsonValue::Kind::Bool); + CHECK(Parse("42").GetKind() == JsonValue::Kind::Number); + CHECK(Parse("\"text\"").GetKind() == JsonValue::Kind::String); + CHECK(Parse("[]").GetKind() == JsonValue::Kind::Array); + CHECK(Parse("{}").GetKind() == JsonValue::Kind::Object); +} + +void TestNakedPrimitives() +{ + // D4's requirement: full JSON standard support including top-level scalars. A parser + // that only accepts objects would fail here, and the API does send bare values in some + // error bodies. + CHECK_EQ_INT(Parse("42").AsInt64(), 42); + CHECK_EQ(Parse("\"hello\"").AsString(), std::string("hello")); + CHECK(Parse("true").AsBool()); + CHECK(!Parse("false").AsBool()); + CHECK(Parse("null").GetKind() == JsonValue::Kind::Null); +} + +// --- Typed reads ----------------------------------------------------------------------- + +void TestTypedReads() +{ + const JsonValue root = Parse("{\"s\":\"text\",\"i\":-7,\"u\":18446744073709551615," + "\"d\":1.5,\"b\":true,\"n\":null}"); + + CHECK_EQ(root["s"].AsString(), std::string("text")); + CHECK_EQ_INT(root["i"].AsInt64(), -7); + CHECK(root["d"].AsDouble() == 1.5); + CHECK(root["b"].AsBool()); + CHECK(root["n"].GetKind() == JsonValue::Kind::Null); + + // The 2^64-1 case, which is where a `double`-based parser loses precision. D4's spike + // established that nlohmann is exact here; this asserts the handle does not undo it. + CHECK(root["u"].AsUInt64() == 18446744073709551615ULL); +} + +void TestLargeIntegersSurvive() +{ + // 2^53 + 1 is the first integer a double cannot represent. The spike's premise was that + // this was the hazard; it is not, but the handle must not reintroduce it. + const JsonValue root = Parse("{\"big\":9007199254740993}"); + CHECK(root["big"].AsInt64() == 9007199254740993LL); + CHECK(root["big"].AsUInt64() == 9007199254740993ULL); +} + +void TestWrongKindReturnsADefault() +{ + // A caller that has already checked `GetKind()` pays nothing; a caller that has not gets + // a defined answer rather than undefined behaviour. + const JsonValue root = Parse("{\"s\":\"text\"}"); + + CHECK_EQ_INT(root["s"].AsInt64(), 0); + CHECK(root["s"].AsDouble() == 0.0); + CHECK(!root["s"].AsBool()); + CHECK(root["s"].AsUInt64() == 0ULL); +} + +// --- Absent keys are distinguishable from null ----------------------------------------- + +void TestAbsentKeyIsInvalidNotNull() +{ + // The distinction D23 exists to preserve: "the key is missing" and "the key is null" are + // different answers, and conflating them is how a decoder silently defaults a field. + const JsonValue root = Parse("{\"present\":null}"); + + CHECK(root["present"].GetKind() == JsonValue::Kind::Null); + CHECK(root["present"].IsValid()); + + CHECK(root["absent"].GetKind() == JsonValue::Kind::Invalid); + CHECK(!root["absent"].IsValid()); + + CHECK(root.HasKey("present")); + CHECK(!root.HasKey("absent")); +} + +void TestIndexingANonObjectIsInvalid() +{ + const JsonValue root = Parse("[1,2,3]"); + CHECK(!root["key"].IsValid()); + CHECK(!root.HasKey("key")); +} + +// --- Nesting --------------------------------------------------------------------------- + +void TestNestedAccess() +{ + const JsonValue root = Parse( + "{\"broadcasts\":[{\"id\":\"b1\",\"languages\":[{\"headline\":\"hi\"}]}]}"); + + CHECK(root["broadcasts"].GetKind() == JsonValue::Kind::Array); + CHECK_EQ_INT(static_cast(root["broadcasts"].Size()), 1); + + const JsonValue first = root["broadcasts"].At(0); + CHECK_EQ(first["id"].AsString(), std::string("b1")); + + const JsonValue language = first["languages"].At(0); + CHECK_EQ(language["headline"].AsString(), std::string("hi")); +} + +void TestOutOfRangeIndexIsInvalid() +{ + const JsonValue root = Parse("[1,2,3]"); + CHECK_EQ_INT(static_cast(root.Size()), 3); + CHECK(root.At(2).IsValid()); + CHECK(!root.At(3).IsValid()); + CHECK(!root.At(1000).IsValid()); +} + +void TestKeysContainingSlashesAndTildes() +{ + // The path is a sequence of keys, not a string, so a key containing '/' or '~' needs no + // escaping and cannot be confused with a separator. This is the case a string-path + // implementation gets wrong. + const JsonValue root = Parse("{\"a/b\":1,\"c~d\":2,\"e~1f\":3}"); + + CHECK_EQ_INT(root["a/b"].AsInt64(), 1); + CHECK_EQ_INT(root["c~d"].AsInt64(), 2); + CHECK_EQ_INT(root["e~1f"].AsInt64(), 3); +} + +// --- Lifetime -------------------------------------------------------------------------- + +void TestValueOutlivesItsSourceText() +{ + // The handle owns its document, so it stays valid after the text it was parsed from is + // gone. This is what makes it safe to hold across a callback. + JsonValue held; + { + const std::string text = "{\"key\":\"value\"}"; + held = Parse(text); + } + CHECK_EQ(held["key"].AsString(), std::string("value")); +} + +void TestSubValueOutlivesItsParent() +{ + JsonValue child; + { + const JsonValue root = Parse("{\"outer\":{\"inner\":\"deep\"}}"); + child = root["outer"]["inner"]; + } + CHECK_EQ(child.AsString(), std::string("deep")); +} + +// --- Malformed input (D23) ------------------------------------------------------------- + +void TestMalformedBodiesAreErrors() +{ + // Every shape D23 lists that is a *parse* failure. The decode-shape failures (valid JSON + // of the wrong shape) belong to the definition layer, not here. + const char* const malformed[] = { + "", // empty + " ", // whitespace only + "{", // truncated + "{\"a\":1", // truncated mid-object + "{\"a\":}", // missing value + "not json at all", // HTML-ish garbage + "502", // the Cloudflare case + "{'a':1}", // single quotes + "{\"a\":1,}", // trailing comma + }; + + for (const char* text : malformed) { + const Result result = core::ParseJson(text); + CHECK(!result.Ok()); + CHECK(result.Error().code == ErrorCode::MalformedResponse); + + // The body is preserved on the failure, so the adopter can see what the server + // actually sent (D7, D23). + CHECK_EQ(result.RawBody(), std::string(text)); + } +} + +void TestValidJsonOfTheWrongShapeParses() +{ + // A bare array or a bare string is *valid JSON*. Whether it is the right shape for an + // endpoint is the definition layer's business, so parsing must succeed here. + CHECK(Parse("[]").GetKind() == JsonValue::Kind::Array); + CHECK(Parse("\"error\"").GetKind() == JsonValue::Kind::String); + CHECK(Parse("123").GetKind() == JsonValue::Kind::Number); +} + +// --- Serialisation --------------------------------------------------------------------- + +void TestSerializeRoundTripsScalarsAndArrays() +{ + CHECK_EQ(core::SerializeJson(Parse("null")), std::string("null")); + CHECK_EQ(core::SerializeJson(Parse("true")), std::string("true")); + CHECK_EQ(core::SerializeJson(Parse("\"text\"")), std::string("\"text\"")); + CHECK_EQ(core::SerializeJson(Parse("[1,2,3]")), std::string("[1.0,2.0,3.0]")); +} + +void TestSerializeOfInvalidIsEmpty() +{ + CHECK_EQ(core::SerializeJson(JsonValue()), std::string()); +} + +} // namespace + +int main() +{ + TestKinds(); + TestNakedPrimitives(); + TestTypedReads(); + TestLargeIntegersSurvive(); + TestWrongKindReturnsADefault(); + TestAbsentKeyIsInvalidNotNull(); + TestIndexingANonObjectIsInvalid(); + TestNestedAccess(); + TestOutOfRangeIndexIsInvalid(); + TestKeysContainingSlashesAndTildes(); + TestValueOutlivesItsSourceText(); + TestSubValueOutlivesItsParent(); + TestMalformedBodiesAreErrors(); + TestValidJsonOfTheWrongShapeParses(); + TestSerializeRoundTripsScalarsAndArrays(); + TestSerializeOfInvalidIsEmpty(); + + return testing::Report(); +} From 33c1b78c38244b8ff57d813a0d2303842b6d0c23 Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Wed, 25 Nov 2026 09:19:32 +0100 Subject: [PATCH 2/3] Fix five review findings in the JSON layer Two were undefined behaviour, two were data loss, one was a contract violation. - AsInt64 and AsUInt64 cast an out-of-range double to an integer, which is undefined behaviour rather than a clamp. 1e100 is valid JSON and reaches that branch. Both now check the representable range first and saturate, so the non-representable result is defined rather than left to the platform. - SerializeJson rebuilt every number through AsDouble(), so 9007199254740993 came back as 9.007199254740992e+15 - silently changing valid JSON data. It also could not represent an object at all: an object inside an array serialised to an empty string, which the non-throwing parse turned into a discarded value, and dump() on a discarded value aborts under JSON_NOEXCEPTION. Both are fixed by serialising from the resolved document instead of rebuilding through the public surface. This is core, so it can reach the impl - and reaching for the public handle was the mistake, not the shortcut. - Size() accepted Kind::Object and reported its member count, contradicting the documented "arrays only" contract and disagreeing with At(), which returns invalid for an object. One existing test asserted the buggy output: it expected "[1.0,2.0,3.0]" for "[1,2,3]". That expectation was the bug, so it is corrected rather than preserved. Verified by sabotage: restoring the object branch in Size() fails the contract test, and routing numbers through double fails both precision assertions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- include/lootlocker/json_value.h | 8 +++- src/core/json.cpp | 71 ++++++++++++++++++--------------- tests/test_json.cpp | 57 +++++++++++++++++++++++++- 3 files changed, 101 insertions(+), 35 deletions(-) diff --git a/include/lootlocker/json_value.h b/include/lootlocker/json_value.h index 6a38979..62569eb 100644 --- a/include/lootlocker/json_value.h +++ b/include/lootlocker/json_value.h @@ -26,8 +26,10 @@ class JsonValue; namespace core { class JsonParser; -// Declared here so the friend declaration below can name it. Defined in `src/core/json.cpp`. +// Declared here so the friend declarations below can name them. Defined in +// `src/core/json.cpp`. Result ParseJson(const std::string& text); +std::string SerializeJson(const JsonValue& value); } // namespace core class JsonValue { @@ -77,6 +79,10 @@ class JsonValue { // `JsonValue` from an impl. friend Result core::ParseJson(const std::string& text); + // `SerializeJson` resolves the document directly rather than rebuilding through the + // public surface, which would lose integer precision and could not represent an object. + friend std::string core::SerializeJson(const JsonValue& value); + struct Impl; explicit JsonValue(std::shared_ptr impl); diff --git a/src/core/json.cpp b/src/core/json.cpp index d07ef92..7fdb660 100644 --- a/src/core/json.cpp +++ b/src/core/json.cpp @@ -153,7 +153,19 @@ std::int64_t JsonValue::AsInt64() const if (value->is_number_integer()) { return value->get(); } - return static_cast(value->get()); + + // A float. `1e100` is valid JSON and does not fit an `int64_t`, and converting an + // out-of-range `double` to an integer is undefined behaviour rather than a clamp - so + // the range is checked before the cast, and the non-representable result is defined as + // the saturated bound rather than left to the platform. + const double raw = value->get(); + if (!(raw >= -9223372036854775808.0)) { // also false for NaN + return -9223372036854775807LL - 1; + } + if (!(raw < 9223372036854775808.0)) { + return 9223372036854775807LL; + } + return static_cast(raw); } std::uint64_t JsonValue::AsUInt64() const @@ -170,8 +182,17 @@ std::uint64_t JsonValue::AsUInt64() const const auto raw = value->get(); return raw < 0 ? 0 : static_cast(raw); } + + // A float. Checked before the cast for the same reason as `AsInt64`: an out-of-range + // `double` to `uint64_t` conversion is undefined behaviour, and `1e100` is valid JSON. const double raw = value->get(); - return raw < 0.0 ? 0 : static_cast(raw); + if (!(raw > 0.0)) { // also false for NaN + return 0; + } + if (!(raw < 18446744073709551616.0)) { + return 18446744073709551615ULL; + } + return static_cast(raw); } std::string JsonValue::AsString() const @@ -211,8 +232,10 @@ bool JsonValue::HasKey(const std::string& key) const std::size_t JsonValue::Size() const { - const Kind kind = GetKind(); - if (kind != Kind::Array && kind != Kind::Object) { + // Arrays only, as documented. An object reporting its member count would make a caller + // treat it as an array-sized value, and `At()` on an object returns invalid anyway - so + // the two would disagree. + if (GetKind() != Kind::Array) { return 0; } return Resolve(*m_impl->document, m_impl->path)->size(); @@ -261,38 +284,20 @@ std::string SerializeJson(const JsonValue& value) return std::string(); } - // Rebuilt from the public surface rather than reaching into the impl, so this stays a - // consumer of the handle like everything else. Only tests and logging use it - the SDK + // Serialised from the resolved document rather than rebuilt through the public surface. + // + // Rebuilding was wrong in two ways: a number went through `AsDouble()`, so an integer + // like 9007199254740993 came back as 9007199254740992; and an object inside an array + // serialised to an empty string, which the non-throwing parse then turned into a + // discarded value - and `dump()` on a discarded value aborts under `JSON_NOEXCEPTION`. + // + // This is `core`, so it can reach the impl. Only tests and logging use it - the SDK // never re-serialises a response, because `RawBody()` is the original bytes (D7). - switch (value.GetKind()) { - case JsonValue::Kind::Null: - return "null"; - case JsonValue::Kind::Bool: - return value.AsBool() ? "true" : "false"; - case JsonValue::Kind::Number: { - const nlohmann::json number = value.AsDouble(); - return number.dump(); - } - case JsonValue::Kind::String: { - const nlohmann::json string = value.AsString(); - return string.dump(); - } - case JsonValue::Kind::Array: { - nlohmann::json array = nlohmann::json::array(); - for (std::size_t i = 0; i < value.Size(); ++i) { - array.push_back(nlohmann::json::parse(SerializeJson(value.At(i)), nullptr, false)); - } - return array.dump(); - } - case JsonValue::Kind::Object: - // Object keys are not exposed by the handle, so an object cannot be rebuilt. Nothing - // in the SDK needs it, and adding a key iterator to the public surface to support a - // test helper would be the wrong trade. - return std::string(); - case JsonValue::Kind::Invalid: - default: + const nlohmann::json* resolved = Resolve(*value.m_impl->document, value.m_impl->path); + if (resolved == nullptr) { return std::string(); } + return resolved->dump(); } } // namespace core diff --git a/tests/test_json.cpp b/tests/test_json.cpp index 3754d6b..ba74079 100644 --- a/tests/test_json.cpp +++ b/tests/test_json.cpp @@ -221,7 +221,58 @@ void TestSerializeRoundTripsScalarsAndArrays() CHECK_EQ(core::SerializeJson(Parse("null")), std::string("null")); CHECK_EQ(core::SerializeJson(Parse("true")), std::string("true")); CHECK_EQ(core::SerializeJson(Parse("\"text\"")), std::string("\"text\"")); - CHECK_EQ(core::SerializeJson(Parse("[1,2,3]")), std::string("[1.0,2.0,3.0]")); + + // Integers stay integers. The old expectation here was "[1.0,2.0,3.0]", which was the + // bug: every number went through `AsDouble()`. + CHECK_EQ(core::SerializeJson(Parse("[1,2,3]")), std::string("[1,2,3]")); + CHECK_EQ(core::SerializeJson(Parse("[1.5,2.5]")), std::string("[1.5,2.5]")); +} + +void TestOutOfRangeFloatsSaturate() +{ + // `1e100` is valid JSON and does not fit an integer. Converting an out-of-range `double` + // to an integer is undefined behaviour rather than a clamp, so the range is checked + // before the cast and the result is defined as the saturated bound. + const JsonValue root = Parse("{\"huge\":1e100,\"neg\":-1e100,\"nan\":1e100}"); + + CHECK(root["huge"].AsInt64() == 9223372036854775807LL); + CHECK(root["huge"].AsUInt64() == 18446744073709551615ULL); + CHECK(root["neg"].AsInt64() == -9223372036854775807LL - 1); + CHECK(root["neg"].AsUInt64() == 0ULL); +} + +void TestSizeIsArraysOnly() +{ + // The contract says arrays only. An object reporting its member count would make a + // caller treat it as an array-sized value, and `At()` on an object returns invalid - so + // the two would disagree. + const JsonValue root = Parse("{\"arr\":[1,2,3],\"obj\":{\"a\":1,\"b\":2}}"); + + CHECK_EQ_INT(static_cast(root["arr"].Size()), 3); + CHECK_EQ_INT(static_cast(root["obj"].Size()), 0); + CHECK(!root["obj"].At(0).IsValid()); +} + +void TestSerializePreservesIntegerPrecision() +{ + // Routing every number through `AsDouble()` turned 9007199254740993 into + // 9007199254740992 - silently changing valid JSON data. + CHECK_EQ(core::SerializeJson(Parse("9007199254740993")), std::string("9007199254740993")); + CHECK_EQ(core::SerializeJson(Parse("18446744073709551615")), + std::string("18446744073709551615")); + CHECK_EQ(core::SerializeJson(Parse("-9223372036854775808")), + std::string("-9223372036854775808")); +} + +void TestSerializeHandlesObjectsAndNesting() +{ + // An object inside an array used to serialise to an empty string, which the non-throwing + // parse turned into a discarded value - and `dump()` on a discarded value aborts under + // `JSON_NOEXCEPTION`. + CHECK_EQ(core::SerializeJson(Parse("{\"a\":1}")), std::string("{\"a\":1}")); + CHECK_EQ(core::SerializeJson(Parse("[{\"a\":1},2]")), std::string("[{\"a\":1},2]")); + CHECK_EQ(core::SerializeJson(Parse("{\"outer\":{\"inner\":[1,2]}}")), + std::string("{\"outer\":{\"inner\":[1,2]}}")); } void TestSerializeOfInvalidIsEmpty() @@ -248,6 +299,10 @@ int main() TestMalformedBodiesAreErrors(); TestValidJsonOfTheWrongShapeParses(); TestSerializeRoundTripsScalarsAndArrays(); + TestOutOfRangeFloatsSaturate(); + TestSizeIsArraysOnly(); + TestSerializePreservesIntegerPrecision(); + TestSerializeHandlesObjectsAndNesting(); TestSerializeOfInvalidIsEmpty(); return testing::Report(); From 296673ec16cf98d83af35e342097d0e7a2dabb15 Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Wed, 25 Nov 2026 10:25:26 +0100 Subject: [PATCH 3/3] Expose the number granularity, and document the JSON layer Two owner questions on the PR, both fair. - "Should we not expose this granularity upwards as well?" Yes. JsonValue exposed Kind and the typed reads but not the integer/unsigned distinction that AsInt64 and AsUInt64 depend on internally - so an adopter writing a from_json for a uint64 field could not tell an integer from a float, and would have to guess from the value. Guessing is how the 2^53 hazard comes back. IsInteger() and IsUnsigned() are now public. - "How is it getting in the source package?" It already was: the submodule is pinned to v3.11.3 and CMakeLists puts its single_include on core's PRIVATE path. I checked because the question implied it might not be, and git describe reported "v3.11.2-84-g9cca280a4" - which turned out to be a stale local tag list, not a real drift. The commit is exactly refs/tags/v3.11.3. The third point was the substantive one: the README said nothing about the JSON layer at all. It now documents the three things an adopter actually needs - RawBody() for a field the SDK does not model, an ADL from_json against JsonValue for custom decoding, and the fact that there is deliberately no parser seam, with the reason. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 66 +++++++++++++++++++++++++++++++++ include/lootlocker/json_value.h | 11 ++++++ src/core/json.cpp | 17 +++++++++ tests/test_json.cpp | 22 +++++++++++ 4 files changed, 116 insertions(+) diff --git a/README.md b/README.md index f33ae4d..be832b7 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,72 @@ already cached can block for the length of the lookup. The transfer itself is po name resolution is not. If that matters, resolve once at startup or inject a transport whose resolver is asynchronous. +## JSON + +The SDK parses JSON with [nlohmann/json](https://github.com/nlohmann/json), vendored as a +submodule pinned to `v3.11.3` and included by exactly one translation unit. **You never see +it.** No public header includes it, and no public type names it. + +That is deliberate: it keeps our parser choice out of the API, so changing it later is not a +breaking change for you. + +### Reading a field the SDK does not model + +Use `RawBody()`. Every result carries the response body exactly as the server sent it, on +success and on failure, so you can parse it with whatever you already have: + +```cpp +lootlocker::broadcasts::List(ll, [](lootlocker::Result> r) { + if (!r.Ok()) { + // The body is here too, so you can see what the server actually said. + my_log(r.RawBody()); + return; + } + my_own_parser(r.RawBody()); // your parser, your types +}); +``` + +This is the intended answer to "the SDK is missing a field". It is not a workaround. + +### Custom decoding for a type + +If you need a field decoded differently from the default, write an ADL `from_json` next to +your type. It takes a `lootlocker::JsonValue`, which is a parser-independent handle — it +exposes the shape of the value and nothing about which library produced it: + +```cpp +namespace my_game { + +struct PlayerStats { + std::uint64_t total_score = 0; + std::string rank; +}; + +void from_json(const lootlocker::JsonValue& j, PlayerStats& out) +{ + // `IsUnsigned()` matters: reading a uint64 through AsDouble() loses precision above + // 2^53, which is the one hazard the JSON spike found. + if (j["total_score"].IsUnsigned()) { + out.total_score = j["total_score"].AsUInt64(); + } + out.rank = j["rank"].AsString(); +} + +} // namespace my_game +``` + +`JsonValue` gives you `GetKind()`, `IsInteger()`, `IsUnsigned()`, the typed `As*` reads, +`operator[]`, `HasKey()`, `Size()` and `At()`. An absent key is `Kind::Invalid`, which is +distinct from `Kind::Null` — so "the field is missing" and "the field is null" are different +answers, and you can tell them apart. + +### There is no parser seam + +Unlike the transport or the state writer, the JSON parser is not injectable. It is internal +machinery rather than an ecosystem-docking point: every adopter needs it, none needs a +different one, and a seam with no consumer is a seam nobody maintains. If you need a +different parser, `RawBody()` gives you the bytes. + ## What is in v1 Guest, white label and Steam authentication, plus broadcasts. Presence, offline mode, diff --git a/include/lootlocker/json_value.h b/include/lootlocker/json_value.h index 62569eb..4874b00 100644 --- a/include/lootlocker/json_value.h +++ b/include/lootlocker/json_value.h @@ -61,6 +61,17 @@ class JsonValue { std::uint64_t AsUInt64() const; std::string AsString() const; + // Whether a `Number` is an integer rather than a float, and whether it is unsigned. + // + // Exposed because a custom serialiser needs the same distinction the SDK's own decoders + // make: a `uint64` field must not be read through `AsDouble()`, which loses precision + // above 2^53. Without these, an adopter writing a `from_json` for such a field has to + // guess from the value, and guessing is how the 2^53 hazard comes back. + // + // Both are false for anything that is not a `Number`. + bool IsInteger() const; + bool IsUnsigned() const; + // Object access. Returns an invalid value when the key is absent or this is not an // object. JsonValue operator[](const std::string& key) const; diff --git a/src/core/json.cpp b/src/core/json.cpp index 7fdb660..4f5e871 100644 --- a/src/core/json.cpp +++ b/src/core/json.cpp @@ -203,6 +203,23 @@ std::string JsonValue::AsString() const return Resolve(*m_impl->document, m_impl->path)->get(); } +bool JsonValue::IsInteger() const +{ + if (GetKind() != Kind::Number) { + return false; + } + const nlohmann::json* value = Resolve(*m_impl->document, m_impl->path); + return value->is_number_integer() || value->is_number_unsigned(); +} + +bool JsonValue::IsUnsigned() const +{ + if (GetKind() != Kind::Number) { + return false; + } + return Resolve(*m_impl->document, m_impl->path)->is_number_unsigned(); +} + JsonValue JsonValue::operator[](const std::string& key) const { if (GetKind() != Kind::Object) { diff --git a/tests/test_json.cpp b/tests/test_json.cpp index ba74079..f4e1523 100644 --- a/tests/test_json.cpp +++ b/tests/test_json.cpp @@ -275,6 +275,27 @@ void TestSerializeHandlesObjectsAndNesting() std::string("{\"outer\":{\"inner\":[1,2]}}")); } +void TestNumberGranularityIsExposed() +{ + // A custom serialiser needs the same distinction the SDK's own decoders make: a `uint64` + // field must not be read through `AsDouble()`, which loses precision above 2^53. + const JsonValue root = Parse("{\"i\":-7,\"u\":18446744073709551615,\"d\":1.5,\"s\":\"x\"}"); + + CHECK(root["i"].IsInteger()); + CHECK(!root["i"].IsUnsigned()); + + CHECK(root["u"].IsInteger()); + CHECK(root["u"].IsUnsigned()); + + // A float is a number but not an integer, which is the distinction that matters. + CHECK(!root["d"].IsInteger()); + CHECK(!root["d"].IsUnsigned()); + + // And neither is true for a non-number. + CHECK(!root["s"].IsInteger()); + CHECK(!root["s"].IsUnsigned()); +} + void TestSerializeOfInvalidIsEmpty() { CHECK_EQ(core::SerializeJson(JsonValue()), std::string()); @@ -303,6 +324,7 @@ int main() TestSizeIsArraysOnly(); TestSerializePreservesIntegerPrecision(); TestSerializeHandlesObjectsAndNesting(); + TestNumberGranularityIsExposed(); TestSerializeOfInvalidIsEmpty(); return testing::Report();