diff --git a/CMakeLists.txt b/CMakeLists.txt index 8b44f4b..8bc6563 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -142,7 +142,9 @@ 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 src/core/executor.cpp src/core/client.cpp @@ -190,6 +192,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..1549ed1 100644 --- a/README.md +++ b/README.md @@ -328,7 +328,61 @@ 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 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: `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 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::GuestSessionInputs inputs; + +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. + +## 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..89f0884 100644 --- a/include/lootlocker/auth.h +++ b/include/lootlocker/auth.h @@ -1,16 +1,104 @@ #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 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 { + +// 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; + + // The player's display name. Empty means "leave it as it is". + std::string player_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)>; + 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:** `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 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 GuestSessionInputs& inputs, + 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/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 new file mode 100644 index 0000000..6daae9f --- /dev/null +++ b/include/lootlocker/session.h @@ -0,0 +1,55 @@ +#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 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 +// 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..25896a3 100644 --- a/src/auth/auth.cpp +++ b/src/auth/auth.cpp @@ -1,4 +1,252 @@ #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 + +#include "core/definition.h" +#include "core/query_parameters.h" + +#include +#include +#include +#include + +namespace lootlocker { + +namespace { + +// The key the SDK persists. Named here rather than inline so a typo is a compile error +// rather than a silently missing key. +// +// **`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 GenerateGuestIdentifier() +{ + 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. +// +// **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 ResolveGuestIdentifier(Client& ll, const GuestSessionInputs& inputs) +{ + std::shared_ptr writer = ll.GetStateWriter().lock(); + + if (inputs.guest_identifier.has_value() && !inputs.guest_identifier->empty()) { + if (writer) { + writer->SetString(kGuestIdentifierKey, *inputs.guest_identifier); + } + return *inputs.guest_identifier; + } + + if (writer) { + std::string persisted; + if (writer->GetString(kGuestIdentifierKey, persisted) && !persisted.empty()) { + return persisted; + } + } + + const std::string generated = GenerateGuestIdentifier(); + if (writer) { + writer->SetString(kGuestIdentifierKey, generated); + } + return generated; +} + +// The timezone to send, or empty for "send none". +// +// **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 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(); + + const std::string& override_value = + optionals.timezone.empty() ? config.timezone : optionals.timezone; + + return ResolveTimezone(config.timezone_provider.lock().get(), override_value, + config.send_timezone); +} + +// The backend's `optionals` object, serialised only when it carries something. +// +// 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; + bool auto_create_profile = true; + bool check_dlc = false; + std::string referral_code; + std::string referral_program_key; +}; + +void to_json(JsonBuilder& b, const SessionOptionalsBody& in) +{ + if (!in.timezone.empty()) { + b.Set("timezone", in.timezone); + } + if (!in.player_name.empty()) { + b.Set("player_name", in.player_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.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; + Platform platform = Platform::Guest; + SessionOptionalsBody 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", ToString(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 + +namespace core { + +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; + + // 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; + + 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, GuestSessionInputs(), std::move(on_done)); +} + +RequestId StartGuestSession(Client& ll, const GuestSessionInputs& inputs, + SessionCallback on_done) +{ + const Config& config = ll.GetConfig(); + + GuestSessionRequest request; + request.game_key = config.game_key; + request.game_version = config.game_version; + request.platform = Platform::Guest; + request.player_identifier = ResolveGuestIdentifier(ll, inputs); + + if (inputs.optionals.has_value()) { + const SessionOptionals& in = *inputs.optionals; + + 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; + 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 = ResolveSessionTimezone(ll, SessionOptionals()); + request.has_optionals = !request.optionals.timezone.empty(); + } + + 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/definition.h b/src/core/definition.h index cd854ef..d00a691 100644 --- a/src/core/definition.h +++ b/src/core/definition.h @@ -161,6 +161,53 @@ 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 +// 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 {}; + +// 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 @@ -175,12 +222,22 @@ 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); 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"); } @@ -200,20 +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. // + // **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()) { - 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/src/core/executor.cpp b/src/core/executor.cpp index 2e95dfe..b812ad4 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,20 @@ 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. 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); + } + } + ++entry.attempts; entry.started_at_ms = now; diff --git a/src/core/executor.h b/src/core/executor.h index e0eb1d6..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. @@ -81,6 +85,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 +207,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/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/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/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 new file mode 100644 index 0000000..843f558 --- /dev/null +++ b/src/core/session.cpp @@ -0,0 +1,42 @@ +#include + +#include "json.h" + +namespace lootlocker { + +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 (!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); + } + + // Optional: an absent name genuinely means "not set", and the API omits the rest on + // some auth paths. + 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); + } + + 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..af7426d --- /dev/null +++ b/tests/test_auth.cpp @@ -0,0 +1,723 @@ +// Guest auth (T14). +// +// The verification the task asks for: `auth::StartGuestSession` over +// `POST /game/v2/session/guest`, including the guest identifier's reuse across restarts. + +#include +#include +#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::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 { + 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 once: 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()); + } +}; + +// 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. +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"); + + 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(!FieldFromBody(sent->body, "player_identifier").empty()); +} + +// 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); + if (sent == nullptr) { + 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("character_name") == std::string::npos); +} + +// 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)); + + GuestSessionInputs inputs; + inputs.optionals = SessionOptionals(); // all defaults + + 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("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 ---------------------------------------------------------- + +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); + + CHECK(f.client->HasSession()); + CHECK_EQ(f.client->GetSession().session_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(); + 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, ""); +} + +// 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 +// 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 TestGuestIdentifierIsReusedAcrossRestarts() +{ + 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) { + first_identifier = FieldFromBody(sent->body, "player_identifier"); + } + 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) { + CHECK_EQ(FieldFromBody(sent->body, "player_identifier"), first_identifier); + } + } +} + +// An explicit identifier wins over the persisted one, and is persisted itself. +void TestExplicitIdentifierWinsAndPersists() +{ + TempFile file("explicit"); + + std::shared_ptr writer = + std::make_shared(file.path); + + Config config = MakeConfig(); + config.state_writer = writer; + + { + Fixture f(config); + + GuestSessionInputs inputs; + inputs.guest_identifier = std::string("chosen-by-the-game"); + + 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_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`. +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) { + *out = FieldFromBody(sent->body, "player_identifier"); + } + } + + CHECK(!first.empty()); + CHECK(!second.empty()); + CHECK(first != second); +} + +// --- platform -------------------------------------------------------------- + +void TestPlatformNames() +{ + 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"); + + Platform parsed = Platform::None; + CHECK(lootlocker::TryParsePlatform("steam", parsed)); + CHECK(parsed == Platform::Steam); + + // An unknown name is a contract change, not a missing value. + 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() +{ + 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(); + TestTokenIsNotSentOnAuthRequest(); + TestOptionalsAreNested(); + TestOptionalsFields(); + TestDefaultsAreOmitted(); + TestTimezoneResolution(); + TestSendTimezoneFalse(); + TestSuccessfulSession(); + TestMissingRequiredFieldIsAnError(); + TestMissingOptionalFieldIsFine(); + TestEmptyBodyIsNotASuccess(); + TestNoContentIsNotASuccessForRequiredResponse(); + TestWrongTypeMessage(); + TestTimezoneFallsBackToTheSystem(); + TestInjectedProviderWins(); + TestGuestIdentifierIsReusedAcrossRestarts(); + TestExplicitIdentifierWinsAndPersists(); + TestNullWriterGeneratesNewIdentifierEachTime(); + TestPlatformNames(); + TestSessionAccessors(); + TestReturnsExecutorId(); + return testing::Report(); +}