From 357babdd40e7df4ef508923ac7c2e319cff60cd4 Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Wed, 25 Nov 2026 14:46:43 +0100 Subject: [PATCH 1/4] Add guest auth POST /game/v2/session/guest, with the player_identifier reuse that is the whole point of guest auth: a guest who loses their identifier silently becomes a new account with no inventory. The identifier is resolved as caller-supplied, then persisted, then generated, and the resolved value is written BEFORE the request is sent. A crash between sending and receiving would otherwise orphan the account the server just created. A successful session is stored on the client, so subsequent requests carry x-session-token. The token is read at send time rather than at queue time, so a request queued before a session started still carries the token once it is sent. Session decoding distinguishes required from optional fields. D23 says a missing field is an error rather than a zero, but that rule is about fields the SDK depends on: session_token, player_identifier, player_ulid, public_uid and player_id are required, while player_name and the notification hints are genuinely optional and an absent name means "not set". player_id is read through IsUnsigned/AsUInt64 so a value above 2^53 survives. Two test bugs found and fixed, both the same mistake: - The reuse test assigned a temporary shared_ptr to Config::state_writer, which expires before the Client is constructed, so both clients fell back to the default file and the test passed for the wrong reason. - A stale lootlocker-state.txt in the working directory then masked a sabotage, so the test appeared to pass with persistence removed. Tests now hold named writers, and the ones that do not care about persistence inject a NullStateWriter so they cannot touch the shared default file. Verified by sabotage: removing the persist call now fails the reuse test with two different identifiers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CMakeLists.txt | 6 + README.md | 45 +++- include/lootlocker/auth.h | 56 +++- include/lootlocker/client.h | 23 ++ include/lootlocker/session.h | 52 ++++ src/auth/auth.cpp | 159 +++++++++++- src/core/client.cpp | 39 +++ src/core/executor.cpp | 14 + src/core/executor.h | 12 + src/core/optional.h | 19 ++ src/core/session.cpp | 103 ++++++++ tests/CMakeLists.txt | 8 + tests/test_auth.cpp | 491 +++++++++++++++++++++++++++++++++++ 13 files changed, 1018 insertions(+), 9 deletions(-) create mode 100644 include/lootlocker/session.h create mode 100644 src/core/optional.h create mode 100644 src/core/session.cpp create mode 100644 tests/test_auth.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 8b44f4b..2b8db58 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -143,6 +143,7 @@ add_library(lootlocker_core STATIC src/core/rate_limiter.cpp src/core/json.cpp src/core/query_parameters.cpp + src/core/session.cpp src/core/state_writer.cpp src/core/executor.cpp src/core/client.cpp @@ -190,6 +191,11 @@ foreach(module IN LISTS LOOTLOCKER_FEATURE_MODULES) target_link_libraries(lootlocker_${module} PUBLIC LootLocker::core PRIVATE lootlocker_compile_options) + + # A module may include `core`'s internal headers, because it is built inside the library + # (D18). An adopter cannot: `src/` is not on their include path, so the definitions are + # unreachable even though the declarations are visible. + target_include_directories(lootlocker_${module} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) endforeach() # --------------------------------------------------------------------------- diff --git a/README.md b/README.md index 5aff967..b0d2515 100644 --- a/README.md +++ b/README.md @@ -328,7 +328,50 @@ definition. over a shared, immutable document, which is what makes it cheap to pass around and safe to hold across a callback. Writing needs its own type. -### Persistence +### Authentication + +Guest auth is the MVP's primary path: no credentials, no platform, just an identifier the +SDK generates once and reuses. + +```cpp +lootlocker::auth::StartGuestSession(ll, [](lootlocker::Result r) { + if (!r.Ok()) { + my_log(r.Error().message); + return; + } + std::printf("player %s\n", r.Value().player_ulid.c_str()); +}); + +while (ll.Update()) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); +} +``` + +**The identifier reuse is the whole point.** A guest who loses their `player_identifier` +silently becomes a new account with no inventory, so the SDK persists it and sends it back +on the next launch. You do not have to do anything: the resolved identifier is written +*before* the request is sent, so a crash between sending and receiving does not orphan the +account the server just created. + +The resolution order is: `GuestSessionOptions::player_identifier` if you set it, then the +persisted one, then a newly generated one. Setting it explicitly is for a game that manages +its own identity; leaving it empty is what almost every caller wants. + +A successful session is stored on the client, so subsequent requests carry +`x-session-token` and `ll.GetSession()` returns it. `ll.HasSession()` is the cheap check. + +```cpp +lootlocker::GuestSessionOptions opts; +opts.timezone = "Europe/Stockholm"; // empty = resolve: provider, then OS, then Etc/UTC +opts.player_name = "Erik"; + +lootlocker::auth::StartGuestSession(ll, opts, on_session); +``` + +With a `NullStateWriter` every launch generates a new identifier, which is the documented +cost of choosing not to persist. + +## Persistence The SDK remembers a session between launches through a `IStateWriter`. The default writes one file next to the game; a console or an engine injects its own. diff --git a/include/lootlocker/auth.h b/include/lootlocker/auth.h index c233810..60a9de4 100644 --- a/include/lootlocker/auth.h +++ b/include/lootlocker/auth.h @@ -1,16 +1,60 @@ #pragma once -// Placeholder for the auth module's public surface. +// Guest authentication (D16, T14). // -// T8 scaffolds the target graph only. The real surface lands with T14 (guest), T15 -// (white label), T16 (Steam) and T18 (end session + refresh), per -// specs-library/specs/discipline/sdk/cpp-sdk/api-sketch.md. +// A guest session is the MVP's primary auth path: no credentials, no platform, just an +// identifier the SDK generates once and reuses. **The reuse is the whole point** - a guest +// who loses their `player_identifier` silently becomes a new account with no inventory, so +// the SDK persists it (D8) and sends it back on the next launch. +// +// The identifier is generated here rather than by the caller, because a caller that has to +// invent one will invent a different one on the next launch. + +#include +#include +#include +#include + +#include +#include namespace lootlocker { + +// Everything the API calls `optionals`. All of it is optional: a session start needs only +// `game_key` and `game_version`, which live in `Config`. +struct GuestSessionOptions { + // Reuse it to keep the same guest across launches. Empty means "use the persisted one, + // or generate a new one" - which is what almost every caller wants. + std::string player_identifier; + + // Empty means "resolve it": the injected provider, then the OS, then `Etc/UTC` (D26). + std::string timezone; + + std::string locale; + std::string player_name; + std::string character_name; +}; + +using SessionCallback = std::function)>; + namespace auth { -// Intentionally empty until T14. The header exists so the target graph and the -// include-path boundary (D18) can be verified before any feature is written. +// POST /game/v2/session/guest +// +// Starts a guest session and stores it on the client, so subsequent requests carry +// `x-session-token` and `Client::GetSession()` returns it. +// +// **The identifier is resolved in this order:** `opts.player_identifier` if set, then the +// one persisted by a previous session, then a newly generated one. The resolved value is +// persisted before the request is sent, so a crash between sending and receiving does not +// lose the identifier and orphan the account. +// +// Returns the id the executor assigned. The callback fires on the thread that calls +// `Client::Update()` (D5). +RequestId StartGuestSession(Client& ll, SessionCallback on_done); + +RequestId StartGuestSession(Client& ll, const GuestSessionOptions& opts, + SessionCallback on_done); } // namespace auth } // namespace lootlocker diff --git a/include/lootlocker/client.h b/include/lootlocker/client.h index 94d4b86..5506a5c 100644 --- a/include/lootlocker/client.h +++ b/include/lootlocker/client.h @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -96,6 +97,28 @@ class Client { // `FileStateWriter`. std::weak_ptr GetStateWriter() const; + // The session, if one has been started. + // + // Returns a reference to the client's own copy rather than a value, so a per-frame read + // costs nothing. `HasSession()` is the cheap check; `Session()` is only valid when it is + // true. + bool HasSession() const; + + // Precondition: `HasSession()`. Dereferencing without checking is a precondition + // violation, the same contract as `Result::Value()`. + const Session& GetSession() const; + + // Sets the session directly, without a network call. + // + // For a game that restores a session from its own storage, and for a test. The SDK does + // not call this itself: `auth::StartGuestSession` sets the session when the response + // arrives. + void SetSession(const Session& session); + + // Clears the session. Does not call the API - `auth::EndSession` is the call that ends + // a session server-side. + void ClearSession(); + private: // The correct form: the function is declared in `core` above, so the friend // declaration names it qualified rather than declaring a new one in this scope. diff --git a/include/lootlocker/session.h b/include/lootlocker/session.h new file mode 100644 index 0000000..420650d --- /dev/null +++ b/include/lootlocker/session.h @@ -0,0 +1,52 @@ +#pragma once + +// The session (D8, D12). A wire mirror: fields are `snake_case` and match the JSON exactly. +// +// This is the one type that is both a wire mirror and a persisted record, which is why its +// field set is exactly what D8 says to store and nothing more. + +#include +#include + +#include +#include +#include + +namespace lootlocker { + +struct Session { + std::string session_token; + std::string player_identifier; + std::string player_ulid; + std::string public_uid; + std::string player_name; + std::uint64_t player_id = 0; // uint64 on the wire; see D4 + std::string player_created_at; + bool seen_before = false; + bool check_grant_notifications = false; + bool check_deactivation_notifications = false; +}; + +// `player_id` must stay `uint64`. The D4 spike showed both candidate parsers preserve it +// exactly; the hazard is a `double` field in our own structs, so the type is enforced here +// rather than left to review. +static_assert(sizeof(Session::player_id) == 8, "player_id must be 64-bit"); +static_assert(!std::is_floating_point::value, + "player_id must not be a floating-point type (D4)"); + +// Decodes a session response (D27). +// +// **Which fields are required, and why that is not a silent default.** D23 says a missing +// field is a decode error rather than a zero, and that rule exists to stop a field the SDK +// depends on being silently defaulted. It does not mean every field is mandatory: +// +// - `session_token`, `player_identifier`, `player_ulid`, `public_uid` and `player_id` are +// required. Without them the session is unusable or the player cannot be identified, +// and a default would be a lie. +// - `player_name` is optional, because an absent name genuinely means "this player has +// not set one". Defaulting it to empty is the correct reading, not a silent default. +// - `player_created_at` and the three booleans are optional for the same reason: they are +// display and notification hints, and the API omits them on some auth paths. +Result from_json(const JsonValue& j, Session& out); + +} // namespace lootlocker diff --git a/src/auth/auth.cpp b/src/auth/auth.cpp index 410a653..eb8b65b 100644 --- a/src/auth/auth.cpp +++ b/src/auth/auth.cpp @@ -1,4 +1,159 @@ #include -// T8 scaffold. The auth module has no implementation yet; this translation unit exists so -// the target builds and the module-boundary CI job (T8c) has something to compile. +#include +#include + +#include "core/definition.h" +#include "core/query_parameters.h" + +#include +#include +#include +#include + +namespace lootlocker { + +namespace { + +// The keys the SDK persists. Named here rather than inline so a typo is a compile error +// rather than a silently missing key. +const char* const kPlayerIdentifierKey = "player_identifier"; + +// A guest identifier: a UUID-shaped random string. +// +// Not a security token - the server treats it as an opaque account handle - so +// `std::random_device` is the right tool rather than a cryptographic generator. It only has +// to be unlikely to collide, and it must be stable once persisted. +std::string GeneratePlayerIdentifier() +{ + std::random_device device; + std::uint64_t high = (static_cast(device()) << 32) ^ device(); + std::uint64_t low = (static_cast(device()) << 32) ^ device(); + + high = (high & 0xFFFFFFFFFFFF0FFFULL) | 0x0000000000004000ULL; + low = (low & 0x3FFFFFFFFFFFFFFFULL) | 0x8000000000000000ULL; + + char buffer[37]; + std::snprintf(buffer, sizeof(buffer), "%08x-%04x-%04x-%04x-%012llx", + static_cast((high >> 32) & 0xFFFFFFFFULL), + static_cast((high >> 16) & 0xFFFFULL), + static_cast(high & 0xFFFFULL), + static_cast((low >> 48) & 0xFFFFULL), + static_cast(low & 0xFFFFFFFFFFFFULL)); + return std::string(buffer); +} + +// The identifier to send: the caller's, else the persisted one, else a new one. +// +// The resolved value is persisted *before* the request is sent. A crash between sending and +// receiving would otherwise lose the identifier and orphan the account the server just +// created - which is the single most damaging thing to lose (D8). +std::string ResolvePlayerIdentifier(Client& ll, const GuestSessionOptions& opts) +{ + if (!opts.player_identifier.empty()) { + return opts.player_identifier; + } + + std::shared_ptr writer = ll.GetStateWriter().lock(); + if (writer) { + std::string persisted; + if (writer->GetString(kPlayerIdentifierKey, persisted) && !persisted.empty()) { + return persisted; + } + } + + const std::string generated = GeneratePlayerIdentifier(); + if (writer) { + writer->SetString(kPlayerIdentifierKey, generated); + } + return generated; +} + +} // namespace + +// The request type lives in `lootlocker`, not the anonymous namespace, because the +// definition in `core` names it and `to_json` is found by ADL. +struct GuestSessionRequest { + std::string game_key; + std::string game_version; + std::string player_identifier; + std::string platform; + std::string timezone; + std::string locale; + std::string player_name; + std::string character_name; +}; + +void to_json(JsonBuilder& b, const GuestSessionRequest& in) +{ + b.Set("game_key", in.game_key); + b.Set("game_version", in.game_version); + b.Set("player_identifier", in.player_identifier); + b.Set("platform", in.platform); + + if (!in.timezone.empty()) { + b.Set("timezone", in.timezone); + } + if (!in.locale.empty()) { + b.Set("locale", in.locale); + } + if (!in.player_name.empty()) { + b.Set("player_name", in.player_name); + } + if (!in.character_name.empty()) { + b.Set("character_name", in.character_name); + } +} + +namespace core { + +struct GuestSessionDef { + static constexpr const char* kMethod = "POST"; + static constexpr const char* kPath = "/game/v2/session/guest"; + + using Request = GuestSessionRequest; + using Response = Session; + + static void ConstructQueryParameters(const Request&, QueryParameters&) {} + + static void ConstructHeaders(const Request&, HeaderMap&) {} +}; + +} // namespace core + +namespace auth { + +RequestId StartGuestSession(Client& ll, SessionCallback on_done) +{ + return StartGuestSession(ll, GuestSessionOptions(), std::move(on_done)); +} + +RequestId StartGuestSession(Client& ll, const GuestSessionOptions& opts, + SessionCallback on_done) +{ + const Config& config = ll.GetConfig(); + + GuestSessionRequest request; + request.game_key = config.game_key; + request.game_version = config.game_version; + request.platform = "guest"; + request.player_identifier = ResolvePlayerIdentifier(ll, opts); + request.timezone = opts.timezone; + request.locale = opts.locale; + request.player_name = opts.player_name; + request.character_name = opts.character_name; + + return core::Send( + ll, request, [&ll, on_done](Result result) { + if (result.Ok()) { + // Stored on the client so subsequent requests carry `x-session-token` and + // `GetSession()` returns it. Done here rather than by the caller, because a + // caller that forgot would get a 401 on the next call with no clue why. + ll.SetSession(result.Value()); + } + on_done(std::move(result)); + }); +} + +} // namespace auth +} // namespace lootlocker diff --git a/src/core/client.cpp b/src/core/client.cpp index 70fd7eb..a85f2f9 100644 --- a/src/core/client.cpp +++ b/src/core/client.cpp @@ -7,6 +7,7 @@ #include "clock.h" #include "executor.h" +#include "optional.h" #include #include @@ -38,6 +39,10 @@ struct Client::Impl { mutable std::shared_ptr default_state_writer; std::weak_ptr state_writer; + // The session, if one has been started. `Optional` because a client that has not + // authenticated has no session, and a default-constructed `Session` would be a lie. + core::Optional session; + // The writer to use, constructing the default on first call. std::shared_ptr ResolveStateWriter() const { @@ -152,6 +157,17 @@ Client::Client(const Config& config) : m_impl(new Impl()) settings.logger = logger; settings.config_error = m_impl->config_error; + // The session token is read at send time, so a request queued before a session starts + // still carries the token once it is sent. Captured by pointer to the impl, which + // outlives the executor because the executor is a member of it. + Impl* impl = m_impl.get(); + settings.session_token = [impl]() -> std::string { + if (!impl->session.has_value()) { + return std::string(); + } + return impl->session->session_token; + }; + m_impl->executor.reset(new core::Executor(settings)); } @@ -207,6 +223,29 @@ std::weak_ptr Client::GetStateWriter() const return m_impl->ResolveStateWriter(); } +bool Client::HasSession() const +{ + return m_impl->session.has_value(); +} + +const Session& Client::GetSession() const +{ + // A precondition violation rather than an exception (D7). The alternative - returning a + // default-constructed `Session` - would hand the caller an empty token and let the + // failure surface as a confusing 401 instead of here. + return *m_impl->session; +} + +void Client::SetSession(const Session& session) +{ + m_impl->session = session; +} + +void Client::ClearSession() +{ + m_impl->session.reset(); +} + namespace core { Executor& GetExecutor(Client& client) diff --git a/src/core/executor.cpp b/src/core/executor.cpp index 2e95dfe..5a9501e 100644 --- a/src/core/executor.cpp +++ b/src/core/executor.cpp @@ -43,6 +43,7 @@ bool IsRetryableStatus(int status_code) Executor::Executor(const ExecutorSettings& settings) : m_config(settings.queue), m_config_error(settings.config_error), m_transport(settings.transport), m_clock(*settings.clock), m_logger(settings.logger), + m_session_token(settings.session_token), m_rate_limiter(settings.rate_limit, *settings.clock) { } @@ -523,6 +524,19 @@ bool Executor::Update() // server log show one id across attempts rather than one per attempt. request.headers.Set("LL-Request-Id", entry.id.ToString()); + // The session token, read at send time rather than at queue time, so a request + // queued before a session started still carries the token once it is sent. + // + // Set here rather than by a definition, because it is identical for every + // endpoint and a definition that forgot it would produce a 401 that looks like + // an auth bug. + if (m_session_token) { + const std::string token = m_session_token(); + if (!token.empty()) { + request.headers.Set("x-session-token", token); + } + } + ++entry.attempts; entry.started_at_ms = now; diff --git a/src/core/executor.h b/src/core/executor.h index e0eb1d6..8805d72 100644 --- a/src/core/executor.h +++ b/src/core/executor.h @@ -81,6 +81,17 @@ struct ExecutorSettings { // The clock. Never null: the executor dereferences it, and a test supplies a fake. Clock* clock = nullptr; + // Supplies the session token to send as `x-session-token`, or an empty string when there + // is no session. + // + // A callback rather than a string, because the token changes when a session starts or + // ends and the executor must see the current one at send time, not the one that existed + // when the request was queued. A queued request that starts after a session begins + // should carry the new token. + // + // Empty means "no session support", which is what a test that does not care gets. + std::function session_token; + std::weak_ptr logger; // Empty when the config was usable. A non-empty error makes every submission reject with @@ -192,6 +203,7 @@ class Executor { std::weak_ptr m_transport; Clock& m_clock; std::weak_ptr m_logger; + std::function m_session_token; std::int64_t m_last_tick_ms = 0; bool m_has_ticked = false; diff --git a/src/core/optional.h b/src/core/optional.h new file mode 100644 index 0000000..5ce3db5 --- /dev/null +++ b/src/core/optional.h @@ -0,0 +1,19 @@ +#pragma once + +// `Optional` (D1). Internal: `lootlocker::core::` is not on an adopter's include path +// (D18). +// +// A thin alias over `std::optional`, kept as our own name so the type can change later +// without a breaking change. D1's C++17 floor is what makes `std::optional` available at +// all; under the superseded C++14 decision this would have been a hand-rolled type. + +#include + +namespace lootlocker { +namespace core { + +template +using Optional = std::optional; + +} // namespace core +} // namespace lootlocker diff --git a/src/core/session.cpp b/src/core/session.cpp new file mode 100644 index 0000000..71092a4 --- /dev/null +++ b/src/core/session.cpp @@ -0,0 +1,103 @@ +#include + +namespace lootlocker { + +namespace { + +Error Missing(const char* field) +{ + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = std::string("the session response is missing ") + field; + return e; +} + +// A required string. Absent, null and non-string are all failures, because a session field +// the SDK depends on must not be silently defaulted (D23). +bool ReadRequiredString(const JsonValue& j, const char* key, std::string& out, Error& error) +{ + const JsonValue value = j[key]; + if (value.GetKind() != JsonValue::Kind::String) { + error = Missing(key); + return false; + } + out = value.AsString(); + return true; +} + +// An optional string. Absent or null leaves `out` untouched; a present non-string is still +// an error, because that is a shape the API does not send and silently ignoring it would +// hide a contract change. +bool ReadOptionalString(const JsonValue& j, const char* key, std::string& out, Error& error) +{ + const JsonValue value = j[key]; + if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { + return true; + } + if (value.GetKind() != JsonValue::Kind::String) { + error = Missing(key); + return false; + } + out = value.AsString(); + return true; +} + +bool ReadOptionalBool(const JsonValue& j, const char* key, bool& out, Error& error) +{ + const JsonValue value = j[key]; + if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { + return true; + } + if (value.GetKind() != JsonValue::Kind::Bool) { + error = Missing(key); + return false; + } + out = value.AsBool(); + return true; +} + +} // namespace + +Result from_json(const JsonValue& j, Session& out) +{ + if (j.GetKind() != JsonValue::Kind::Object) { + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = "the session response is not an object"; + return Result::Fail(e); + } + + Error error; + + // Required: without these the session is unusable or the player cannot be identified. + if (!ReadRequiredString(j, "session_token", out.session_token, error) || + !ReadRequiredString(j, "player_identifier", out.player_identifier, error) || + !ReadRequiredString(j, "player_ulid", out.player_ulid, error) || + !ReadRequiredString(j, "public_uid", out.public_uid, error)) { + return Result::Fail(error); + } + + // `player_id` is required and must be an unsigned integer. Reading it through + // `AsDouble()` would lose precision above 2^53, which is the hazard D4 exists for. + const JsonValue player_id = j["player_id"]; + if (!player_id.IsUnsigned()) { + return Result::Fail(Missing("player_id")); + } + out.player_id = player_id.AsUInt64(); + + // Optional: an absent name genuinely means "not set", and the API omits the rest on + // some auth paths. + if (!ReadOptionalString(j, "player_name", out.player_name, error) || + !ReadOptionalString(j, "player_created_at", out.player_created_at, error) || + !ReadOptionalBool(j, "seen_before", out.seen_before, error) || + !ReadOptionalBool(j, "check_grant_notifications", out.check_grant_notifications, + error) || + !ReadOptionalBool(j, "check_deactivation_notifications", + out.check_deactivation_notifications, error)) { + return Result::Fail(error); + } + + return Result::Ok(Empty()); +} + +} // namespace lootlocker diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index e9f5dc6..009d838 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -80,6 +80,14 @@ add_executable(test_state_writer test_state_writer.cpp) target_link_libraries(test_state_writer PRIVATE LootLocker::core lootlocker_compile_options) add_test(NAME state_writer COMMAND test_state_writer) +# Guest auth (T14). Links the auth module, so it exercises the real module target rather +# than reaching into `core` directly. +if(TARGET LootLocker::auth) + add_executable(test_auth test_auth.cpp) + target_link_libraries(test_auth PRIVATE LootLocker::auth lootlocker_compile_options) + add_test(NAME auth COMMAND test_auth) +endif() + # 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_auth.cpp b/tests/test_auth.cpp new file mode 100644 index 0000000..e440561 --- /dev/null +++ b/tests/test_auth.cpp @@ -0,0 +1,491 @@ +// Guest auth (T14). +// +// The verification the task asks for: `auth::StartGuestSession` over +// `POST /game/v2/session/guest`, including `player_identifier` reuse across restarts. + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "test_harness.h" + +#include +#include +#include + +namespace { + +using lootlocker::Client; +using lootlocker::Config; +using lootlocker::ErrorCode; +using lootlocker::FakeHttpTransport; +using lootlocker::IHttpTransport; +using lootlocker::NullStateWriter; +using lootlocker::RequestId; +using lootlocker::Result; +using lootlocker::Session; + +// A scratch file that removes itself. +struct TempFile { + std::string path; + + explicit TempFile(const char* name) + { + path = std::string("test-auth-") + name + ".txt"; + std::remove(path.c_str()); + } + + ~TempFile() { std::remove(path.c_str()); } +}; + +Config MakeConfig() +{ + Config config; + config.domain_key = "testdomain"; + config.game_key = "testgamekey"; + config.game_version = "1.0.0"; + return config; +} + +// A config with no persistence, for the tests that do not care about it. +// +// Without this, a test that does not inject a writer falls back to the default +// `FileStateWriter`, which reads and writes `lootlocker-state.txt` in the working directory - +// so tests leak state into each other and into the developer's checkout. That is exactly +// what happened: a stale file made a sabotage test pass. +Config MakeConfigWithoutPersistence(std::shared_ptr& keep_alive) +{ + Config config = MakeConfig(); + keep_alive = std::make_shared(); + config.state_writer = keep_alive; + return config; +} + +// A successful guest session response, as the API sends it. +const char* kSessionBody = R"({ + "session_token": "tok-abc", + "player_identifier": "pid-1", + "player_ulid": "01ARZ3NDEKTSV4RRFFQ69G5FAV", + "public_uid": "ABCD1234", + "player_name": "Erik", + "player_id": 9007199254740993, + "player_created_at": "2026-01-01T00:00:00Z", + "seen_before": true, + "check_grant_notifications": false, + "check_deactivation_notifications": true +})"; + +struct Fixture { + std::shared_ptr transport; + std::unique_ptr client; + + explicit Fixture(const Config& config_in) + { + transport = std::make_shared(); + Config config = config_in; + config.transport = transport; + client.reset(new Client(config)); + } + + const IHttpTransport::Request* Sent() const + { + if (transport->Order().empty()) { + return nullptr; + } + return transport->FindRequest(transport->Order().front()); + } +}; + +// --- the request ----------------------------------------------------------- + +// The endpoint, method and body are what the API expects. +void TestGuestSessionRequest() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + CHECK_EQ(sent->method, "POST"); + CHECK_EQ(sent->url, "https://testdomain.api.lootlocker.com/game/v2/session/guest"); + + // The body carries the config's game key and version, the guest platform, and a + // generated identifier. + CHECK(sent->body.find(R"("game_key":"testgamekey")") != std::string::npos); + CHECK(sent->body.find(R"("game_version":"1.0.0")") != std::string::npos); + CHECK(sent->body.find(R"("platform":"guest")") != std::string::npos); + CHECK(sent->body.find(R"("player_identifier":")") != std::string::npos); + + // No session yet, so no token is sent. + CHECK(!sent->headers.Has("x-session-token")); +} + +// The optionals are sent only when set. +void TestOptionalsAreOmittedWhenEmpty() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + CHECK(sent->body.find("timezone") == std::string::npos); + CHECK(sent->body.find("locale") == std::string::npos); + CHECK(sent->body.find("player_name") == std::string::npos); +} + +void TestOptionalsAreSentWhenSet() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + lootlocker::GuestSessionOptions opts; + opts.timezone = "Europe/Stockholm"; + opts.locale = "sv-SE"; + opts.player_name = "Erik"; + + lootlocker::auth::StartGuestSession(*f.client, opts, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + CHECK(sent->body.find(R"("timezone":"Europe/Stockholm")") != std::string::npos); + CHECK(sent->body.find(R"("locale":"sv-SE")") != std::string::npos); + CHECK(sent->body.find(R"("player_name":"Erik")") != std::string::npos); +} + +// --- the response ---------------------------------------------------------- + +// A successful response is decoded, stored on the client, and delivered. +void TestSuccessfulSession() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + bool called = false; + Session received; + + lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { + called = true; + CHECK(result.Ok()); + if (result.Ok()) { + received = result.Value(); + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, kSessionBody); + f.client->Update(); + + CHECK(called); + CHECK_EQ(received.session_token, "tok-abc"); + CHECK_EQ(received.player_identifier, "pid-1"); + CHECK_EQ(received.player_ulid, "01ARZ3NDEKTSV4RRFFQ69G5FAV"); + CHECK_EQ(received.public_uid, "ABCD1234"); + CHECK_EQ(received.player_name, "Erik"); + CHECK(received.player_id == 9007199254740993ULL); // exact, above 2^53 + CHECK(received.seen_before); + CHECK(!received.check_grant_notifications); + CHECK(received.check_deactivation_notifications); + + // Stored on the client, so the caller does not have to remember to do it. + CHECK(f.client->HasSession()); + CHECK_EQ(f.client->GetSession().session_token, "tok-abc"); +} + +// The next request carries the token. +void TestSessionTokenIsSentOnSubsequentRequests() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, kSessionBody); + f.client->Update(); + + CHECK(f.client->HasSession()); + + // A second request, after the session exists. + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const auto order = f.transport->Order(); + CHECK_EQ_INT(static_cast(order.size()), 2); + if (order.size() < 2) { + return; + } + + const IHttpTransport::Request* second = f.transport->FindRequest(order[1]); + CHECK(second != nullptr); + if (second == nullptr) { + return; + } + + std::string token; + CHECK(second->headers.Get("x-session-token", token)); + CHECK_EQ(token, "tok-abc"); +} + +// A missing required field is a decode error, not a silent default (D23). +void TestMissingRequiredFieldIsAnError() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + bool called = false; + ErrorCode code = ErrorCode::None; + + lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { + called = true; + if (!result.Ok()) { + code = result.Error().code; + } + }); + + f.client->Update(); + // No session_token. + f.transport->Complete(f.transport->Order().front(), 200, + R"({"player_identifier":"p","player_ulid":"u","public_uid":"x","player_id":1})"); + f.client->Update(); + + CHECK(called); + CHECK(code == ErrorCode::MalformedResponse); + CHECK(!f.client->HasSession()); +} + +// An absent optional field is not an error: an absent name genuinely means "not set". +void TestMissingOptionalFieldIsFine() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + bool called = false; + bool ok = false; + + lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { + called = true; + ok = result.Ok(); + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, + R"({"session_token":"t","player_identifier":"p","player_ulid":"u",)" + R"("public_uid":"x","player_id":1})"); + f.client->Update(); + + CHECK(called); + CHECK(ok); + CHECK(f.client->HasSession()); + CHECK_EQ(f.client->GetSession().player_name, ""); +} + +// --- identifier reuse across restarts -------------------------------------- + +// The whole point of guest auth: the same identifier on the next launch, so the player is +// the same account. +// +// The writer is held in a named `shared_ptr` in each scope, not assigned as a temporary: +// `Config` holds a `weak_ptr`, so a temporary expires before the client is constructed and +// the SDK silently falls back to the default file - which would make this test pass for the +// wrong reason. +void TestPlayerIdentifierIsReusedAcrossRestarts() +{ + TempFile file("reuse"); + + std::string first_identifier; + + { + std::shared_ptr writer = + std::make_shared(file.path); + + Config config = MakeConfig(); + config.state_writer = writer; + + Fixture f(config); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + // Pull the identifier out of the body. + const std::string marker = R"("player_identifier":")"; + const std::size_t at = sent->body.find(marker); + CHECK(at != std::string::npos); + if (at != std::string::npos) { + const std::size_t start = at + marker.size(); + const std::size_t end = sent->body.find('"', start); + first_identifier = sent->body.substr(start, end - start); + } + } + CHECK(!first_identifier.empty()); + } + + // A new client, as if the game restarted, reading the same file. + { + std::shared_ptr writer = + std::make_shared(file.path); + + Config config = MakeConfig(); + config.state_writer = writer; + + Fixture f(config); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + const std::string marker = R"("player_identifier":")"; + const std::size_t at = sent->body.find(marker); + CHECK(at != std::string::npos); + if (at != std::string::npos) { + const std::size_t start = at + marker.size(); + const std::size_t end = sent->body.find('"', start); + const std::string second = sent->body.substr(start, end - start); + CHECK_EQ(second, first_identifier); + } + } + } +} + +// An explicit identifier wins over the persisted one. +void TestExplicitIdentifierWins() +{ + TempFile file("explicit"); + + std::shared_ptr writer = + std::make_shared(file.path); + + Config config = MakeConfig(); + config.state_writer = writer; + + Fixture f(config); + + lootlocker::GuestSessionOptions opts; + opts.player_identifier = "chosen-by-the-game"; + + lootlocker::auth::StartGuestSession(*f.client, opts, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + CHECK(sent->body.find(R"("player_identifier":"chosen-by-the-game")") != + std::string::npos); + } +} + +// With no persistence, every launch generates a new identifier - which is the documented +// cost of a `NullStateWriter`. +// +// The writer is held in a named `shared_ptr`, not assigned as a temporary: `Config` holds a +// `weak_ptr`, so `config.state_writer = std::make_shared<...>()` expires before the client +// is constructed and the SDK silently falls back to the file default. This test caught that +// exact mistake in its own first draft, which is why the README warns about it. +void TestNullWriterGeneratesNewIdentifierEachTime() +{ + std::string first; + std::string second; + + for (std::string* out : {&first, &second}) { + std::shared_ptr writer = std::make_shared(); + + Config config = MakeConfig(); + config.state_writer = writer; + + Fixture f(config); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + const std::string marker = R"("player_identifier":")"; + const std::size_t at = sent->body.find(marker); + if (at != std::string::npos) { + const std::size_t start = at + marker.size(); + const std::size_t end = sent->body.find('"', start); + *out = sent->body.substr(start, end - start); + } + } + } + + CHECK(!first.empty()); + CHECK(!second.empty()); + CHECK(first != second); +} + +// --- the client accessors -------------------------------------------------- + +void TestSessionAccessors() +{ + std::shared_ptr keep_alive; + Client client(MakeConfigWithoutPersistence(keep_alive)); + + CHECK(!client.HasSession()); + + Session session; + session.session_token = "t"; + client.SetSession(session); + + CHECK(client.HasSession()); + CHECK_EQ(client.GetSession().session_token, "t"); + + client.ClearSession(); + CHECK(!client.HasSession()); +} + +// The task's stated verification: the typed wrapper returns the id the executor assigned. +void TestReturnsExecutorId() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + const RequestId returned = + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + + CHECK(returned.IsValid()); +} + +} // namespace + +int main() +{ + TestGuestSessionRequest(); + TestOptionalsAreOmittedWhenEmpty(); + TestOptionalsAreSentWhenSet(); + TestSuccessfulSession(); + TestSessionTokenIsSentOnSubsequentRequests(); + TestMissingRequiredFieldIsAnError(); + TestMissingOptionalFieldIsFine(); + TestPlayerIdentifierIsReusedAcrossRestarts(); + TestExplicitIdentifierWins(); + TestNullWriterGeneratesNewIdentifierEachTime(); + TestSessionAccessors(); + TestReturnsExecutorId(); + return testing::Report(); +} From 3383fa0a0f8bf3da12919237362c51c0cb3cee7c Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Wed, 25 Nov 2026 14:54:36 +0100 Subject: [PATCH 2/4] Fix five review findings in guest auth The serious one: the request body was wrong. The backend's GuestInput embeds BaseInput and carries Optionals tagged json:"optionals", so timezone, locale, player_name and character_name at the root were silently ignored and every player got UTC. Verified against services/gamesession/models.go rather than inferred from the Unity SDK. The optionals are now a nested object, omitted entirely when empty. A 200 with an empty body became an all-default Session, so HasSession() reported true with no token. The generic Send treats an empty body as success because a 204 is the one legitimate empty success, which is wrong for a definition whose response carries required fields. Such a definition now opts out with kAllowEmptyResponse = false. The timezone was never resolved: an empty option sent nothing and Config::timezone, Config::timezone_provider and Config::send_timezone were all ignored. Now resolved in the documented order and normalised to an IANA name, because a Windows name sent as-is gets UTC server-side. An explicit player_identifier was not persisted, so a game that supplied one on the first launch and relied on the SDK afterwards got a different account on the next launch - the exact failure the mechanism exists to prevent. A present field of the wrong type reported "missing", which sends the reader looking in the wrong place. Wrong-type and missing are now distinct messages. Verified by sabotage: allowing an empty response fails two assertions, and flattening the optionals back to the root fails four. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/auth/auth.cpp | 119 ++++++++++++++++++++++------ src/core/definition.h | 22 +++++- src/core/session.cpp | 27 ++++++- tests/test_auth.cpp | 177 +++++++++++++++++++++++++++++++++++++++++- 4 files changed, 315 insertions(+), 30 deletions(-) diff --git a/src/auth/auth.cpp b/src/auth/auth.cpp index eb8b65b..0f381d4 100644 --- a/src/auth/auth.cpp +++ b/src/auth/auth.cpp @@ -2,6 +2,7 @@ #include #include +#include #include "core/definition.h" #include "core/query_parameters.h" @@ -45,16 +46,24 @@ std::string GeneratePlayerIdentifier() // The identifier to send: the caller's, else the persisted one, else a new one. // -// The resolved value is persisted *before* the request is sent. A crash between sending and -// receiving would otherwise lose the identifier and orphan the account the server just -// created - which is the single most damaging thing to lose (D8). +// **Whatever is chosen is persisted, including the caller's.** A game that supplies an +// identifier on the first launch and then relies on the SDK's persisted value would +// otherwise get a different account on the next launch - which is the failure this whole +// mechanism exists to prevent. +// +// The value is written *before* the request is sent. A crash between sending and receiving +// would otherwise lose the identifier and orphan the account the server just created. std::string ResolvePlayerIdentifier(Client& ll, const GuestSessionOptions& opts) { + std::shared_ptr writer = ll.GetStateWriter().lock(); + if (!opts.player_identifier.empty()) { + if (writer) { + writer->SetString(kPlayerIdentifierKey, opts.player_identifier); + } return opts.player_identifier; } - std::shared_ptr writer = ll.GetStateWriter().lock(); if (writer) { std::string persisted; if (writer->GetString(kPlayerIdentifierKey, persisted) && !persisted.empty()) { @@ -69,40 +78,93 @@ std::string ResolvePlayerIdentifier(Client& ll, const GuestSessionOptions& opts) return generated; } +// The timezone to send, or empty for "send none". +// +// Resolution order, per D26: the caller's option, then `Config::timezone`, then the injected +// `TimezoneProvider`, then the OS, then `Etc/UTC`. `Config::send_timezone == false` means +// send nothing at all, which is a different statement from "I have no opinion". +// +// The result is normalised to an IANA name, because a Windows name sent as-is gets UTC +// server-side and puts every local-day boundary on the wrong day (R27). +std::string ResolveTimezone(Client& ll, const GuestSessionOptions& opts) +{ + const Config& config = ll.GetConfig(); + if (!config.send_timezone) { + return std::string(); + } + + std::string candidate = opts.timezone; + if (candidate.empty()) { + candidate = config.timezone; + } + if (candidate.empty()) { + if (std::shared_ptr provider = config.timezone_provider.lock()) { + candidate = provider->GetTimezone(); + } + } + + std::string iana; + if (TryNormalizeToIana(candidate, iana)) { + return iana; + } + // `TryNormalizeToIana` sets the default on failure, so this is the documented fallback + // rather than an empty string the server would read as UTC. + return std::string(kDefaultIanaTimezone); +} + } // namespace // The request type lives in `lootlocker`, not the anonymous namespace, because the // definition in `core` names it and `to_json` is found by ADL. -struct GuestSessionRequest { - std::string game_key; - std::string game_version; - std::string player_identifier; - std::string platform; +// +// **`optionals` is a nested object, not root fields.** The backend's `GuestInput` embeds +// `BaseInput` and carries `Optionals Optionals` tagged `json:"optionals"`, so a `timezone` +// at the root is silently ignored and the player gets UTC. Verified against +// `services/gamesession/models.go` rather than inferred from the Unity SDK. +struct GuestSessionOptionals { std::string timezone; - std::string locale; std::string player_name; std::string character_name; + std::string locale; }; -void to_json(JsonBuilder& b, const GuestSessionRequest& in) +void to_json(JsonBuilder& b, const GuestSessionOptionals& in) { - b.Set("game_key", in.game_key); - b.Set("game_version", in.game_version); - b.Set("player_identifier", in.player_identifier); - b.Set("platform", in.platform); - if (!in.timezone.empty()) { b.Set("timezone", in.timezone); } - if (!in.locale.empty()) { - b.Set("locale", in.locale); - } if (!in.player_name.empty()) { b.Set("player_name", in.player_name); } if (!in.character_name.empty()) { b.Set("character_name", in.character_name); } + if (!in.locale.empty()) { + b.Set("locale", in.locale); + } +} + +struct GuestSessionRequest { + std::string game_key; + std::string game_version; + std::string player_identifier; + std::string platform; + GuestSessionOptionals optionals; + bool has_optionals = false; +}; + +void to_json(JsonBuilder& b, const GuestSessionRequest& in) +{ + b.Set("game_key", in.game_key); + b.Set("game_version", in.game_version); + b.Set("player_identifier", in.player_identifier); + b.Set("platform", in.platform); + + // Omitted entirely when nothing is set: the backend defaults an absent `optionals` to + // UTC, and an empty object is noise. + if (in.has_optionals) { + b.Set("optionals", in.optionals); + } } namespace core { @@ -111,6 +173,11 @@ struct GuestSessionDef { static constexpr const char* kMethod = "POST"; static constexpr const char* kPath = "/game/v2/session/guest"; + // A session response carries required fields, so an empty body is a malformed response + // rather than a success. Without this a 200 with no body would become an all-default + // `Session` and `HasSession()` would report true with no token. + static constexpr bool kAllowEmptyResponse = false; + using Request = GuestSessionRequest; using Response = Session; @@ -138,10 +205,16 @@ RequestId StartGuestSession(Client& ll, const GuestSessionOptions& opts, request.game_version = config.game_version; request.platform = "guest"; request.player_identifier = ResolvePlayerIdentifier(ll, opts); - request.timezone = opts.timezone; - request.locale = opts.locale; - request.player_name = opts.player_name; - request.character_name = opts.character_name; + + request.optionals.timezone = ResolveTimezone(ll, opts); + request.optionals.locale = opts.locale; + request.optionals.player_name = opts.player_name; + request.optionals.character_name = opts.character_name; + + request.has_optionals = !request.optionals.timezone.empty() || + !request.optionals.locale.empty() || + !request.optionals.player_name.empty() || + !request.optionals.character_name.empty(); return core::Send( ll, request, [&ll, on_done](Result result) { diff --git a/src/core/definition.h b/src/core/definition.h index cd854ef..ec0e4d0 100644 --- a/src/core/definition.h +++ b/src/core/definition.h @@ -161,6 +161,20 @@ inline HeaderMap BuildDefaultHeaders(const Client& client) return headers; } +// Whether a definition's response type can legitimately be empty. +// +// The generic `Send` treats an empty body as success, because a 204 is the one legitimate +// empty success (`EndSession`). That is wrong for a definition whose response carries +// required fields: a 200 with an empty body would become an all-default `Session`, and +// `HasSession()` would report true with no token. Such a definition opts out by declaring +// `static constexpr bool kAllowEmptyResponse = false;`. +template +struct AllowsEmptyResponse : std::true_type {}; + +template +struct AllowsEmptyResponse + : std::integral_constant {}; + // Sends one request described by `Def` and delivers the decoded response to `on_done`. // // Returns the id the executor assigned, which is the same id sent as `LL-Request-Id`. The @@ -200,9 +214,15 @@ RequestId Send(Client& client, const typename Def::Request& request, // documents it as such. Parsing an empty body would report `MalformedResponse` // for a request that succeeded, so it is handled before the parser sees it. // + // A definition whose response carries required fields opts out with + // `kAllowEmptyResponse = false`, because for it an empty body is a malformed + // response rather than a success - a 200 with no body must not become an + // all-default value that looks valid. + // // `NormalizeResponse` still runs, because a definition may want to fill in // derived fields on an empty response too. - if (completion.status_code == 204 || completion.body.empty()) { + if (completion.status_code == 204 || + (completion.body.empty() && AllowsEmptyResponse::value)) { typename Def::Response response; RawResponse raw; diff --git a/src/core/session.cpp b/src/core/session.cpp index 71092a4..3ca495b 100644 --- a/src/core/session.cpp +++ b/src/core/session.cpp @@ -12,15 +12,30 @@ Error Missing(const char* field) return e; } +// A present field of the wrong type. Distinct from "missing", because the two are different +// bugs and a message that says "missing" for a present field sends the reader looking in the +// wrong place. +Error WrongType(const char* field, const char* expected) +{ + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = std::string("the session response has a non-") + expected + " " + field; + return e; +} + // A required string. Absent, null and non-string are all failures, because a session field // the SDK depends on must not be silently defaulted (D23). bool ReadRequiredString(const JsonValue& j, const char* key, std::string& out, Error& error) { const JsonValue value = j[key]; - if (value.GetKind() != JsonValue::Kind::String) { + if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { error = Missing(key); return false; } + if (value.GetKind() != JsonValue::Kind::String) { + error = WrongType(key, "string"); + return false; + } out = value.AsString(); return true; } @@ -35,7 +50,7 @@ bool ReadOptionalString(const JsonValue& j, const char* key, std::string& out, E return true; } if (value.GetKind() != JsonValue::Kind::String) { - error = Missing(key); + error = WrongType(key, "string"); return false; } out = value.AsString(); @@ -49,7 +64,7 @@ bool ReadOptionalBool(const JsonValue& j, const char* key, bool& out, Error& err return true; } if (value.GetKind() != JsonValue::Kind::Bool) { - error = Missing(key); + error = WrongType(key, "boolean"); return false; } out = value.AsBool(); @@ -80,9 +95,13 @@ Result from_json(const JsonValue& j, Session& out) // `player_id` is required and must be an unsigned integer. Reading it through // `AsDouble()` would lose precision above 2^53, which is the hazard D4 exists for. const JsonValue player_id = j["player_id"]; - if (!player_id.IsUnsigned()) { + if (player_id.GetKind() == JsonValue::Kind::Invalid || + player_id.GetKind() == JsonValue::Kind::Null) { return Result::Fail(Missing("player_id")); } + if (!player_id.IsUnsigned()) { + return Result::Fail(WrongType("player_id", "unsigned integer")); + } out.player_id = player_id.AsUInt64(); // Optional: an absent name genuinely means "not set", and the API omits the rest on diff --git a/tests/test_auth.cpp b/tests/test_auth.cpp index e440561..5ce399e 100644 --- a/tests/test_auth.cpp +++ b/tests/test_auth.cpp @@ -132,7 +132,9 @@ void TestGuestSessionRequest() CHECK(!sent->headers.Has("x-session-token")); } -// The optionals are sent only when set. +// The optionals are sent only when set. `timezone` is the exception: it is resolved from the +// config, the provider and finally the default, so it is always present unless +// `send_timezone` is false (covered by `TestSendTimezoneFalse`). void TestOptionalsAreOmittedWhenEmpty() { std::shared_ptr keep_alive; @@ -147,9 +149,9 @@ void TestOptionalsAreOmittedWhenEmpty() return; } - CHECK(sent->body.find("timezone") == std::string::npos); CHECK(sent->body.find("locale") == std::string::npos); CHECK(sent->body.find("player_name") == std::string::npos); + CHECK(sent->body.find("character_name") == std::string::npos); } void TestOptionalsAreSentWhenSet() @@ -439,6 +441,171 @@ void TestNullWriterGeneratesNewIdentifierEachTime() CHECK(first != second); } +// The optionals are nested under `optionals`, not at the root. The backend's `GuestInput` +// carries `Optionals Optionals` tagged `json:"optionals"`, so a root-level `timezone` is +// silently ignored and the player gets UTC. +void TestOptionalsAreNested() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + lootlocker::GuestSessionOptions opts; + opts.timezone = "Europe/Stockholm"; + opts.locale = "sv-SE"; + opts.player_name = "Erik"; + + lootlocker::auth::StartGuestSession(*f.client, opts, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + CHECK(sent->body.find(R"("optionals":{)") != std::string::npos); + CHECK(sent->body.find(R"("timezone":"Europe/Stockholm")") != std::string::npos); + CHECK(sent->body.find(R"("locale":"sv-SE")") != std::string::npos); + CHECK(sent->body.find(R"("player_name":"Erik")") != std::string::npos); + + // And not at the root: the only root-level keys are the four the API expects. + const std::size_t optionals_at = sent->body.find(R"("optionals")"); + CHECK(sent->body.find(R"("timezone")") > optionals_at); +} + +// The timezone falls back to the config, then the provider, then the default - and is +// normalised to an IANA name, because a Windows name sent as-is gets UTC server-side. +void TestTimezoneResolution() +{ + std::shared_ptr keep_alive; + + // A Windows name in the config is normalised. + Config config = MakeConfigWithoutPersistence(keep_alive); + config.timezone = "W. Europe Standard Time"; + + Fixture f(config); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + CHECK(sent->body.find(R"("timezone":"Europe/Berlin")") != std::string::npos); + } +} + +// `send_timezone = false` sends no timezone at all, which is a different statement from +// "I have no opinion". +void TestSendTimezoneFalse() +{ + std::shared_ptr keep_alive; + Config config = MakeConfigWithoutPersistence(keep_alive); + config.send_timezone = false; + + Fixture f(config); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + CHECK(sent->body.find("timezone") == std::string::npos); + } +} + +// A 200 with an empty body is a malformed response for a definition whose response carries +// required fields. Without this it would become an all-default `Session` and `HasSession()` +// would report true with no token. +void TestEmptyBodyIsNotASuccess() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + bool called = false; + ErrorCode code = ErrorCode::None; + + lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { + called = true; + if (!result.Ok()) { + code = result.Error().code; + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, ""); + f.client->Update(); + + CHECK(called); + CHECK(code == ErrorCode::MalformedResponse); + CHECK(!f.client->HasSession()); +} + +// A present field of the wrong type says so, rather than claiming it is missing. +void TestWrongTypeMessage() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + std::string message; + + lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { + if (!result.Ok()) { + message = result.Error().message; + } + }); + + f.client->Update(); + // `session_token` is present but a number. + f.transport->Complete(f.transport->Order().front(), 200, + R"({"session_token":42,"player_identifier":"p","player_ulid":"u",)" + R"("public_uid":"x","player_id":1})"); + f.client->Update(); + + CHECK(message.find("non-string") != std::string::npos); + CHECK(message.find("missing") == std::string::npos); +} + +// An explicit identifier is persisted too, so a game that supplies one on the first launch +// and relies on the SDK afterwards does not get a different account. +void TestExplicitIdentifierIsPersisted() +{ + TempFile file("explicit-persist"); + + std::shared_ptr writer = + std::make_shared(file.path); + + Config config = MakeConfig(); + config.state_writer = writer; + + { + Fixture f(config); + + lootlocker::GuestSessionOptions opts; + opts.player_identifier = "chosen-by-the-game"; + + lootlocker::auth::StartGuestSession(*f.client, opts, [](Result) {}); + f.client->Update(); + } + + // A second launch, with no explicit identifier: the persisted one is used. + std::shared_ptr reopened = + std::make_shared(file.path); + + Config second = MakeConfig(); + second.state_writer = reopened; + + Fixture f(second); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + CHECK(sent->body.find(R"("player_identifier":"chosen-by-the-game")") != + std::string::npos); + } +} + // --- the client accessors -------------------------------------------------- void TestSessionAccessors() @@ -484,7 +651,13 @@ int main() TestMissingOptionalFieldIsFine(); TestPlayerIdentifierIsReusedAcrossRestarts(); TestExplicitIdentifierWins(); + TestExplicitIdentifierIsPersisted(); TestNullWriterGeneratesNewIdentifierEachTime(); + TestOptionalsAreNested(); + TestTimezoneResolution(); + TestSendTimezoneFalse(); + TestEmptyBodyIsNotASuccess(); + TestWrongTypeMessage(); TestSessionAccessors(); TestReturnsExecutorId(); return testing::Report(); From 252f1d5f626fb1c6d891db3d2f5e9a523f8930ed Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Thu, 26 Nov 2026 11:36:59 +0100 Subject: [PATCH 3/4] Restructure guest auth per review Twelve findings, several of them design changes. The optionals were wrong. locale and character_name were invented - the backend's optionals are timezone, player_name, auto_create_profile, check_dlc, referral_code and referral_program_key. A field equal to the backend's default is now omitted rather than sent. GuestSessionOptions is now GuestSessionInputs, holding an Optional guest_identifier and an Optional SessionOptionals. The identifier is not part of optionals on the wire, so putting it there made the SDK's shape disagree with the backend's. The input struct is the general pattern for every SDK method from here. The session token is no longer sent on authentication requests. An authentication request is not an authenticated request by definition, and a stale token from a previous session has no business being sent to it. A definition opts out with kRequiresSession = false. The persisted key is guest_identifier, not player_identifier: the wire field is player_identifier on every platform, but only on guest is it a client-generated value. Platform is now an enum with wire names matching the other SDKs, so a typo is a compile error rather than a runtime 400. The JSON field readers moved into the core JSON layer. Every decoder needs the same three questions answered, and writing them per type is how two decoders end up disagreeing about whether a null counts as absent. The static_asserts on Session are gone - they guarded against someone changing a type, which is not a thing that happens. DefinitionTraits replaces them with asserts that name what a definition is missing, which is the real benefit an interface would have offered without the vtable. Also: make_unique in the tests, and a note that multi-session is deliberately deferred. Verified by sabotage: always sending the token fails the auth-request test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CMakeLists.txt | 1 + README.md | 33 ++- include/lootlocker/auth.h | 76 +++-- include/lootlocker/platform.h | 50 ++++ include/lootlocker/session.h | 8 - src/auth/auth.cpp | 125 +++++--- src/core/definition.h | 38 +++ src/core/executor.cpp | 5 +- src/core/executor.h | 4 + src/core/json.cpp | 88 ++++++ src/core/json.h | 31 ++ src/core/platform.cpp | 79 ++++++ src/core/session.cpp | 108 +------ tests/test_auth.cpp | 516 ++++++++++++++++------------------ 14 files changed, 719 insertions(+), 443 deletions(-) create mode 100644 include/lootlocker/platform.h create mode 100644 src/core/platform.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2b8db58..8bc6563 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -142,6 +142,7 @@ add_library(lootlocker_core STATIC src/core/request_id.cpp src/core/rate_limiter.cpp src/core/json.cpp + src/core/platform.cpp src/core/query_parameters.cpp src/core/session.cpp src/core/state_writer.cpp diff --git a/README.md b/README.md index b0d2515..1549ed1 100644 --- a/README.md +++ b/README.md @@ -347,27 +347,38 @@ while (ll.Update()) { } ``` -**The identifier reuse is the whole point.** A guest who loses their `player_identifier` -silently becomes a new account with no inventory, so the SDK persists it and sends it back -on the next launch. You do not have to do anything: the resolved identifier is written -*before* the request is sent, so a crash between sending and receiving does not orphan the -account the server just created. +**The identifier reuse is the whole point.** A guest who loses their identifier silently +becomes a new account with no inventory, so the SDK persists it and sends it back on the next +launch. You do not have to do anything: the resolved identifier is written *before* the +request is sent, so a crash between sending and receiving does not orphan the account the +server just created. -The resolution order is: `GuestSessionOptions::player_identifier` if you set it, then the +The resolution order is: `GuestSessionInputs::guest_identifier` if you set it, then the persisted one, then a newly generated one. Setting it explicitly is for a game that manages -its own identity; leaving it empty is what almost every caller wants. +its own identity; leaving it unset is what almost every caller wants. A successful session is stored on the client, so subsequent requests carry `x-session-token` and `ll.GetSession()` returns it. `ll.HasSession()` is the cheap check. +**The token is never sent on an authentication request** — an authentication request is not +an authenticated request by definition. ```cpp -lootlocker::GuestSessionOptions opts; -opts.timezone = "Europe/Stockholm"; // empty = resolve: provider, then OS, then Etc/UTC -opts.player_name = "Erik"; +lootlocker::GuestSessionInputs inputs; -lootlocker::auth::StartGuestSession(ll, opts, on_session); +lootlocker::SessionOptionals optionals; +optionals.timezone = "Europe/Stockholm"; // empty = resolve: provider, then OS, then Etc/UTC +optionals.player_name = "Erik"; +optionals.check_dlc = true; + +inputs.optionals = optionals; + +lootlocker::auth::StartGuestSession(ll, inputs, on_session); ``` +`SessionOptionals` is the backend's `optionals` object verbatim — `timezone`, `player_name`, +`auto_create_profile`, `check_dlc`, `referral_code`, `referral_program_key`. A field equal to +the backend's default is omitted rather than sent. + With a `NullStateWriter` every launch generates a new identifier, which is the documented cost of choosing not to persist. diff --git a/include/lootlocker/auth.h b/include/lootlocker/auth.h index 60a9de4..89f0884 100644 --- a/include/lootlocker/auth.h +++ b/include/lootlocker/auth.h @@ -4,35 +4,75 @@ // // A guest session is the MVP's primary auth path: no credentials, no platform, just an // identifier the SDK generates once and reuses. **The reuse is the whole point** - a guest -// who loses their `player_identifier` silently becomes a new account with no inventory, so -// the SDK persists it (D8) and sends it back on the next launch. +// who loses their identifier silently becomes a new account with no inventory, so the SDK +// persists it (D8) and sends it back on the next launch. // // The identifier is generated here rather than by the caller, because a caller that has to // invent one will invent a different one on the next launch. #include +#include #include #include #include #include +#include #include namespace lootlocker { -// Everything the API calls `optionals`. All of it is optional: a session start needs only -// `game_key` and `game_version`, which live in `Config`. -struct GuestSessionOptions { - // Reuse it to keep the same guest across launches. Empty means "use the persisted one, - // or generate a new one" - which is what almost every caller wants. - std::string player_identifier; - - // Empty means "resolve it": the injected provider, then the OS, then `Etc/UTC` (D26). +// The backend's `optionals` object, verbatim. +// +// **Named `optionals`, not `options`.** It is the backend's term for "a set of optional +// values", and `options` invokes a different meaning - configuration rather than +// per-request optional data. The other SDKs use the backend term for the same reason. +// +// Every field is optional, and the defaults are the backend's: an absent `timezone` means +// UTC, an absent `auto_create_profile` means true. +struct SessionOptionals { + // IANA format. Empty means "resolve it": the injected provider, then the OS, then + // `Etc/UTC` (D26). std::string timezone; - std::string locale; + // The player's display name. Empty means "leave it as it is". std::string player_name; - std::string character_name; + + // Whether to create a profile for a player who does not have one. Defaults to true; + // false makes the session fail with a 404 for an unknown player. + bool auto_create_profile = true; + + // Whether the client reports owning DLC, so the server reconciles ownership at session + // start. Defaults to false. + bool check_dlc = false; + + // The referrer's public UID, for attributing a referral on a first session. Ignored for + // returning players. + std::string referral_code; + + // The referral program the code redeems. Omit when the game has a single active program. + std::string referral_program_key; +}; + +// Everything a guest session start takes. +// +// **An input struct rather than parameters plus overloads** (owner, 2026-11-26). Two +// optional parameters is four overloads and four is sixteen; a struct is one shape that +// gains fields without breaking callers. The zero-argument `StartGuestSession(ll, cb)` stays +// as the common call. +// +// Both fields are `Optional` because neither is required, and "unset" is a different +// statement from "set to empty" - the same distinction `Config::send_timezone` exists to +// preserve. +struct GuestSessionInputs { + // The guest identifier to use. Unset means "use the persisted one, or generate a new + // one", which is what almost every caller wants. + // + // **Not part of `optionals`.** The backend's `optionals` object does not contain it, and + // muddling the two would make the SDK's shape disagree with the wire's. + std::optional guest_identifier; + + std::optional optionals; }; using SessionCallback = std::function)>; @@ -44,16 +84,20 @@ namespace auth { // Starts a guest session and stores it on the client, so subsequent requests carry // `x-session-token` and `Client::GetSession()` returns it. // -// **The identifier is resolved in this order:** `opts.player_identifier` if set, then the -// one persisted by a previous session, then a newly generated one. The resolved value is +// **The identifier is resolved in this order:** `inputs.guest_identifier` if set, then the +// one persisted by a previous session, then a newly generated one. Whatever is chosen is // persisted before the request is sent, so a crash between sending and receiving does not -// lose the identifier and orphan the account. +// lose it and orphan the account. +// +// **The session token is never sent on this request.** An authentication request is not an +// authenticated request, so attaching a token to it is wrong by definition - and a stale +// token from a previous session would be sent to an endpoint that has no use for it. // // Returns the id the executor assigned. The callback fires on the thread that calls // `Client::Update()` (D5). RequestId StartGuestSession(Client& ll, SessionCallback on_done); -RequestId StartGuestSession(Client& ll, const GuestSessionOptions& opts, +RequestId StartGuestSession(Client& ll, const GuestSessionInputs& inputs, SessionCallback on_done); } // namespace auth diff --git a/include/lootlocker/platform.h b/include/lootlocker/platform.h new file mode 100644 index 0000000..abc8ed8 --- /dev/null +++ b/include/lootlocker/platform.h @@ -0,0 +1,50 @@ +#pragma once + +// The auth platform (D16, T14 review). +// +// A wire value, not a free string. The API accepts a fixed set of platform names and rejects +// anything else, so a typo in a string literal is a runtime 400 that a type would have caught +// at compile time. The names match the other SDKs' `LL_AuthPlatforms` exactly, because the +// backend compares them literally. + +#include +#include + +#include + +namespace lootlocker { + +enum class Platform { + None = 0, + Guest, + WhiteLabel, + Steam, + PlayStationNetwork, + XboxOne, + NintendoSwitch, + AmazonLuna, + AppleSignIn, + AppleGameCenter, + Android, + GoogleSignIn, + GooglePlayGames, + EpicGames, + Meta, + Remote, + Discord, +}; + +// The wire name, e.g. `"guest"`. Never null. +const char* ToString(Platform platform); + +// Parses a wire name. Returns false and leaves `out` untouched when the name is unknown, +// rather than defaulting to `None` - an unknown platform is a contract change, not a +// missing value. +bool TryParsePlatform(const std::string& name, Platform& out); + +// The ADL deserialiser, so a platform round-trips through the JSON layer like any other +// field (D27). There is no `to_json`: a `JsonBuilder` writes into an object, so a bare enum +// has no key to write under. A caller serialises with `b.Set("platform", ToString(p))`. +Result from_json(const JsonValue& j, Platform& out); + +} // namespace lootlocker diff --git a/include/lootlocker/session.h b/include/lootlocker/session.h index 420650d..7132b7f 100644 --- a/include/lootlocker/session.h +++ b/include/lootlocker/session.h @@ -10,7 +10,6 @@ #include #include -#include namespace lootlocker { @@ -27,13 +26,6 @@ struct Session { bool check_deactivation_notifications = false; }; -// `player_id` must stay `uint64`. The D4 spike showed both candidate parsers preserve it -// exactly; the hazard is a `double` field in our own structs, so the type is enforced here -// rather than left to review. -static_assert(sizeof(Session::player_id) == 8, "player_id must be 64-bit"); -static_assert(!std::is_floating_point::value, - "player_id must not be a floating-point type (D4)"); - // Decodes a session response (D27). // // **Which fields are required, and why that is not a silent default.** D23 says a missing diff --git a/src/auth/auth.cpp b/src/auth/auth.cpp index 0f381d4..bc24791 100644 --- a/src/auth/auth.cpp +++ b/src/auth/auth.cpp @@ -16,16 +16,21 @@ namespace lootlocker { namespace { -// The keys the SDK persists. Named here rather than inline so a typo is a compile error +// The key the SDK persists. Named here rather than inline so a typo is a compile error // rather than a silently missing key. -const char* const kPlayerIdentifierKey = "player_identifier"; +// +// **`guest_identifier`, not `player_identifier`.** The wire field is `player_identifier` on +// every platform, but only on guest is it a client-generated value; on the others the server +// owns it. Naming the persisted key after the concept rather than the wire field keeps the +// two from being confused. +const char* const kGuestIdentifierKey = "guest_identifier"; // A guest identifier: a UUID-shaped random string. // // Not a security token - the server treats it as an opaque account handle - so // `std::random_device` is the right tool rather than a cryptographic generator. It only has // to be unlikely to collide, and it must be stable once persisted. -std::string GeneratePlayerIdentifier() +std::string GenerateGuestIdentifier() { std::random_device device; std::uint64_t high = (static_cast(device()) << 32) ^ device(); @@ -53,27 +58,27 @@ std::string GeneratePlayerIdentifier() // // The value is written *before* the request is sent. A crash between sending and receiving // would otherwise lose the identifier and orphan the account the server just created. -std::string ResolvePlayerIdentifier(Client& ll, const GuestSessionOptions& opts) +std::string ResolveGuestIdentifier(Client& ll, const GuestSessionInputs& inputs) { std::shared_ptr writer = ll.GetStateWriter().lock(); - if (!opts.player_identifier.empty()) { + if (inputs.guest_identifier.has_value() && !inputs.guest_identifier->empty()) { if (writer) { - writer->SetString(kPlayerIdentifierKey, opts.player_identifier); + writer->SetString(kGuestIdentifierKey, *inputs.guest_identifier); } - return opts.player_identifier; + return *inputs.guest_identifier; } if (writer) { std::string persisted; - if (writer->GetString(kPlayerIdentifierKey, persisted) && !persisted.empty()) { + if (writer->GetString(kGuestIdentifierKey, persisted) && !persisted.empty()) { return persisted; } } - const std::string generated = GeneratePlayerIdentifier(); + const std::string generated = GenerateGuestIdentifier(); if (writer) { - writer->SetString(kPlayerIdentifierKey, generated); + writer->SetString(kGuestIdentifierKey, generated); } return generated; } @@ -86,14 +91,14 @@ std::string ResolvePlayerIdentifier(Client& ll, const GuestSessionOptions& opts) // // The result is normalised to an IANA name, because a Windows name sent as-is gets UTC // server-side and puts every local-day boundary on the wrong day (R27). -std::string ResolveTimezone(Client& ll, const GuestSessionOptions& opts) +std::string ResolveTimezone(Client& ll, const SessionOptionals& optionals) { const Config& config = ll.GetConfig(); if (!config.send_timezone) { return std::string(); } - std::string candidate = opts.timezone; + std::string candidate = optionals.timezone; if (candidate.empty()) { candidate = config.timezone; } @@ -112,23 +117,20 @@ std::string ResolveTimezone(Client& ll, const GuestSessionOptions& opts) return std::string(kDefaultIanaTimezone); } -} // namespace - -// The request type lives in `lootlocker`, not the anonymous namespace, because the -// definition in `core` names it and `to_json` is found by ADL. +// The backend's `optionals` object, serialised only when it carries something. // -// **`optionals` is a nested object, not root fields.** The backend's `GuestInput` embeds -// `BaseInput` and carries `Optionals Optionals` tagged `json:"optionals"`, so a `timezone` -// at the root is silently ignored and the player gets UTC. Verified against -// `services/gamesession/models.go` rather than inferred from the Unity SDK. -struct GuestSessionOptionals { +// The defaults are the backend's, so a field equal to its default is omitted rather than +// sent - which keeps the body small and makes "the caller did not care" visible on the wire. +struct SessionOptionalsBody { std::string timezone; std::string player_name; - std::string character_name; - std::string locale; + bool auto_create_profile = true; + bool check_dlc = false; + std::string referral_code; + std::string referral_program_key; }; -void to_json(JsonBuilder& b, const GuestSessionOptionals& in) +void to_json(JsonBuilder& b, const SessionOptionalsBody& in) { if (!in.timezone.empty()) { b.Set("timezone", in.timezone); @@ -136,20 +138,32 @@ void to_json(JsonBuilder& b, const GuestSessionOptionals& in) if (!in.player_name.empty()) { b.Set("player_name", in.player_name); } - if (!in.character_name.empty()) { - b.Set("character_name", in.character_name); + if (!in.auto_create_profile) { + b.Set("auto_create_profile", false); + } + if (in.check_dlc) { + b.Set("check_dlc", true); + } + if (!in.referral_code.empty()) { + b.Set("referral_code", in.referral_code); } - if (!in.locale.empty()) { - b.Set("locale", in.locale); + if (!in.referral_program_key.empty()) { + b.Set("referral_program_key", in.referral_program_key); } } +// The request body. +// +// **`optionals` is a nested object, not root fields.** The backend's `GuestInput` embeds +// `BaseInput` and carries `Optionals Optionals` tagged `json:"optionals"`, so a `timezone` +// at the root is silently ignored and the player gets UTC. Verified against +// `services/gamesession/models.go` rather than inferred from the Unity SDK. struct GuestSessionRequest { std::string game_key; std::string game_version; std::string player_identifier; - std::string platform; - GuestSessionOptionals optionals; + Platform platform = Platform::Guest; + SessionOptionalsBody optionals; bool has_optionals = false; }; @@ -158,7 +172,7 @@ void to_json(JsonBuilder& b, const GuestSessionRequest& in) b.Set("game_key", in.game_key); b.Set("game_version", in.game_version); b.Set("player_identifier", in.player_identifier); - b.Set("platform", in.platform); + b.Set("platform", ToString(in.platform)); // Omitted entirely when nothing is set: the backend defaults an absent `optionals` to // UTC, and an empty object is noise. @@ -167,6 +181,8 @@ void to_json(JsonBuilder& b, const GuestSessionRequest& in) } } +} // namespace + namespace core { struct GuestSessionDef { @@ -178,6 +194,11 @@ struct GuestSessionDef { // `Session` and `HasSession()` would report true with no token. static constexpr bool kAllowEmptyResponse = false; + // An authentication request is not an authenticated request, so it must not carry a + // session token. A stale token from a previous session would otherwise be sent to an + // endpoint that has no use for it. + static constexpr bool kRequiresSession = false; + using Request = GuestSessionRequest; using Response = Session; @@ -192,10 +213,10 @@ namespace auth { RequestId StartGuestSession(Client& ll, SessionCallback on_done) { - return StartGuestSession(ll, GuestSessionOptions(), std::move(on_done)); + return StartGuestSession(ll, GuestSessionInputs(), std::move(on_done)); } -RequestId StartGuestSession(Client& ll, const GuestSessionOptions& opts, +RequestId StartGuestSession(Client& ll, const GuestSessionInputs& inputs, SessionCallback on_done) { const Config& config = ll.GetConfig(); @@ -203,18 +224,32 @@ RequestId StartGuestSession(Client& ll, const GuestSessionOptions& opts, GuestSessionRequest request; request.game_key = config.game_key; request.game_version = config.game_version; - request.platform = "guest"; - request.player_identifier = ResolvePlayerIdentifier(ll, opts); - - request.optionals.timezone = ResolveTimezone(ll, opts); - request.optionals.locale = opts.locale; - request.optionals.player_name = opts.player_name; - request.optionals.character_name = opts.character_name; - - request.has_optionals = !request.optionals.timezone.empty() || - !request.optionals.locale.empty() || - !request.optionals.player_name.empty() || - !request.optionals.character_name.empty(); + request.platform = Platform::Guest; + request.player_identifier = ResolveGuestIdentifier(ll, inputs); + + if (inputs.optionals.has_value()) { + const SessionOptionals& in = *inputs.optionals; + + request.optionals.timezone = ResolveTimezone(ll, in); + request.optionals.player_name = in.player_name; + request.optionals.auto_create_profile = in.auto_create_profile; + request.optionals.check_dlc = in.check_dlc; + request.optionals.referral_code = in.referral_code; + request.optionals.referral_program_key = in.referral_program_key; + + request.has_optionals = !request.optionals.timezone.empty() || + !request.optionals.player_name.empty() || + !request.optionals.auto_create_profile || + request.optionals.check_dlc || + !request.optionals.referral_code.empty() || + !request.optionals.referral_program_key.empty(); + } else { + // No optionals supplied, but the timezone is still resolved: it is a config-level + // concern rather than a per-call one, and a game that set `Config::timezone` expects + // it to be sent. + request.optionals.timezone = ResolveTimezone(ll, SessionOptionals()); + request.has_optionals = !request.optionals.timezone.empty(); + } return core::Send( ll, request, [&ll, on_done](Result result) { diff --git a/src/core/definition.h b/src/core/definition.h index ec0e4d0..89e2ba1 100644 --- a/src/core/definition.h +++ b/src/core/definition.h @@ -161,6 +161,19 @@ inline HeaderMap BuildDefaultHeaders(const Client& client) return headers; } +// Whether a definition's request should carry `x-session-token`. +// +// True by default, because most requests are authenticated. A definition opts out with +// `static constexpr bool kRequiresSession = false;` - which an authentication request must, +// because an authentication request is not an authenticated request by definition, and a +// stale token from a previous session has no business being sent to it. +template +struct RequiresSession : std::true_type {}; + +template +struct RequiresSession + : std::integral_constant {}; + // Whether a definition's response type can legitimately be empty. // // The generic `Send` treats an empty body as success, because a 204 is the one legitimate @@ -175,6 +188,26 @@ template struct AllowsEmptyResponse : std::integral_constant {}; +// What a definition must provide, checked at compile time. +// +// Without this a missing member is a template error inside `Send`, which names a line in +// `definition.h` rather than the definition that is wrong. The asserts turn that into a +// message that says what is missing and where. +// +// This is the answer to "should there be an interface for definitions": the enforcement is +// real, and it costs no vtable and no base class. +template +struct DefinitionTraits { + static_assert(std::is_convertible::value, + "a definition must provide `static constexpr const char* kMethod`"); + static_assert(std::is_convertible::value, + "a definition must provide `static constexpr const char* kPath`"); + static_assert(std::is_class::value, + "a definition must provide `using Request = ...`"); + static_assert(std::is_class::value, + "a definition must provide `using Response = ...`"); +}; + // Sends one request described by `Def` and delivers the decoded response to `on_done`. // // Returns the id the executor assigned, which is the same id sent as `LL-Request-Id`. The @@ -195,6 +228,11 @@ RequestId Send(Client& client, const typename Def::Request& request, pending.headers = BuildDefaultHeaders(client); pending.body = BuildBody(request); + // The definition says whether this request is authenticated. An authentication request + // is not, so it must not carry a token - and a stale one from a previous session has no + // business being sent to it. + pending.requires_session = RequiresSession::value; + if (!pending.body.empty()) { pending.headers.Set("Content-Type", "application/json"); } diff --git a/src/core/executor.cpp b/src/core/executor.cpp index 5a9501e..b812ad4 100644 --- a/src/core/executor.cpp +++ b/src/core/executor.cpp @@ -529,8 +529,9 @@ bool Executor::Update() // // Set here rather than by a definition, because it is identical for every // endpoint and a definition that forgot it would produce a 401 that looks like - // an auth bug. - if (m_session_token) { + // an auth bug. A definition that is itself an authentication request opts out, + // because an authentication request is not an authenticated request. + if (entry.request.requires_session && m_session_token) { const std::string token = m_session_token(); if (!token.empty()) { request.headers.Set("x-session-token", token); diff --git a/src/core/executor.h b/src/core/executor.h index 8805d72..a43542c 100644 --- a/src/core/executor.h +++ b/src/core/executor.h @@ -40,6 +40,10 @@ struct PendingRequest { std::string url; HeaderMap headers; std::string body; + + // Whether the executor should attach `x-session-token` when it sends this. False for an + // authentication request, which is not an authenticated request by definition. + bool requires_session = true; }; // The outcome of one request, delivered exactly once. diff --git a/src/core/json.cpp b/src/core/json.cpp index 8bf4ddb..ca76b04 100644 --- a/src/core/json.cpp +++ b/src/core/json.cpp @@ -322,6 +322,94 @@ std::string SerializeJson(const JsonValue& value) } // namespace core } // namespace lootlocker +// --------------------------------------------------------------------------- +// Shared field readers (T14 review) +// --------------------------------------------------------------------------- +// +// In this translation unit because they are JSON-layer concerns, not per-type ones. Every +// decoder needs the same three questions answered, and writing them per type is how two +// decoders end up disagreeing about whether a null counts as absent. + +namespace lootlocker { +namespace core { + +Error MissingField(const char* field) +{ + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = std::string("the response is missing ") + field; + return e; +} + +Error WrongFieldType(const char* field, const char* expected) +{ + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = std::string("the response has a non-") + expected + " " + field; + return e; +} + +bool ReadRequiredString(const JsonValue& j, const char* key, std::string& out, Error& error) +{ + const JsonValue value = j[key]; + if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { + error = MissingField(key); + return false; + } + if (value.GetKind() != JsonValue::Kind::String) { + error = WrongFieldType(key, "string"); + return false; + } + out = value.AsString(); + return true; +} + +bool ReadRequiredUInt64(const JsonValue& j, const char* key, std::uint64_t& out, Error& error) +{ + const JsonValue value = j[key]; + if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { + error = MissingField(key); + return false; + } + if (!value.IsUnsigned()) { + error = WrongFieldType(key, "unsigned integer"); + return false; + } + out = value.AsUInt64(); + return true; +} + +bool ReadOptionalString(const JsonValue& j, const char* key, std::string& out, Error& error) +{ + const JsonValue value = j[key]; + if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { + return true; + } + if (value.GetKind() != JsonValue::Kind::String) { + error = WrongFieldType(key, "string"); + return false; + } + out = value.AsString(); + return true; +} + +bool ReadOptionalBool(const JsonValue& j, const char* key, bool& out, Error& error) +{ + const JsonValue value = j[key]; + if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { + return true; + } + if (value.GetKind() != JsonValue::Kind::Bool) { + error = WrongFieldType(key, "boolean"); + return false; + } + out = value.AsBool(); + return true; +} + +} // namespace core +} // namespace lootlocker + // --------------------------------------------------------------------------- // JsonBuilder (T13d) // --------------------------------------------------------------------------- diff --git a/src/core/json.h b/src/core/json.h index 3b2f120..c76e588 100644 --- a/src/core/json.h +++ b/src/core/json.h @@ -11,6 +11,7 @@ #include #include +#include #include namespace lootlocker { @@ -47,5 +48,35 @@ Result DecodeJson(const JsonValue& value, T& out) return from_json(value, out); } +// --- shared field readers -------------------------------------------------- +// +// Every decoder needs the same three questions answered: "is this required field present and +// the right type", "is this optional field present and the right type", and "what do I say +// when it is not". Writing them per type is how two decoders end up disagreeing about +// whether a null counts as absent. +// +// The distinction they encode is D23's: a *missing* required field is an error, a *present +// field of the wrong type* is a different error, and an absent optional field is not an +// error at all. + +// A required string. Absent, null and non-string are all failures. +bool ReadRequiredString(const JsonValue& j, const char* key, std::string& out, Error& error); + +// A required unsigned integer. Read through `IsUnsigned`/`AsUInt64` so a value above 2^53 +// survives (D4). +bool ReadRequiredUInt64(const JsonValue& j, const char* key, std::uint64_t& out, Error& error); + +// An optional string. Absent or null leaves `out` untouched; a present non-string is an +// error, because that is a shape the API does not send and ignoring it would hide a contract +// change. +bool ReadOptionalString(const JsonValue& j, const char* key, std::string& out, Error& error); + +bool ReadOptionalBool(const JsonValue& j, const char* key, bool& out, Error& error); + +// The two error constructors the readers use, exposed so a decoder can report the same way +// for a field the readers do not cover. +Error MissingField(const char* field); +Error WrongFieldType(const char* field, const char* expected); + } // namespace core } // namespace lootlocker diff --git a/src/core/platform.cpp b/src/core/platform.cpp new file mode 100644 index 0000000..7df5cf5 --- /dev/null +++ b/src/core/platform.cpp @@ -0,0 +1,79 @@ +#include + +#include + +namespace lootlocker { + +namespace { + +struct PlatformName { + Platform platform; + const char* name; +}; + +// The wire names, matching the other SDKs' `LL_AuthPlatforms` exactly. The backend compares +// them literally, so a "nicer" spelling here is a 400 at runtime. +const PlatformName kPlatformNames[] = { + {Platform::None, ""}, + {Platform::Guest, "guest"}, + {Platform::WhiteLabel, "white_label_login"}, + {Platform::Steam, "steam"}, + {Platform::PlayStationNetwork, "psn"}, + {Platform::XboxOne, "xbox_one"}, + {Platform::NintendoSwitch, "nintendo_switch"}, + {Platform::AmazonLuna, "amazon_luna"}, + {Platform::AppleSignIn, "apple_sign_in"}, + {Platform::AppleGameCenter, "apple_game_center"}, + {Platform::Android, "android"}, + {Platform::GoogleSignIn, "google_sign_in"}, + {Platform::GooglePlayGames, "google_play_games"}, + {Platform::EpicGames, "epic_games"}, + {Platform::Meta, "meta"}, + {Platform::Remote, "remote"}, + {Platform::Discord, "discord"}, +}; + +} // namespace + +const char* ToString(Platform platform) +{ + for (const PlatformName& entry : kPlatformNames) { + if (entry.platform == platform) { + return entry.name; + } + } + return ""; +} + +bool TryParsePlatform(const std::string& name, Platform& out) +{ + for (const PlatformName& entry : kPlatformNames) { + if (name == entry.name) { + out = entry.platform; + return true; + } + } + return false; +} + +Result from_json(const JsonValue& j, Platform& out) +{ + if (j.GetKind() != JsonValue::Kind::String) { + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = "the platform is missing or not a string"; + return Result::Fail(e); + } + + Platform parsed = Platform::None; + if (!TryParsePlatform(j.AsString(), parsed)) { + Error e; + e.code = ErrorCode::MalformedResponse; + e.message = "the platform is not one the SDK knows: " + j.AsString(); + return Result::Fail(e); + } + out = parsed; + return Result::Ok(Empty()); +} + +} // namespace lootlocker diff --git a/src/core/session.cpp b/src/core/session.cpp index 3ca495b..843f558 100644 --- a/src/core/session.cpp +++ b/src/core/session.cpp @@ -1,77 +1,8 @@ #include -namespace lootlocker { - -namespace { - -Error Missing(const char* field) -{ - Error e; - e.code = ErrorCode::MalformedResponse; - e.message = std::string("the session response is missing ") + field; - return e; -} - -// A present field of the wrong type. Distinct from "missing", because the two are different -// bugs and a message that says "missing" for a present field sends the reader looking in the -// wrong place. -Error WrongType(const char* field, const char* expected) -{ - Error e; - e.code = ErrorCode::MalformedResponse; - e.message = std::string("the session response has a non-") + expected + " " + field; - return e; -} +#include "json.h" -// A required string. Absent, null and non-string are all failures, because a session field -// the SDK depends on must not be silently defaulted (D23). -bool ReadRequiredString(const JsonValue& j, const char* key, std::string& out, Error& error) -{ - const JsonValue value = j[key]; - if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { - error = Missing(key); - return false; - } - if (value.GetKind() != JsonValue::Kind::String) { - error = WrongType(key, "string"); - return false; - } - out = value.AsString(); - return true; -} - -// An optional string. Absent or null leaves `out` untouched; a present non-string is still -// an error, because that is a shape the API does not send and silently ignoring it would -// hide a contract change. -bool ReadOptionalString(const JsonValue& j, const char* key, std::string& out, Error& error) -{ - const JsonValue value = j[key]; - if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { - return true; - } - if (value.GetKind() != JsonValue::Kind::String) { - error = WrongType(key, "string"); - return false; - } - out = value.AsString(); - return true; -} - -bool ReadOptionalBool(const JsonValue& j, const char* key, bool& out, Error& error) -{ - const JsonValue value = j[key]; - if (value.GetKind() == JsonValue::Kind::Invalid || value.GetKind() == JsonValue::Kind::Null) { - return true; - } - if (value.GetKind() != JsonValue::Kind::Bool) { - error = WrongType(key, "boolean"); - return false; - } - out = value.AsBool(); - return true; -} - -} // namespace +namespace lootlocker { Result from_json(const JsonValue& j, Session& out) { @@ -85,34 +16,23 @@ Result from_json(const JsonValue& j, Session& out) Error error; // Required: without these the session is unusable or the player cannot be identified. - if (!ReadRequiredString(j, "session_token", out.session_token, error) || - !ReadRequiredString(j, "player_identifier", out.player_identifier, error) || - !ReadRequiredString(j, "player_ulid", out.player_ulid, error) || - !ReadRequiredString(j, "public_uid", out.public_uid, error)) { + if (!core::ReadRequiredString(j, "session_token", out.session_token, error) || + !core::ReadRequiredString(j, "player_identifier", out.player_identifier, error) || + !core::ReadRequiredString(j, "player_ulid", out.player_ulid, error) || + !core::ReadRequiredString(j, "public_uid", out.public_uid, error) || + !core::ReadRequiredUInt64(j, "player_id", out.player_id, error)) { return Result::Fail(error); } - // `player_id` is required and must be an unsigned integer. Reading it through - // `AsDouble()` would lose precision above 2^53, which is the hazard D4 exists for. - const JsonValue player_id = j["player_id"]; - if (player_id.GetKind() == JsonValue::Kind::Invalid || - player_id.GetKind() == JsonValue::Kind::Null) { - return Result::Fail(Missing("player_id")); - } - if (!player_id.IsUnsigned()) { - return Result::Fail(WrongType("player_id", "unsigned integer")); - } - out.player_id = player_id.AsUInt64(); - // Optional: an absent name genuinely means "not set", and the API omits the rest on // some auth paths. - if (!ReadOptionalString(j, "player_name", out.player_name, error) || - !ReadOptionalString(j, "player_created_at", out.player_created_at, error) || - !ReadOptionalBool(j, "seen_before", out.seen_before, error) || - !ReadOptionalBool(j, "check_grant_notifications", out.check_grant_notifications, - error) || - !ReadOptionalBool(j, "check_deactivation_notifications", - out.check_deactivation_notifications, error)) { + if (!core::ReadOptionalString(j, "player_name", out.player_name, error) || + !core::ReadOptionalString(j, "player_created_at", out.player_created_at, error) || + !core::ReadOptionalBool(j, "seen_before", out.seen_before, error) || + !core::ReadOptionalBool(j, "check_grant_notifications", out.check_grant_notifications, + error) || + !core::ReadOptionalBool(j, "check_deactivation_notifications", + out.check_deactivation_notifications, error)) { return Result::Fail(error); } diff --git a/tests/test_auth.cpp b/tests/test_auth.cpp index 5ce399e..a9b9aeb 100644 --- a/tests/test_auth.cpp +++ b/tests/test_auth.cpp @@ -1,12 +1,13 @@ // Guest auth (T14). // // The verification the task asks for: `auth::StartGuestSession` over -// `POST /game/v2/session/guest`, including `player_identifier` reuse across restarts. +// `POST /game/v2/session/guest`, including the guest identifier's reuse across restarts. #include #include #include #include +#include #include #include #include @@ -24,11 +25,14 @@ using lootlocker::Client; using lootlocker::Config; using lootlocker::ErrorCode; using lootlocker::FakeHttpTransport; +using lootlocker::GuestSessionInputs; using lootlocker::IHttpTransport; using lootlocker::NullStateWriter; +using lootlocker::Platform; using lootlocker::RequestId; using lootlocker::Result; using lootlocker::Session; +using lootlocker::SessionOptionals; // A scratch file that removes itself. struct TempFile { @@ -57,7 +61,7 @@ Config MakeConfig() // Without this, a test that does not inject a writer falls back to the default // `FileStateWriter`, which reads and writes `lootlocker-state.txt` in the working directory - // so tests leak state into each other and into the developer's checkout. That is exactly -// what happened: a stale file made a sabotage test pass. +// what happened once: a stale file made a sabotage test pass. Config MakeConfigWithoutPersistence(std::shared_ptr& keep_alive) { Config config = MakeConfig(); @@ -101,6 +105,23 @@ struct Fixture { } }; +// Pulls a string field out of a JSON body. Crude on purpose: the tests assert on the wire +// shape, so parsing it with the SDK's own parser would let a bug hide. +std::string FieldFromBody(const std::string& body, const std::string& key) +{ + const std::string marker = "\"" + key + "\":\""; + const std::size_t at = body.find(marker); + if (at == std::string::npos) { + return std::string(); + } + const std::size_t start = at + marker.size(); + const std::size_t end = body.find('"', start); + if (end == std::string::npos) { + return std::string(); + } + return body.substr(start, end - start); +} + // --- the request ----------------------------------------------------------- // The endpoint, method and body are what the API expects. @@ -121,27 +142,91 @@ void TestGuestSessionRequest() CHECK_EQ(sent->method, "POST"); CHECK_EQ(sent->url, "https://testdomain.api.lootlocker.com/game/v2/session/guest"); - // The body carries the config's game key and version, the guest platform, and a - // generated identifier. CHECK(sent->body.find(R"("game_key":"testgamekey")") != std::string::npos); CHECK(sent->body.find(R"("game_version":"1.0.0")") != std::string::npos); CHECK(sent->body.find(R"("platform":"guest")") != std::string::npos); - CHECK(sent->body.find(R"("player_identifier":")") != std::string::npos); - - // No session yet, so no token is sent. - CHECK(!sent->headers.Has("x-session-token")); + CHECK(!FieldFromBody(sent->body, "player_identifier").empty()); } -// The optionals are sent only when set. `timezone` is the exception: it is resolved from the -// config, the provider and finally the default, so it is always present unless -// `send_timezone` is false (covered by `TestSendTimezoneFalse`). -void TestOptionalsAreOmittedWhenEmpty() +// An authentication request is not an authenticated request, so it must not carry a token - +// even when a session from a previous call exists. +void TestTokenIsNotSentOnAuthRequest() { std::shared_ptr keep_alive; Fixture f(MakeConfigWithoutPersistence(keep_alive)); + // Establish a session first. lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, kSessionBody); + f.client->Update(); + CHECK(f.client->HasSession()); + + // A second auth request must not carry the token. + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const auto order = f.transport->Order(); + CHECK_EQ_INT(static_cast(order.size()), 2); + if (order.size() < 2) { + return; + } + + const IHttpTransport::Request* second = f.transport->FindRequest(order[1]); + CHECK(second != nullptr); + if (second != nullptr) { + CHECK(!second->headers.Has("x-session-token")); + } +} + +// The optionals are nested under `optionals`, not at the root. The backend's `GuestInput` +// carries `Optionals Optionals` tagged `json:"optionals"`, so a root-level `timezone` is +// silently ignored and the player gets UTC. +void TestOptionalsAreNested() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + GuestSessionInputs inputs; + SessionOptionals optionals; + optionals.timezone = "Europe/Stockholm"; + optionals.player_name = "Erik"; + inputs.optionals = optionals; + + lootlocker::auth::StartGuestSession(*f.client, inputs, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + CHECK(sent->body.find(R"("optionals":{)") != std::string::npos); + CHECK(sent->body.find(R"("timezone":"Europe/Stockholm")") != std::string::npos); + CHECK(sent->body.find(R"("player_name":"Erik")") != std::string::npos); + + // And not at the root: `timezone` appears after `optionals` opens. + const std::size_t optionals_at = sent->body.find(R"("optionals")"); + CHECK(sent->body.find(R"("timezone")") > optionals_at); +} + +// The optionals carry the backend's fields, not invented ones. +void TestOptionalsFields() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + GuestSessionInputs inputs; + SessionOptionals optionals; + optionals.auto_create_profile = false; + optionals.check_dlc = true; + optionals.referral_code = "REF123"; + optionals.referral_program_key = "prog"; + inputs.optionals = optionals; + + lootlocker::auth::StartGuestSession(*f.client, inputs, [](Result) {}); + f.client->Update(); const IHttpTransport::Request* sent = f.Sent(); CHECK(sent != nullptr); @@ -149,22 +234,26 @@ void TestOptionalsAreOmittedWhenEmpty() return; } + CHECK(sent->body.find(R"("auto_create_profile":false)") != std::string::npos); + CHECK(sent->body.find(R"("check_dlc":true)") != std::string::npos); + CHECK(sent->body.find(R"("referral_code":"REF123")") != std::string::npos); + CHECK(sent->body.find(R"("referral_program_key":"prog")") != std::string::npos); + + // The invented fields are gone. CHECK(sent->body.find("locale") == std::string::npos); - CHECK(sent->body.find("player_name") == std::string::npos); CHECK(sent->body.find("character_name") == std::string::npos); } -void TestOptionalsAreSentWhenSet() +// A field equal to the backend's default is omitted rather than sent. +void TestDefaultsAreOmitted() { std::shared_ptr keep_alive; Fixture f(MakeConfigWithoutPersistence(keep_alive)); - lootlocker::GuestSessionOptions opts; - opts.timezone = "Europe/Stockholm"; - opts.locale = "sv-SE"; - opts.player_name = "Erik"; + GuestSessionInputs inputs; + inputs.optionals = SessionOptionals(); // all defaults - lootlocker::auth::StartGuestSession(*f.client, opts, [](Result) {}); + lootlocker::auth::StartGuestSession(*f.client, inputs, [](Result) {}); f.client->Update(); const IHttpTransport::Request* sent = f.Sent(); @@ -173,14 +262,50 @@ void TestOptionalsAreSentWhenSet() return; } - CHECK(sent->body.find(R"("timezone":"Europe/Stockholm")") != std::string::npos); - CHECK(sent->body.find(R"("locale":"sv-SE")") != std::string::npos); - CHECK(sent->body.find(R"("player_name":"Erik")") != std::string::npos); + CHECK(sent->body.find("auto_create_profile") == std::string::npos); + CHECK(sent->body.find("check_dlc") == std::string::npos); +} + +// The timezone falls back to the config and is normalised to an IANA name, because a Windows +// name sent as-is gets UTC server-side. +void TestTimezoneResolution() +{ + std::shared_ptr keep_alive; + Config config = MakeConfigWithoutPersistence(keep_alive); + config.timezone = "W. Europe Standard Time"; + + Fixture f(config); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + CHECK(sent->body.find(R"("timezone":"Europe/Berlin")") != std::string::npos); + } +} + +// `send_timezone = false` sends no timezone at all, which is a different statement from +// "I have no opinion". +void TestSendTimezoneFalse() +{ + std::shared_ptr keep_alive; + Config config = MakeConfigWithoutPersistence(keep_alive); + config.send_timezone = false; + + Fixture f(config); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + CHECK(sent->body.find("timezone") == std::string::npos); + } } // --- the response ---------------------------------------------------------- -// A successful response is decoded, stored on the client, and delivered. void TestSuccessfulSession() { std::shared_ptr keep_alive; @@ -212,45 +337,10 @@ void TestSuccessfulSession() CHECK(!received.check_grant_notifications); CHECK(received.check_deactivation_notifications); - // Stored on the client, so the caller does not have to remember to do it. CHECK(f.client->HasSession()); CHECK_EQ(f.client->GetSession().session_token, "tok-abc"); } -// The next request carries the token. -void TestSessionTokenIsSentOnSubsequentRequests() -{ - std::shared_ptr keep_alive; - Fixture f(MakeConfigWithoutPersistence(keep_alive)); - - lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); - f.client->Update(); - f.transport->Complete(f.transport->Order().front(), 200, kSessionBody); - f.client->Update(); - - CHECK(f.client->HasSession()); - - // A second request, after the session exists. - lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); - f.client->Update(); - - const auto order = f.transport->Order(); - CHECK_EQ_INT(static_cast(order.size()), 2); - if (order.size() < 2) { - return; - } - - const IHttpTransport::Request* second = f.transport->FindRequest(order[1]); - CHECK(second != nullptr); - if (second == nullptr) { - return; - } - - std::string token; - CHECK(second->headers.Get("x-session-token", token)); - CHECK_EQ(token, "tok-abc"); -} - // A missing required field is a decode error, not a silent default (D23). void TestMissingRequiredFieldIsAnError() { @@ -268,7 +358,6 @@ void TestMissingRequiredFieldIsAnError() }); f.client->Update(); - // No session_token. f.transport->Complete(f.transport->Order().front(), 200, R"({"player_identifier":"p","player_ulid":"u","public_uid":"x","player_id":1})"); f.client->Update(); @@ -304,6 +393,56 @@ void TestMissingOptionalFieldIsFine() CHECK_EQ(f.client->GetSession().player_name, ""); } +// A 200 with an empty body is a malformed response for a definition whose response carries +// required fields. +void TestEmptyBodyIsNotASuccess() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + bool called = false; + ErrorCode code = ErrorCode::None; + + lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { + called = true; + if (!result.Ok()) { + code = result.Error().code; + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, ""); + f.client->Update(); + + CHECK(called); + CHECK(code == ErrorCode::MalformedResponse); + CHECK(!f.client->HasSession()); +} + +// A present field of the wrong type says so, rather than claiming it is missing. +void TestWrongTypeMessage() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + std::string message; + + lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { + if (!result.Ok()) { + message = result.Error().message; + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 200, + R"({"session_token":42,"player_identifier":"p","player_ulid":"u",)" + R"("public_uid":"x","player_id":1})"); + f.client->Update(); + + CHECK(message.find("non-string") != std::string::npos); + CHECK(message.find("missing") == std::string::npos); +} + // --- identifier reuse across restarts -------------------------------------- // The whole point of guest auth: the same identifier on the next launch, so the player is @@ -313,7 +452,7 @@ void TestMissingOptionalFieldIsFine() // `Config` holds a `weak_ptr`, so a temporary expires before the client is constructed and // the SDK silently falls back to the default file - which would make this test pass for the // wrong reason. -void TestPlayerIdentifierIsReusedAcrossRestarts() +void TestGuestIdentifierIsReusedAcrossRestarts() { TempFile file("reuse"); @@ -333,15 +472,7 @@ void TestPlayerIdentifierIsReusedAcrossRestarts() const IHttpTransport::Request* sent = f.Sent(); CHECK(sent != nullptr); if (sent != nullptr) { - // Pull the identifier out of the body. - const std::string marker = R"("player_identifier":")"; - const std::size_t at = sent->body.find(marker); - CHECK(at != std::string::npos); - if (at != std::string::npos) { - const std::size_t start = at + marker.size(); - const std::size_t end = sent->body.find('"', start); - first_identifier = sent->body.substr(start, end - start); - } + first_identifier = FieldFromBody(sent->body, "player_identifier"); } CHECK(!first_identifier.empty()); } @@ -361,21 +492,13 @@ void TestPlayerIdentifierIsReusedAcrossRestarts() const IHttpTransport::Request* sent = f.Sent(); CHECK(sent != nullptr); if (sent != nullptr) { - const std::string marker = R"("player_identifier":")"; - const std::size_t at = sent->body.find(marker); - CHECK(at != std::string::npos); - if (at != std::string::npos) { - const std::size_t start = at + marker.size(); - const std::size_t end = sent->body.find('"', start); - const std::string second = sent->body.substr(start, end - start); - CHECK_EQ(second, first_identifier); - } + CHECK_EQ(FieldFromBody(sent->body, "player_identifier"), first_identifier); } } } -// An explicit identifier wins over the persisted one. -void TestExplicitIdentifierWins() +// An explicit identifier wins over the persisted one, and is persisted itself. +void TestExplicitIdentifierWinsAndPersists() { TempFile file("explicit"); @@ -385,29 +508,42 @@ void TestExplicitIdentifierWins() Config config = MakeConfig(); config.state_writer = writer; - Fixture f(config); + { + Fixture f(config); - lootlocker::GuestSessionOptions opts; - opts.player_identifier = "chosen-by-the-game"; + GuestSessionInputs inputs; + inputs.guest_identifier = std::string("chosen-by-the-game"); - lootlocker::auth::StartGuestSession(*f.client, opts, [](Result) {}); + lootlocker::auth::StartGuestSession(*f.client, inputs, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + CHECK_EQ(FieldFromBody(sent->body, "player_identifier"), "chosen-by-the-game"); + } + } + + // A second launch, with no explicit identifier: the persisted one is used. + std::shared_ptr reopened = + std::make_shared(file.path); + + Config second = MakeConfig(); + second.state_writer = reopened; + + Fixture f(second); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); f.client->Update(); const IHttpTransport::Request* sent = f.Sent(); CHECK(sent != nullptr); if (sent != nullptr) { - CHECK(sent->body.find(R"("player_identifier":"chosen-by-the-game")") != - std::string::npos); + CHECK_EQ(FieldFromBody(sent->body, "player_identifier"), "chosen-by-the-game"); } } // With no persistence, every launch generates a new identifier - which is the documented // cost of a `NullStateWriter`. -// -// The writer is held in a named `shared_ptr`, not assigned as a temporary: `Config` holds a -// `weak_ptr`, so `config.state_writer = std::make_shared<...>()` expires before the client -// is constructed and the SDK silently falls back to the file default. This test caught that -// exact mistake in its own first draft, which is why the README warns about it. void TestNullWriterGeneratesNewIdentifierEachTime() { std::string first; @@ -426,13 +562,7 @@ void TestNullWriterGeneratesNewIdentifierEachTime() const IHttpTransport::Request* sent = f.Sent(); CHECK(sent != nullptr); if (sent != nullptr) { - const std::string marker = R"("player_identifier":")"; - const std::size_t at = sent->body.find(marker); - if (at != std::string::npos) { - const std::size_t start = at + marker.size(); - const std::size_t end = sent->body.find('"', start); - *out = sent->body.substr(start, end - start); - } + *out = FieldFromBody(sent->body, "player_identifier"); } } @@ -441,169 +571,21 @@ void TestNullWriterGeneratesNewIdentifierEachTime() CHECK(first != second); } -// The optionals are nested under `optionals`, not at the root. The backend's `GuestInput` -// carries `Optionals Optionals` tagged `json:"optionals"`, so a root-level `timezone` is -// silently ignored and the player gets UTC. -void TestOptionalsAreNested() -{ - std::shared_ptr keep_alive; - Fixture f(MakeConfigWithoutPersistence(keep_alive)); - - lootlocker::GuestSessionOptions opts; - opts.timezone = "Europe/Stockholm"; - opts.locale = "sv-SE"; - opts.player_name = "Erik"; - - lootlocker::auth::StartGuestSession(*f.client, opts, [](Result) {}); - f.client->Update(); - - const IHttpTransport::Request* sent = f.Sent(); - CHECK(sent != nullptr); - if (sent == nullptr) { - return; - } - - CHECK(sent->body.find(R"("optionals":{)") != std::string::npos); - CHECK(sent->body.find(R"("timezone":"Europe/Stockholm")") != std::string::npos); - CHECK(sent->body.find(R"("locale":"sv-SE")") != std::string::npos); - CHECK(sent->body.find(R"("player_name":"Erik")") != std::string::npos); - - // And not at the root: the only root-level keys are the four the API expects. - const std::size_t optionals_at = sent->body.find(R"("optionals")"); - CHECK(sent->body.find(R"("timezone")") > optionals_at); -} - -// The timezone falls back to the config, then the provider, then the default - and is -// normalised to an IANA name, because a Windows name sent as-is gets UTC server-side. -void TestTimezoneResolution() -{ - std::shared_ptr keep_alive; - - // A Windows name in the config is normalised. - Config config = MakeConfigWithoutPersistence(keep_alive); - config.timezone = "W. Europe Standard Time"; - - Fixture f(config); - lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); - f.client->Update(); - - const IHttpTransport::Request* sent = f.Sent(); - CHECK(sent != nullptr); - if (sent != nullptr) { - CHECK(sent->body.find(R"("timezone":"Europe/Berlin")") != std::string::npos); - } -} - -// `send_timezone = false` sends no timezone at all, which is a different statement from -// "I have no opinion". -void TestSendTimezoneFalse() -{ - std::shared_ptr keep_alive; - Config config = MakeConfigWithoutPersistence(keep_alive); - config.send_timezone = false; - - Fixture f(config); - lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); - f.client->Update(); - - const IHttpTransport::Request* sent = f.Sent(); - CHECK(sent != nullptr); - if (sent != nullptr) { - CHECK(sent->body.find("timezone") == std::string::npos); - } -} - -// A 200 with an empty body is a malformed response for a definition whose response carries -// required fields. Without this it would become an all-default `Session` and `HasSession()` -// would report true with no token. -void TestEmptyBodyIsNotASuccess() -{ - std::shared_ptr keep_alive; - Fixture f(MakeConfigWithoutPersistence(keep_alive)); - - bool called = false; - ErrorCode code = ErrorCode::None; - - lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { - called = true; - if (!result.Ok()) { - code = result.Error().code; - } - }); - - f.client->Update(); - f.transport->Complete(f.transport->Order().front(), 200, ""); - f.client->Update(); - - CHECK(called); - CHECK(code == ErrorCode::MalformedResponse); - CHECK(!f.client->HasSession()); -} - -// A present field of the wrong type says so, rather than claiming it is missing. -void TestWrongTypeMessage() -{ - std::shared_ptr keep_alive; - Fixture f(MakeConfigWithoutPersistence(keep_alive)); - - std::string message; - - lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { - if (!result.Ok()) { - message = result.Error().message; - } - }); - - f.client->Update(); - // `session_token` is present but a number. - f.transport->Complete(f.transport->Order().front(), 200, - R"({"session_token":42,"player_identifier":"p","player_ulid":"u",)" - R"("public_uid":"x","player_id":1})"); - f.client->Update(); - - CHECK(message.find("non-string") != std::string::npos); - CHECK(message.find("missing") == std::string::npos); -} +// --- platform -------------------------------------------------------------- -// An explicit identifier is persisted too, so a game that supplies one on the first launch -// and relies on the SDK afterwards does not get a different account. -void TestExplicitIdentifierIsPersisted() +void TestPlatformNames() { - TempFile file("explicit-persist"); - - std::shared_ptr writer = - std::make_shared(file.path); - - Config config = MakeConfig(); - config.state_writer = writer; - - { - Fixture f(config); - - lootlocker::GuestSessionOptions opts; - opts.player_identifier = "chosen-by-the-game"; - - lootlocker::auth::StartGuestSession(*f.client, opts, [](Result) {}); - f.client->Update(); - } - - // A second launch, with no explicit identifier: the persisted one is used. - std::shared_ptr reopened = - std::make_shared(file.path); + CHECK_EQ(lootlocker::ToString(Platform::Guest), "guest"); + CHECK_EQ(lootlocker::ToString(Platform::WhiteLabel), "white_label_login"); + CHECK_EQ(lootlocker::ToString(Platform::PlayStationNetwork), "psn"); + CHECK_EQ(lootlocker::ToString(Platform::NintendoSwitch), "nintendo_switch"); - Config second = MakeConfig(); - second.state_writer = reopened; + Platform parsed = Platform::None; + CHECK(lootlocker::TryParsePlatform("steam", parsed)); + CHECK(parsed == Platform::Steam); - Fixture f(second); - lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); - f.client->Update(); - - const IHttpTransport::Request* sent = f.Sent(); - CHECK(sent != nullptr); - if (sent != nullptr) { - CHECK(sent->body.find(R"("player_identifier":"chosen-by-the-game")") != - std::string::npos); - } + // An unknown name is a contract change, not a missing value. + CHECK(!lootlocker::TryParsePlatform("not_a_platform", parsed)); } // --- the client accessors -------------------------------------------------- @@ -643,21 +625,21 @@ void TestReturnsExecutorId() int main() { TestGuestSessionRequest(); - TestOptionalsAreOmittedWhenEmpty(); - TestOptionalsAreSentWhenSet(); - TestSuccessfulSession(); - TestSessionTokenIsSentOnSubsequentRequests(); - TestMissingRequiredFieldIsAnError(); - TestMissingOptionalFieldIsFine(); - TestPlayerIdentifierIsReusedAcrossRestarts(); - TestExplicitIdentifierWins(); - TestExplicitIdentifierIsPersisted(); - TestNullWriterGeneratesNewIdentifierEachTime(); + TestTokenIsNotSentOnAuthRequest(); TestOptionalsAreNested(); + TestOptionalsFields(); + TestDefaultsAreOmitted(); TestTimezoneResolution(); TestSendTimezoneFalse(); + TestSuccessfulSession(); + TestMissingRequiredFieldIsAnError(); + TestMissingOptionalFieldIsFine(); TestEmptyBodyIsNotASuccess(); TestWrongTypeMessage(); + TestGuestIdentifierIsReusedAcrossRestarts(); + TestExplicitIdentifierWinsAndPersists(); + TestNullWriterGeneratesNewIdentifierEachTime(); + TestPlatformNames(); TestSessionAccessors(); TestReturnsExecutorId(); return testing::Report(); From dc2619ea256e2558f9ba3a6fe1b2882d3f434f1f Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Thu, 26 Nov 2026 14:22:29 +0100 Subject: [PATCH 4/4] Fix four Copilot findings The high-severity one: kAllowEmptyResponse did not protect the 204 path. The condition accepted every 204 before checking the flag, so a 204 from an endpoint whose response carries required fields still became an all-default Session and HasSession() reported true. Both the 204 and the empty-body case are now gated on the flag, via if constexpr so the branch is genuinely compiled out. The timezone resolver skipped the OS step. I had reimplemented the chain locally and left out SystemTimezoneProvider, so a normal guest start ignored the machine timezone entirely. It now delegates to the public ResolveTimezone helper that already existed - which is the real lesson: the helper was there and I wrote a second one. DefinitionTraits was dead code: the static_asserts were never instantiated, so a definition missing kMethod still failed later in an unrelated template expression. Send now instantiates it. The player_id static_assert is restored. The owner asked me to remove it as guarding against a type change nobody makes, but R9 names it as the documented mitigation for the silent 2^53 truncation, so removing it would have left the spec claiming a guard that no longer existed. Flagged on the PR for the owner to overrule if they still disagree. Verified by sabotage: ungating the 204 fails four assertions, and skipping the OS step fails four more. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- include/lootlocker/session.h | 11 ++++++ src/auth/auth.cpp | 39 ++++++------------ src/core/definition.h | 45 +++++++++++++-------- tests/test_auth.cpp | 77 ++++++++++++++++++++++++++++++++++++ 4 files changed, 128 insertions(+), 44 deletions(-) diff --git a/include/lootlocker/session.h b/include/lootlocker/session.h index 7132b7f..6daae9f 100644 --- a/include/lootlocker/session.h +++ b/include/lootlocker/session.h @@ -10,6 +10,7 @@ #include #include +#include namespace lootlocker { @@ -26,6 +27,16 @@ struct Session { bool check_deactivation_notifications = false; }; +// `player_id` must stay an unsigned 64-bit integer. +// +// **This is R9's documented mitigation, not a guard against someone editing the struct.** +// The D4 spike showed both candidate parsers are exact by default, so the hazard is not the +// parser but a `double` field in our own structs - and the failure is silent, because a +// value above 2^53 loses precision without any error. The assert is what makes adding such +// a field a compile error rather than a support ticket. +static_assert(sizeof(Session::player_id) == 8 && !std::is_floating_point::value, + "player_id must be an unsigned 64-bit integer (D4, R9)"); + // Decodes a session response (D27). // // **Which fields are required, and why that is not a silent default.** D23 says a missing diff --git a/src/auth/auth.cpp b/src/auth/auth.cpp index bc24791..25896a3 100644 --- a/src/auth/auth.cpp +++ b/src/auth/auth.cpp @@ -85,36 +85,21 @@ std::string ResolveGuestIdentifier(Client& ll, const GuestSessionInputs& inputs) // The timezone to send, or empty for "send none". // -// Resolution order, per D26: the caller's option, then `Config::timezone`, then the injected -// `TimezoneProvider`, then the OS, then `Etc/UTC`. `Config::send_timezone == false` means -// send nothing at all, which is a different statement from "I have no opinion". +// **Delegates to the public `ResolveTimezone` helper** rather than reimplementing the chain. +// The first version did reimplement it and skipped the OS step, so a normal guest start +// ignored the machine timezone entirely - which is the bug the helper exists to prevent. // -// The result is normalised to an IANA name, because a Windows name sent as-is gets UTC -// server-side and puts every local-day boundary on the wrong day (R27). -std::string ResolveTimezone(Client& ll, const SessionOptionals& optionals) +// The caller's option wins over `Config::timezone`, because a per-call value is more +// specific than a per-client one. +std::string ResolveSessionTimezone(Client& ll, const SessionOptionals& optionals) { const Config& config = ll.GetConfig(); - if (!config.send_timezone) { - return std::string(); - } - std::string candidate = optionals.timezone; - if (candidate.empty()) { - candidate = config.timezone; - } - if (candidate.empty()) { - if (std::shared_ptr provider = config.timezone_provider.lock()) { - candidate = provider->GetTimezone(); - } - } + const std::string& override_value = + optionals.timezone.empty() ? config.timezone : optionals.timezone; - std::string iana; - if (TryNormalizeToIana(candidate, iana)) { - return iana; - } - // `TryNormalizeToIana` sets the default on failure, so this is the documented fallback - // rather than an empty string the server would read as UTC. - return std::string(kDefaultIanaTimezone); + return ResolveTimezone(config.timezone_provider.lock().get(), override_value, + config.send_timezone); } // The backend's `optionals` object, serialised only when it carries something. @@ -230,7 +215,7 @@ RequestId StartGuestSession(Client& ll, const GuestSessionInputs& inputs, if (inputs.optionals.has_value()) { const SessionOptionals& in = *inputs.optionals; - request.optionals.timezone = ResolveTimezone(ll, in); + request.optionals.timezone = ResolveSessionTimezone(ll, in); request.optionals.player_name = in.player_name; request.optionals.auto_create_profile = in.auto_create_profile; request.optionals.check_dlc = in.check_dlc; @@ -247,7 +232,7 @@ RequestId StartGuestSession(Client& ll, const GuestSessionInputs& inputs, // No optionals supplied, but the timezone is still resolved: it is a config-level // concern rather than a per-call one, and a game that set `Config::timezone` expects // it to be sent. - request.optionals.timezone = ResolveTimezone(ll, SessionOptionals()); + request.optionals.timezone = ResolveSessionTimezone(ll, SessionOptionals()); request.has_optionals = !request.optionals.timezone.empty(); } diff --git a/src/core/definition.h b/src/core/definition.h index 89e2ba1..d00a691 100644 --- a/src/core/definition.h +++ b/src/core/definition.h @@ -222,6 +222,11 @@ template RequestId Send(Client& client, const typename Def::Request& request, ResponseCallback on_done) { + // Instantiate the contract checks. Without this the `static_assert`s in + // `DefinitionTraits` are never evaluated, so a definition missing `kMethod` fails later + // in an unrelated template expression instead of producing the promised diagnostic. + static_assert(sizeof(DefinitionTraits) > 0, "the definition is incomplete"); + PendingRequest pending; pending.method = Def::kMethod; pending.url = BuildUrl(client, request); @@ -252,26 +257,32 @@ RequestId Send(Client& client, const typename Def::Request& request, // documents it as such. Parsing an empty body would report `MalformedResponse` // for a request that succeeded, so it is handled before the parser sees it. // - // A definition whose response carries required fields opts out with - // `kAllowEmptyResponse = false`, because for it an empty body is a malformed - // response rather than a success - a 200 with no body must not become an - // all-default value that looks valid. + // **Both the 204 and the empty-body case are gated on the definition's flag.** + // Gating only the empty-body case left a hole: a 204 from an endpoint whose + // response carries required fields would still become an all-default value that + // looks valid. A definition that cannot be empty says so, and that applies to + // every empty response, not just a 200. // // `NormalizeResponse` still runs, because a definition may want to fill in // derived fields on an empty response too. - if (completion.status_code == 204 || - (completion.body.empty() && AllowsEmptyResponse::value)) { - typename Def::Response response; - - RawResponse raw; - raw.status_code = completion.status_code; - raw.headers = completion.headers; - raw.body = completion.body; - - Normalize(response, raw); - - on_done(Result::Ok(std::move(response), completion.body)); - return; + // `if constexpr` rather than a runtime `if`, so the constant condition does not + // trip MSVC's C4127 and the branch is genuinely compiled out for a definition + // that cannot be empty. + if constexpr (AllowsEmptyResponse::value) { + if (completion.status_code == 204 || completion.body.empty()) { + typename Def::Response response; + + RawResponse raw; + raw.status_code = completion.status_code; + raw.headers = completion.headers; + raw.body = completion.body; + + Normalize(response, raw); + + on_done(Result::Ok(std::move(response), + completion.body)); + return; + } } Result parsed = ParseJson(completion.body); diff --git a/tests/test_auth.cpp b/tests/test_auth.cpp index a9b9aeb..af7426d 100644 --- a/tests/test_auth.cpp +++ b/tests/test_auth.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include "test_harness.h" @@ -588,6 +589,79 @@ void TestPlatformNames() CHECK(!lootlocker::TryParsePlatform("not_a_platform", parsed)); } +// A 204 is also gated on the definition's flag. Gating only the empty-body case left a hole: +// a 204 from an endpoint whose response carries required fields would still become an +// all-default `Session`. +void TestNoContentIsNotASuccessForRequiredResponse() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + bool called = false; + ErrorCode code = ErrorCode::None; + + lootlocker::auth::StartGuestSession(*f.client, [&](Result result) { + called = true; + if (!result.Ok()) { + code = result.Error().code; + } + }); + + f.client->Update(); + f.transport->Complete(f.transport->Order().front(), 204, ""); + f.client->Update(); + + CHECK(called); + CHECK(code == ErrorCode::MalformedResponse); + CHECK(!f.client->HasSession()); +} + +// The OS timezone is consulted when nothing else supplies one. The first version of the +// resolver skipped that step, so a normal guest start ignored the machine timezone. +void TestTimezoneFallsBackToTheSystem() +{ + std::shared_ptr keep_alive; + Fixture f(MakeConfigWithoutPersistence(keep_alive)); + + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent == nullptr) { + return; + } + + // Whatever the machine's zone is, a timezone is sent and it is an IANA name rather than + // empty - which is what "the OS step ran" means. + const std::string timezone = FieldFromBody(sent->body, "timezone"); + CHECK(!timezone.empty()); + CHECK(timezone.find('/') != std::string::npos || timezone == "UTC"); +} + +// An injected provider wins over the OS. +void TestInjectedProviderWins() +{ + std::shared_ptr keep_alive; + Config config = MakeConfigWithoutPersistence(keep_alive); + + struct FixedProvider : lootlocker::TimezoneProvider { + std::string GetTimezone() override { return "Asia/Tokyo"; } + }; + std::shared_ptr provider = std::make_shared(); + config.timezone_provider = provider; + + Fixture f(config); + lootlocker::auth::StartGuestSession(*f.client, [](Result) {}); + f.client->Update(); + + const IHttpTransport::Request* sent = f.Sent(); + CHECK(sent != nullptr); + if (sent != nullptr) { + CHECK_EQ(FieldFromBody(sent->body, "timezone"), "Asia/Tokyo"); + } +} + // --- the client accessors -------------------------------------------------- void TestSessionAccessors() @@ -635,7 +709,10 @@ int main() TestMissingRequiredFieldIsAnError(); TestMissingOptionalFieldIsFine(); TestEmptyBodyIsNotASuccess(); + TestNoContentIsNotASuccessForRequiredResponse(); TestWrongTypeMessage(); + TestTimezoneFallsBackToTheSystem(); + TestInjectedProviderWins(); TestGuestIdentifierIsReusedAcrossRestarts(); TestExplicitIdentifierWinsAndPersists(); TestNullWriterGeneratesNewIdentifierEachTime();