ADR-0131: Keycloak sign-in in the Windows engineering client
Foundation / checks (ecs) (push) Successful in 2m21s
Foundation / checks (deploy) (push) Successful in 4m1s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (tsan) (push) Canceled after 7m21s
Foundation / checks (network) (push) Canceled after 9m43s
Foundation / checks (checks) (push) Canceled after 9m49s
Foundation / checks (postgres) (push) Canceled after 9m43s
Foundation / checks (client) (push) Canceled after 9m48s

Sign In / Register opens the system browser (PKCE S256, loopback 127.0.0.1:47600)
and keeps the refresh token in Windows Credential Manager. The client then fetches
a 10-minute grant from grants.aeternalisgames.com and connects to the cellular DEV
region. It renews the grant about a minute before expiry through SessionRefresh,
and again after a lost connection. Sign Out closes the session and revokes the
login at the broker and at Keycloak. Grant replies are cross-checked against the
grant record before use. The manual grant-bundle path stays for developers.

The bounded JSON reader moves to evo_json (evo::serialization), shared by the
broker and the client. Adds the client-auth tests. Completes work started in
another session: main.cpp wiring, refresh expiry tracking, no requests for a
superseded session, and clang-tidy and Windows header-order fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-15 15:31:33 -04:00
co-authored by Claude Opus 5.5
parent dec34f39e4
commit 2a5c0d0e22
22 changed files with 1622 additions and 72 deletions
+8 -2
View File
@@ -46,6 +46,12 @@ set(EVO_SANITIZER "none" CACHE STRING "none, address (ASan/UBSan), or thread")
set_property(CACHE EVO_SANITIZER PROPERTY STRINGS none address thread)
include(cmake/ProjectOptions.cmake)
if(EVO_BUILD_CLIENT OR EVO_BUILD_POSTGRES)
add_library(evo_json STATIC src/serialization/json.cpp)
target_include_directories(evo_json PUBLIC "${PROJECT_SOURCE_DIR}/include")
evo_owned_target(evo_json)
endif()
set(evo_simulation_sources src/simulation/world.cpp src/simulation/snapshot.cpp src/simulation/scheduler.cpp src/simulation/spatial.cpp)
add_library(evo_simulation STATIC ${evo_simulation_sources})
add_library(evo::simulation ALIAS evo_simulation)
@@ -277,9 +283,9 @@ if(EVO_BUILD_POSTGRES)
target_link_libraries(evo_control_ledger_postgres PUBLIC evo::postgres evo_network_protocol)
evo_owned_target(evo_control_ledger_postgres)
# ADR-0131 Keycloak grant broker (schema v39).
add_library(evo_grant_broker STATIC src/server/broker/json.cpp
add_library(evo_grant_broker STATIC
src/server/broker/access_token.cpp src/server/broker/grant_broker.cpp)
target_link_libraries(evo_grant_broker PUBLIC evo::region_host evo_network_tls
target_link_libraries(evo_grant_broker PUBLIC evo_json evo::region_host evo_network_tls
PRIVATE OpenSSL::Crypto)
evo_owned_target(evo_grant_broker)
add_executable(evo-grant-broker apps/evo-grant-broker/main.cpp)
+3 -3
View File
@@ -21,12 +21,12 @@
{"name": "analysis", "configurePreset": "analysis"},
{"name": "asan", "configurePreset": "asan"},
{"name": "tsan", "configurePreset": "tsan"},
{"name": "client", "configurePreset": "client", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests"]},
{"name": "client", "configurePreset": "client", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-client-auth-tests"]},
{"name": "client-probe", "configurePreset": "client-probe", "targets": ["evo-client-probe"]},
{"name": "network", "configurePreset": "network", "targets": ["evo-client-state-tests", "evo-network-tests", "evo-cellular-intent-protocol-tests", "evo-cellular-intent-admission-tests", "evo-session-fuzz-smoke", "evo-dev-session"]},
{"name": "quic", "configurePreset": "quic", "targets": ["evo-quic-smoke-tests", "evo-quic-transport-tests", "evo-quic-session-tests", "evo-quic-hol-measure", "evo-session-probe", "evo-load", "evo-network-tests", "evo-cellular-intent-protocol-tests", "evo-cellular-intent-admission-tests", "evo-session-fuzz-smoke"]},
{"name": "client-network", "configurePreset": "client-network", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-network-tests", "evo-cellular-intent-protocol-tests", "evo-cellular-intent-admission-tests", "evo-session-fuzz-smoke", "evo-dev-session", "evo-quic-session-tests", "evo-client-remote-tests", "evo-motion-trace", "evo-session-probe"]},
{"name": "client-package", "configurePreset": "client-package", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-network-tests", "evo-cellular-intent-protocol-tests", "evo-cellular-intent-admission-tests", "evo-session-fuzz-smoke", "evo-dev-session", "evo-quic-session-tests", "evo-client-remote-tests", "evo-motion-trace"]}
{"name": "client-network", "configurePreset": "client-network", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-client-auth-tests", "evo-network-tests", "evo-cellular-intent-protocol-tests", "evo-cellular-intent-admission-tests", "evo-session-fuzz-smoke", "evo-dev-session", "evo-quic-session-tests", "evo-client-remote-tests", "evo-motion-trace", "evo-session-probe"]},
{"name": "client-package", "configurePreset": "client-package", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-client-auth-tests", "evo-network-tests", "evo-cellular-intent-protocol-tests", "evo-cellular-intent-admission-tests", "evo-session-fuzz-smoke", "evo-dev-session", "evo-quic-session-tests", "evo-client-remote-tests", "evo-motion-trace"]}
],
"testPresets": [
{"name": "debug", "configurePreset": "debug", "output": {"outputOnFailure": true}},
+85
View File
@@ -1,6 +1,7 @@
#include "cellular_scene.hpp"
#include "controls_flow.hpp"
#include "evo/client/application.hpp"
#include "evo/client/auth.hpp"
#include "evo/client/launcher.hpp"
#include "evo/client/selection.hpp"
#include "evo/client/session_host.hpp"
@@ -19,6 +20,7 @@
#include <filesystem>
#include <memory>
#include <optional>
#include <span>
#include <string_view>
#include <thread>
#include <utility>
@@ -229,6 +231,12 @@ std::uint64_t milliseconds(std::chrono::steady_clock::time_point t) {
return static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(t.time_since_epoch()).count());
}
// Wall-clock seconds: grant expiry is UTC (the session compares the server's welcome).
std::uint64_t utc_seconds() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
} // namespace
int main(int argc, char** argv) try {
@@ -351,6 +359,36 @@ int main(int argc, char** argv) try {
return host.connect(std::move(opened));
}
};
// ADR-0131: a broker grant names its region route; only the region CA comes from the
// form. The grant stays in memory and the session asks for the next one itself.
const auto grant_material = [&](const evo::client::AuthGrant& grant) {
auto f = buffers.form();
f.endpoint = grant.endpoint;
f.server_name = grant.server_name;
return evo::client::load_connect(f, std::span{&grant.bytes, 1});
};
const auto connect_signed_in = [&](const evo::client::AuthGrant& grant) {
form_error.reset();
if constexpr (!evo::client_app::remote_available) {
form_error = evo::client::LaunchError::no_session;
return false;
} else {
const auto material = grant_material(grant);
if (!material) {
form_error = material.error();
return false;
}
cellular_trial = true; // The DEV broker world is the cellular trial (ADR-0131).
auto opened = evo::client_app::RemoteSession::open(*material, cellular_trial);
if (!opened) {
form_error = evo::client::LaunchError::endpoint;
return false;
}
opened->manage_grants();
cellular_framed = false;
return host.connect(std::move(opened));
}
};
const auto enter_fixture = [&] {
if (!authority) {
authority = make_authority();
@@ -419,6 +457,10 @@ int main(int argc, char** argv) try {
return &remote->organisms();
return nullptr;
};
// ADR-0131 browser sign-in (Windows); elsewhere the panel offers manual grants only.
evo::client::AuthClient auth{evo::client::native_auth_platform()};
bool auth_connect = false; // Connect when the requested grant arrives.
auto grant_requested = std::chrono::steady_clock::time_point{};
int drawn_organisms = -1;
evo::client_app::PanelActions actions;
(*app)->set_overlay([&] {
@@ -428,6 +470,7 @@ int main(int argc, char** argv) try {
view.form_error = form_error;
view.remote_available = evo::client_app::remote_available;
view.cellular_trial = cellular_trial;
view.auth = auth.status();
view.environment = shown_environment();
view.organisms = shown_organisms();
view.selection = &selection;
@@ -512,6 +555,48 @@ int main(int argc, char** argv) try {
remote->set_cellular_feed_target(cellular_trial ? cellular_feed_target : std::nullopt);
remote->set_cellular_controls(buffers.cellular_controls);
}
// ADR-0131 sign-in. One request at a time; grants arrive on a later frame.
if (actions.sign_in && auth.sign_in()) {
auth_connect = true;
grant_requested = now;
}
if (actions.auth_connect && auth.request_grant()) {
auth_connect = true;
grant_requested = now;
}
if (actions.cancel_sign_in) {
auth.cancel();
auth_connect = false;
}
if (actions.sign_out) {
host.cancel(); // Logout revokes every grant; do not keep a session behind it.
cellular_feed_target.reset();
selection.clear();
auth_connect = false;
static_cast<void>(auth.sign_out());
}
if (auto grant = auth.take_grant()) {
if (auth_connect) {
auth_connect = false;
if (connect_signed_in(*grant))
selection.clear();
} else if (auto* remote = host.session()) {
// Refresh or reconnect material for the live session (same account).
if (const auto material = grant_material(*grant))
static_cast<void>(remote->supply_grant(*material));
}
grant->bytes.fill(0);
}
if (const auto status = auth.status(); !status.busy && auth_connect && !status.signed_in)
auth_connect = false; // Sign-in failed or was cancelled; the panel shows why.
// About a minute before expiry, or after a lost connection; never for a session the
// launcher has given up on (superseded by another client, cancelled).
const bool live = launcher.phase() == evo::client::LaunchPhase::connecting ||
launcher.phase() == evo::client::LaunchPhase::connected;
if (const auto* remote = host.session();
live && remote && remote->needs_grant(utc_seconds()) &&
now - grant_requested >= std::chrono::seconds{5} && auth.request_grant())
grant_requested = now;
controls.step(actions, **app, ui);
actions = {};
// The launcher and modal dialogs own input: no world movement or selection.
+50 -12
View File
@@ -121,18 +121,48 @@ void launcher(const PanelView& v, FormBuffers& form, PanelActions& a) {
"server, not an ecosystem, not authoritative.");
ImGui::Separator();
ImGui::TextUnformatted("Connect to a dev region");
ImGui::BeginDisabled(!v.remote_available || phase == LaunchPhase::connecting);
ImGui::InputText("Endpoint (host:port)", form.endpoint.data(), form.endpoint.size());
ImGui::InputText("Server name", form.server_name.data(), form.server_name.size());
ImGui::InputText("Dev CA file", form.authority.data(), form.authority.size());
ImGui::InputText("Grant bundle file", form.grants.data(), form.grants.size());
bool cellular_trial = v.cellular_trial;
if (ImGui::Checkbox("Cellular play (v10)", &cellular_trial))
a.cellular_trial = cellular_trial;
const bool start = phase == LaunchPhase::choosing && ImGui::Button("Connect", {px(160), 0});
ImGui::InputText("Region CA file", form.authority.data(), form.authority.size());
ImGui::BeginDisabled(!v.remote_available || !v.auth.supported || v.auth.busy ||
phase == LaunchPhase::connecting);
if (ImGui::Button(v.auth.signed_in ? "Play in DEV" : "Sign in / Register", {-1, px(34)})) {
a.sign_in = !v.auth.signed_in;
a.auth_connect = v.auth.signed_in;
}
ImGui::EndDisabled();
if (start)
a.connect = true;
if (v.auth.busy) {
ImGui::TextWrapped(
"%s",
v.auth.phase == client::AuthPhase::signing_out ? "Signing out..."
: v.auth.phase == client::AuthPhase::renewing
? "Renewing your connection..."
: "Complete sign-in in your browser, then return here. Connecting is automatic.");
if (v.auth.phase == client::AuthPhase::signing_in && ImGui::Button("Cancel sign-in"))
a.cancel_sign_in = true;
} else if (v.auth.signed_in && ImGui::SmallButton("Sign out"))
a.sign_out = true;
if (v.auth.error) {
ImGui::PushStyleColor(ImGuiCol_Text, amber);
const auto text = client::auth_error_text(*v.auth.error);
ImGui::PushTextWrapPos(0.0F);
ImGui::TextUnformatted(text.data(), text.data() + text.size());
ImGui::PopTextWrapPos();
ImGui::PopStyleColor();
}
ImGui::TextWrapped(
"Your password stays in the system browser. Windows Credential Manager stores your login.");
if (ImGui::CollapsingHeader("Manual connection (developer grants)")) {
ImGui::BeginDisabled(!v.remote_available || phase == LaunchPhase::connecting);
ImGui::InputText("Endpoint (host:port)", form.endpoint.data(), form.endpoint.size());
ImGui::InputText("Server name", form.server_name.data(), form.server_name.size());
ImGui::InputText("Grant bundle file", form.grants.data(), form.grants.size());
bool cellular_trial = v.cellular_trial;
if (ImGui::Checkbox("Cellular play (v10)", &cellular_trial))
a.cellular_trial = cellular_trial;
const bool start = phase == LaunchPhase::choosing && ImGui::Button("Connect", {px(160), 0});
ImGui::EndDisabled();
if (start)
a.connect = true;
}
if (!v.remote_available)
ImGui::TextColored(amber, "Remote mode needs a build with EVO_BUILD_NETWORK.");
if (v.form_error)
@@ -150,7 +180,8 @@ void launcher(const PanelView& v, FormBuffers& form, PanelActions& a) {
if (ImGui::Button("Cancel", {px(120), 0}))
a.cancel = true;
}
ImGui::TextDisabled("Files are read when you connect; nothing is saved.");
ImGui::TextWrapped("The region CA is still required to verify the game server. Manual grant "
"files are only read when connecting.");
ImGui::End();
}
@@ -168,6 +199,13 @@ void banner(const PanelView& v, PanelActions& a) {
ImGui::SameLine();
if (ImGui::SmallButton("Controls"))
a.open_controls = true;
if (v.auth.signed_in) {
ImGui::SameLine();
ImGui::BeginDisabled(v.auth.busy);
if (ImGui::SmallButton("Sign out"))
a.sign_out = true;
ImGui::EndDisabled();
}
} else {
ImGui::TextColored(v.remote && v.remote->phase == "connected" ? green : amber,
"DEV REGION - %s%s", v.remote ? v.remote->phase.c_str() : "?",
+3
View File
@@ -2,6 +2,7 @@
// M9.8c engineering panels (ADR-0084). Drawn inside Application's overlay callback;
// they read presentation copies and report what the user asked for. Only this file
// pair and the platform adapter use the toolkit.
#include "evo/client/auth.hpp"
#include "evo/client/bindings.hpp"
#include "evo/client/environment_view.hpp"
#include "evo/client/launcher.hpp"
@@ -41,6 +42,7 @@ struct PanelView {
std::optional<client::LaunchError> form_error;
bool remote_available{};
bool cellular_trial{};
client::AuthStatus auth;
const client::EnvironmentLayer* environment{};
const client::OrganismLayer* organisms{};
const client::Selection* selection{};
@@ -59,6 +61,7 @@ struct PanelView {
};
struct PanelActions {
bool fixture{}, connect{}, cancel{}, retry{}, back{}, ask_disconnect{};
bool sign_in{}, sign_out{}, auth_connect{}, cancel_sign_in{};
std::optional<std::uint64_t> dismiss_notice, confirm_dialog, cancel_dialog;
bool open_controls{}, apply_controls{}, reset_controls{}, close_controls{}, cancel_capture{};
std::optional<ControlSlot> capture_key;
+69 -3
View File
@@ -174,6 +174,8 @@ class RemoteSession {
session.transport_.authority_pem = m.authority_pem;
session.transport_.authority_pem_file = m.authority_path;
session.grants_ = m.grants;
std::copy_n(m.grants.front().begin() + 32, session.account_.size(),
session.account_.begin());
session.cellular_trial_ = cellular_trial;
session.cellular_play_.initialize(static_cast<std::uint64_t>(
std::chrono::system_clock::now().time_since_epoch().count()));
@@ -187,6 +189,47 @@ class RemoteSession {
RemoteSession& operator=(RemoteSession&&) noexcept = default;
RemoteSession(const RemoteSession&) = delete;
RemoteSession& operator=(const RemoteSession&) = delete;
void manage_grants() {
managed_grants_ = true;
}
[[nodiscard]] bool needs_grant(std::uint64_t utc_now) const {
if (!managed_grants_)
return false;
if (!client_)
return exhausted_ || std::ranges::all_of(used_, [](bool used) { return used; });
const auto& welcome = client_->welcome();
return client_->state() == client::RegionSessionState::established && welcome &&
std::max(welcome->expires_at, refreshed_until_) <= utc_now + 60 && !refresh_waiting_;
}
// Grants are supplied by the authenticated broker, never written to a bundle.
[[nodiscard]] bool supply_grant(const client::ConnectMaterial& material) {
if (!managed_grants_ || material.grants.size() != 1 ||
material.authority_pem != transport_.authority_pem)
return false;
const auto& grant = material.grants.front();
const auto serial = grant_serial(grant);
if (serial < newest_serial_ || serial == UINT64_MAX ||
!std::equal(account_.begin(), account_.end(), grant.begin() + 32))
return false;
const auto region = grant_region(grant);
if (client_ && client_->state() == client::RegionSessionState::established) {
if (region != region_ || !client_->refresh(grant))
return false;
newest_serial_ = serial + 1;
refresh_waiting_ = true;
refresh_sent_at_ = Clock::now();
return true;
}
if (!learn_route({region,
material.endpoint.host + ":" + std::to_string(material.endpoint.port),
material.server_name}))
return false;
grants_.assign(1, grant);
used_.assign(1, false);
target_region_ = region;
exhausted_ = false;
return true;
}
~RemoteSession() {
if (client_)
client_->close(); // Close{client_closed}; unresolved intentions stay unknown.
@@ -350,6 +393,13 @@ class RemoteSession {
return;
auto& c = *client_;
c.poll(now);
if (const auto refreshed = c.take_refresh_result()) {
refresh_waiting_ = false;
if (refreshed->status == 0) // Accepted: the session now runs to the new expiry.
refreshed_until_ = std::max(refreshed_until_, refreshed->expires_at);
} else if (refresh_waiting_ && now - refresh_sent_at_ >= std::chrono::seconds{5}) {
refresh_waiting_ = false;
}
if (c.state() == client::RegionSessionState::closed) {
end(now, ui, launcher);
return;
@@ -472,9 +522,12 @@ class RemoteSession {
if (pick == grants_.size()) {
if (!exhausted_) {
exhausted_ = true;
launcher.observe(client::ConnectSignal::exhausted);
std::printf("session grants for region %llu exhausted; issue a new bundle\n",
static_cast<unsigned long long>(target_region_));
if (!managed_grants_) {
launcher.observe(client::ConnectSignal::exhausted);
std::printf(
"session grants for region %llu exhausted; issue a new bundle\n",
static_cast<unsigned long long>(target_region_));
}
}
return false;
}
@@ -491,6 +544,8 @@ class RemoteSession {
}
client_ = std::move(*made);
established_ = false;
refreshed_until_ = 0; // A new session starts from its own welcome.
refresh_waiting_ = false;
return true;
}
void pause(Clock::time_point now) {
@@ -860,6 +915,10 @@ class RemoteSession {
network::quic::ClientConfig transport_;
std::vector<network::WireGrant> grants_;
std::vector<bool> used_;
std::array<std::uint8_t, 16> account_{};
bool managed_grants_{}, refresh_waiting_{};
std::uint64_t refreshed_until_{}; // Expiry from the last accepted SessionRefresh.
Clock::time_point refresh_sent_at_{};
std::map<std::uint64_t, network::quic::ClientConfig> routes_; // Region -> how to dial it.
std::uint64_t target_region_{}, region_{}, handoffs_{}, newest_serial_{};
std::optional<network::WireGrant> ticket_; // A handoff ticket for the next connection.
@@ -903,6 +962,13 @@ class RemoteSession {
inline constexpr bool remote_available = false;
class RemoteSession {
public:
void manage_grants() {}
[[nodiscard]] bool needs_grant(std::uint64_t) const {
return false;
}
[[nodiscard]] bool supply_grant(const client::ConnectMaterial&) {
return false;
}
static std::optional<RemoteSession> open(const client::ConnectMaterial&, bool = false) {
return std::nullopt;
}
+17
View File
@@ -69,6 +69,16 @@ if(EVO_BUILD_CLIENT)
add_executable(evo-client apps/evo-client/main.cpp apps/evo-client/panels.cpp)
target_link_libraries(evo-client PRIVATE evo_client_platform evo_client_ui evo_imgui)
target_compile_definitions(evo-client PRIVATE EVO_BUILD_IDENTITY="${EVO_BUILD_IDENTITY}")
find_package(Threads REQUIRED)
add_library(evo_client_auth STATIC src/client/auth/protocol.cpp src/client/auth/client.cpp)
target_link_libraries(evo_client_auth PUBLIC evo_client_ui PRIVATE evo_json Threads::Threads)
if(WIN32)
target_sources(evo_client_auth PRIVATE src/client/auth/windows.cpp)
target_compile_definitions(evo_client_auth PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_link_libraries(evo_client_auth PRIVATE winhttp bcrypt advapi32 shell32 ws2_32)
endif()
evo_owned_target(evo_client_auth)
target_link_libraries(evo-client PRIVATE evo_client_auth)
if(EVO_BUILD_QUIC)
# M10.5c remote dev session mode over M10 QUIC sessions (ADR-0093); replaces the M9.7
# TCP session (ADR-0083), whose dev route is gone (ADR-0087).
@@ -133,8 +143,15 @@ if(EVO_BUILD_CLIENT)
add_executable(evo-client-panel-tests tests/client_panels.cpp apps/evo-client/panels.cpp)
target_include_directories(evo-client-panel-tests PRIVATE "${PROJECT_SOURCE_DIR}/apps/evo-client")
target_link_libraries(evo-client-panel-tests PRIVATE evo_client_platform evo_client_ui SDL3::SDL3 evo_imgui)
target_link_libraries(evo-client-panel-tests PRIVATE evo_client_auth)
evo_owned_target(evo-client-panel-tests)
evo_client_runtime(evo-client-panel-tests)
# ADR-0131 sign-in: callback, token and grant replies, worker against a scripted platform.
add_executable(evo-client-auth-tests tests/client_auth.cpp)
target_link_libraries(evo-client-auth-tests PRIVATE evo_client_auth)
evo_owned_target(evo-client-auth-tests)
add_test(NAME client-auth COMMAND evo-client-auth-tests)
set_tests_properties(client-auth PROPERTIES TIMEOUT 60 LABELS "client")
add_test(NAME client-panels COMMAND evo-client-panel-tests)
add_test(NAME client-lifecycle COMMAND evo-client-lifecycle-tests)
add_test(NAME client-smoke COMMAND evo-client --renderer software --frames 3)
+2 -2
View File
@@ -43,13 +43,13 @@ RUN cmake -P tools/prepare-sdl3.cmake \
&& cmake -P tools/prepare-imgui.cmake \
&& cmake --preset client-probe -DCMAKE_CXX_COMPILER=clang++-19 -DCMAKE_C_COMPILER=clang-19 \
-DEVO_BUILD_CLIENT=ON -DEVO_BUILD_UI_PROBE=ON -DEVO_ENABLE_TIDY=ON -DSDL_X11=ON -DSDL_WAYLAND=OFF \
&& cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests evo-client-bindings-tests --parallel 2 \
&& cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests evo-client-bindings-tests evo-client-auth-tests --parallel 2 \
&& ctest --preset client-probe --no-tests=error \
&& xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-probe --renderer software \
&& for cycle in 1 2 3; do xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-ui-probe --renderer software --cycles 1; done \
&& xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests \
&& cmake --preset client-probe -DEVO_BUILD_CLIENT=ON -DEVO_SANITIZER=address -DEVO_ENABLE_TIDY=OFF \
&& cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests evo-client-bindings-tests --parallel 2 \
&& cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests evo-client-bindings-tests evo-client-auth-tests --parallel 2 \
&& ctest --preset client-probe --no-tests=error \
&& for cycle in 1 2 3; do xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-ui-probe --renderer software --cycles 1; done \
&& xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests
@@ -12,7 +12,7 @@ spec:
env:
- {name: REGION_SESSION, value: "dev"}
- {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261015T181504-60231:1792098904"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261015T193133-96611:1792103493"}
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"}
ports:
# QUIC (ADR-0090): UDP only; nothing listens on TCP 7400.
@@ -73,6 +73,30 @@ never be minted on a client.
4. On logout: `POST /logout`, then revoke the refresh token at Keycloak's revocation
endpoint.
### Client implementation (Windows engineering client)
- `evo_client_auth`: the protocol parsers (`protocol.cpp`), one worker thread
(`AuthClient`, `client.cpp`) and the Windows platform (`windows.cpp`). On other
systems sign-in is unavailable, and the manual grant-bundle path remains.
- Sign-in opens the system browser with PKCE S256 and a random state. A loopback
listener on `127.0.0.1:47600` accepts exactly one `/callback` with that state and an
`iss` of the realm, if present. The password never reaches the client.
- The refresh token is stored only in Windows Credential Manager
(`AeternalisEvolution/DEV/refresh-token/v1`). Rotation removes the stored token
before it is sent, so a lost reply ends the login instead of replaying a consumed
token. Access tokens and grants stay in memory and are zeroed when dropped.
- A grant reply is accepted only if its JSON agrees with the grant record: marker,
version, dev environment, account, region, expiry (at most 15 minutes ahead) and a
nonzero serial. The region still verifies the signature.
- The region CA file is still required from the launcher. Endpoint and TLS name come
from the broker's route.
- The session asks for a new grant about 60 s before its expiry, extended by each
accepted `SessionRefresh`, and after a lost connection. It never asks for a session
that was superseded or cancelled. Requests are at least 5 s apart.
- Sign-out closes the session, then calls `/logout` (broker revocation) and Keycloak
revocation, and clears the stored token. If revocation cannot be confirmed, the
client says so: issued grants may live until they expire.
### Deployment (DEV)
- `deploy/kubernetes/grant-broker-dev`, a component of `region/dev` so it runs the
+8
View File
@@ -27,6 +27,14 @@ watermark, grants left, the snapshot, interest and snapshot bytes, and the last
intentions with their outcome (sent, admitted, rejected, simulated, unknown; M10.5c). That list is the record;
short notifications expire and can be dismissed.
**Sign in / Register** (Windows, ADR-0131) opens the system browser for Keycloak.
After sign-in the client fetches a 10-minute grant from `grants.aeternalisgames.com`
and connects to the cellular DEV region. It renews the grant before expiry and after a
lost connection. **Play in DEV** reconnects while signed in. **Sign out** closes the
session and revokes the login. Only the region CA file is still read from the form.
The manual endpoint and grant-bundle fields stay under "Manual connection
(developer grants)".
## Build and run
### Cellular v10
+40
View File
@@ -7610,3 +7610,43 @@ nursery stall is reproduced locally, not confirmed as this player's precise live
refusal. This gate changes neither nursery resources nor simulation/replay rules.
No deployment or World0 operation ran. Authentication is a following gate under
ADR-0131. The unrelated deployment edit and untracked files were preserved.
## 2026-10-15 — ADR-0131 client sign-in (CI pending)
The Windows engineering client signs in with Keycloak in the system browser (PKCE S256,
loopback `127.0.0.1:47600`), keeps the refresh token in Windows Credential Manager,
fetches 10-minute grants from the broker and connects to the DEV region. It renews
grants about 60 s before expiry through `SessionRefresh`, and again after a lost
connection. Sign-out revokes at the broker and at Keycloak. The bounded JSON reader
moved to `evo_json` (`evo::serialization`), which the broker and the client share.
This completes the in-progress client work from another session. The fixes:
- `main.cpp` wiring (sign in, connect on the first grant, renew, sign out);
- the session now records the expiry from accepted refreshes, so it no longer asks
for a grant every 5 s;
- no grant requests for a superseded or cancelled session;
- clang-tidy findings (enum sizes, `stop_token` by reference, an unterminated
`string_view` in the panel);
- the Windows SDK header order, pinned against clang-format reordering.
New `client-auth` tests (`tests/client_auth.cpp`):
- callback path, state, `iss`, duplicate and control-character refusals;
- token replies and their error mapping;
- grant replies cross-checked against the record: region, expiry, account,
environment, serial, padding and lifetime bound;
- the worker on a scripted platform: first login with PKCE fields, saved-login
rotation, fallback to the browser after a revoked refresh token, account change
refused, logout order, unconfirmed revocation, unverified email, credential-store
failure, and cancel and destruction while the browser is open.
Executed locally:
- WSL clang-19 `client-probe` with clang-tidy as CI runs it: 14/14 CTests, plus the
Xvfb X11 lifecycle check;
- ASan/UBSan `client-auth` three times, plus `client-panels`;
- MSVC `tools/windows-check.ps1 -Preset client-package`: 18/18, including
`client-auth` and the QUIC session tests;
- the PostgreSQL broker build on the moved parser;
- clang-format 19.
Limits: no live sign-in against `auth.aeternalisgames.com` yet. That needs the broker
pod running (the issuer key name) and the `grants.aeternalisgames.com` Ingress.
+109
View File
@@ -0,0 +1,109 @@
#pragma once
#include "evo/client/launcher.hpp"
#include <chrono>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
namespace evo::client {
inline constexpr std::string_view auth_redirect = "http://127.0.0.1:47600/callback";
inline constexpr std::string_view auth_client_id = "aevolution-game";
enum class AuthError : std::uint8_t {
unavailable,
cancelled,
listener,
timeout,
browser,
transport,
invalid_response,
denied,
token_expired,
email_unverified,
throttled,
service_unavailable,
credential_store,
logout_incomplete
};
[[nodiscard]] std::string_view auth_error_text(AuthError error);
struct AuthGrant {
GrantRecord bytes{};
std::string account, endpoint, server_name;
std::uint64_t region{}, expires_at{};
};
struct AuthTokens {
std::string access, refresh;
std::uint64_t lifetime{};
};
struct AuthorizationCode {
std::string code, verifier;
};
struct AuthHttpReply {
unsigned status{};
std::string body;
};
enum class AuthEndpoint : std::uint8_t { token, grant, logout, revoke };
// Opaque tokens stay inside the worker/platform boundary. No UI, logs or plaintext files.
class AuthPlatform {
public:
virtual ~AuthPlatform() = default;
[[nodiscard]] virtual std::expected<AuthorizationCode, AuthError>
authorize(std::stop_token stop) = 0;
[[nodiscard]] virtual std::expected<AuthHttpReply, AuthError> post(AuthEndpoint endpoint,
std::string_view body,
std::string_view bearer,
std::stop_token stop) = 0;
[[nodiscard]] virtual std::expected<std::string, AuthError> load_refresh() = 0;
[[nodiscard]] virtual bool save_refresh(std::string_view token) = 0;
[[nodiscard]] virtual bool erase_refresh() = 0;
};
[[nodiscard]] std::unique_ptr<AuthPlatform> native_auth_platform(); // Windows; null elsewhere.
[[nodiscard]] std::string auth_form_escape(std::string_view value);
[[nodiscard]] std::string auth_base64url(std::span<const std::uint8_t> bytes);
[[nodiscard]] std::string auth_authorization_url(std::string_view state,
std::string_view challenge);
// Only the exact loopback path, one matching state, and one code (or denial) are accepted.
[[nodiscard]] std::expected<std::string, AuthError> auth_callback(std::string_view target,
std::string_view state);
[[nodiscard]] std::expected<AuthTokens, AuthError> auth_tokens(const AuthHttpReply& reply);
[[nodiscard]] std::expected<AuthGrant, AuthError> auth_grant(const AuthHttpReply& reply,
std::uint64_t now_seconds);
enum class AuthPhase : std::uint8_t {
signed_out,
signing_in,
ready,
renewing,
signing_out,
failed
};
struct AuthStatus {
AuthPhase phase{AuthPhase::signed_out};
bool supported{}, busy{}, signed_in{};
std::optional<AuthError> error;
};
// One joined worker, serialized refresh-token rotation; main-thread caller only.
// Destruction cancels browser waiting and joins bounded network work.
class AuthClient {
public:
explicit AuthClient(std::unique_ptr<AuthPlatform> platform);
~AuthClient();
AuthClient(const AuthClient&) = delete;
AuthClient& operator=(const AuthClient&) = delete;
[[nodiscard]] bool sign_in();
[[nodiscard]] bool request_grant();
[[nodiscard]] bool sign_out();
void cancel();
[[nodiscard]] AuthStatus status() const;
[[nodiscard]] std::optional<AuthGrant> take_grant();
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace evo::client
+4
View File
@@ -3,6 +3,7 @@
#include <cstddef>
#include <cstdint>
#include <expected>
#include <span>
#include <string>
#include <string_view>
#include <vector>
@@ -54,6 +55,9 @@ struct ConnectMaterial {
// "host:port", "[ipv6]:port" or "a.b.c.d:port"; plain DNS host names only.
[[nodiscard]] std::expected<Endpoint, LaunchError> parse_endpoint(std::string_view text);
[[nodiscard]] std::expected<ConnectMaterial, LaunchError> load_connect(const ConnectForm& form);
// Broker grants stay in memory; the existing pinned region CA is still required.
[[nodiscard]] std::expected<ConnectMaterial, LaunchError>
load_connect(const ConnectForm& form, std::span<const GrantRecord> grants);
// What the session reports while connecting, reduced to what the launcher decides on.
enum class ConnectSignal : std::uint8_t {
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
// ADR-0131: a small, bounded JSON reader for access-token claims and the realm's JWKS.
// It accepts RFC 8259 JSON within the bounds below and nothing else (no comments, no
// trailing commas, no duplicate-key resolution beyond "first wins").
namespace evo::serialization {
inline constexpr std::size_t max_json_bytes = std::size_t{16} * 1024;
inline constexpr std::size_t max_json_depth = 16;
class JsonValue {
public:
enum class Kind : std::uint8_t { null, boolean, number, string, array, object };
[[nodiscard]] Kind kind() const noexcept {
return kind_;
}
// Typed views; nullopt or nullptr when the value has another kind.
[[nodiscard]] std::optional<bool> boolean() const;
[[nodiscard]] std::optional<std::string_view> string() const;
// Integers only (no fraction or exponent), within 0..2^63-1.
[[nodiscard]] std::optional<std::uint64_t> integer() const;
[[nodiscard]] const JsonValue* member(std::string_view name) const;
[[nodiscard]] const std::vector<JsonValue>* array() const;
// Whole-document parse; nullopt for anything malformed or out of bounds.
[[nodiscard]] static std::optional<JsonValue> parse(std::string_view text);
private:
friend class JsonParser;
Kind kind_{Kind::null};
bool boolean_{};
std::string text_; // String value, or the number's literal.
std::vector<JsonValue> items_;
std::vector<std::pair<std::string, JsonValue>> members_;
};
} // namespace evo::serialization
+5 -41
View File
@@ -1,44 +1,8 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
// ADR-0131: a small, bounded JSON reader for access-token claims and the realm's JWKS.
// It accepts RFC 8259 JSON within the bounds below and nothing else (no comments, no
// trailing commas, no duplicate-key resolution beyond "first wins").
#include "evo/serialization/json.hpp"
// Compatibility names for the broker; the parser has no server or persistence dependency.
namespace evo::server::broker {
inline constexpr std::size_t max_json_bytes = std::size_t{16} * 1024;
inline constexpr std::size_t max_json_depth = 16;
class JsonValue {
public:
enum class Kind : std::uint8_t { null, boolean, number, string, array, object };
[[nodiscard]] Kind kind() const noexcept {
return kind_;
}
// Typed views; nullopt or nullptr when the value has another kind.
[[nodiscard]] std::optional<bool> boolean() const;
[[nodiscard]] std::optional<std::string_view> string() const;
// Integers only (no fraction or exponent), within 0..2^63-1.
[[nodiscard]] std::optional<std::uint64_t> integer() const;
[[nodiscard]] const JsonValue* member(std::string_view name) const;
[[nodiscard]] const std::vector<JsonValue>* array() const;
// Whole-document parse; nullopt for anything malformed or out of bounds.
[[nodiscard]] static std::optional<JsonValue> parse(std::string_view text);
private:
friend class JsonParser;
Kind kind_{Kind::null};
bool boolean_{};
std::string text_; // String value, or the number's literal.
std::vector<JsonValue> items_;
std::vector<std::pair<std::string, JsonValue>> members_;
};
using serialization::JsonValue;
using serialization::max_json_bytes;
using serialization::max_json_depth;
} // namespace evo::server::broker
+227
View File
@@ -0,0 +1,227 @@
#include "evo/client/auth.hpp"
#include <mutex>
#include <thread>
#include <utility>
namespace evo::client {
namespace {
void erase(std::string& value) {
for (auto& ch : value)
*static_cast<volatile char*>(&ch) = 0;
value.clear();
}
std::uint64_t utc_seconds() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
} // namespace
struct AuthClient::Impl {
explicit Impl(std::unique_ptr<AuthPlatform> adapter) : platform{std::move(adapter)} {
state.supported = platform != nullptr;
}
~Impl() {
worker.request_stop();
if (worker.joinable())
worker.join();
erase(tokens.access);
erase(tokens.refresh);
if (grant)
grant->bytes.fill(0);
}
enum class Job : std::uint8_t { login, grant, logout };
std::unique_ptr<AuthPlatform> platform;
mutable std::mutex mutex;
AuthStatus state;
std::optional<AuthGrant> grant;
AuthTokens tokens;
std::chrono::steady_clock::time_point access_until{};
std::string account;
std::jthread worker;
std::expected<void, AuthError> exchange(std::string body, const std::stop_token& stop) {
// Rotation is single-use. Remove the old saved token before sending so a
// crash or lost reply cannot replay an ambiguously consumed refresh token.
if (!platform->erase_refresh()) {
erase(body);
return std::unexpected{AuthError::credential_store};
}
auto response = platform->post(AuthEndpoint::token, body, {}, stop);
erase(body);
erase(tokens.access);
erase(tokens.refresh);
if (!response)
return std::unexpected{response.error()};
auto next = auth_tokens(*response);
erase(response->body);
if (!next)
return std::unexpected{next.error()};
if (!platform->save_refresh(next->refresh)) {
erase(next->access);
erase(next->refresh);
return std::unexpected{AuthError::credential_store};
}
access_until = std::chrono::steady_clock::now() + std::chrono::seconds{next->lifetime};
tokens = std::move(*next);
return {};
}
std::expected<void, AuthError> renew(const std::stop_token& stop) {
if (tokens.refresh.empty())
return std::unexpected{AuthError::token_expired};
return exchange("grant_type=refresh_token&client_id=" + std::string{auth_client_id} +
"&refresh_token=" + auth_form_escape(tokens.refresh),
stop);
}
std::expected<void, AuthError> login(const std::stop_token& stop) {
auto saved = platform->load_refresh();
if (!saved)
return std::unexpected{saved.error()};
if (!saved->empty()) {
tokens.refresh = std::move(*saved);
if (const auto refreshed = renew(stop); refreshed)
return {};
if (stop.stop_requested())
return std::unexpected{AuthError::cancelled};
}
auto authorization = platform->authorize(stop);
if (!authorization)
return std::unexpected{authorization.error()};
auto body = "grant_type=authorization_code&client_id=" + std::string{auth_client_id} +
"&redirect_uri=" + auth_form_escape(auth_redirect) +
"&code=" + auth_form_escape(authorization->code) +
"&code_verifier=" + auth_form_escape(authorization->verifier);
erase(authorization->code);
erase(authorization->verifier);
return exchange(std::move(body), stop);
}
std::expected<void, AuthError> fetch_grant(const std::stop_token& stop) {
if (std::chrono::steady_clock::now() + std::chrono::seconds{60} >= access_until) {
const auto refreshed = renew(stop);
if (!refreshed)
return refreshed;
}
auto response = platform->post(AuthEndpoint::grant, {}, tokens.access, stop);
if (!response)
return std::unexpected{response.error()};
auto received = auth_grant(*response, utc_seconds());
erase(response->body);
if (!received)
return std::unexpected{received.error()};
if (!account.empty() && account != received->account)
return std::unexpected{AuthError::invalid_response};
if (stop.stop_requested()) {
received->bytes.fill(0);
return std::unexpected{AuthError::cancelled};
}
account = received->account;
std::lock_guard lock{mutex};
grant = std::move(*received);
return {};
}
std::expected<void, AuthError> logout(const std::stop_token& stop) {
bool complete = true;
if (tokens.refresh.empty()) {
auto saved = platform->load_refresh();
if (saved)
tokens.refresh = std::move(*saved);
else
complete = false;
}
if (std::chrono::steady_clock::now() >= access_until && !tokens.refresh.empty())
if (!renew(stop))
complete = false;
if (!tokens.access.empty()) {
const auto response = platform->post(AuthEndpoint::logout, {}, tokens.access, stop);
complete = response && response->status >= 200 && response->status < 300 && complete;
} else
complete = false;
if (!tokens.refresh.empty()) {
auto body = "client_id=" + std::string{auth_client_id} +
"&token_type_hint=refresh_token&token=" + auth_form_escape(tokens.refresh);
const auto response = platform->post(AuthEndpoint::revoke, body, {}, stop);
erase(body);
complete = response && response->status >= 200 && response->status < 300 && complete;
}
const bool cleared = platform->erase_refresh();
erase(tokens.access);
erase(tokens.refresh);
account.clear();
if (!cleared)
return std::unexpected{AuthError::credential_store};
return complete ? std::expected<void, AuthError>{}
: std::unexpected{AuthError::logout_incomplete};
}
bool start(Job job) {
{
std::lock_guard lock{mutex};
if (!platform || state.busy || (job == Job::grant && !state.signed_in))
return false;
state.busy = true;
state.error.reset();
state.phase = job == Job::login ? AuthPhase::signing_in
: job == Job::logout ? AuthPhase::signing_out
: AuthPhase::renewing;
if (grant)
grant->bytes.fill(0);
grant.reset();
}
if (worker.joinable())
worker.join();
worker = std::jthread{[this, job](const std::stop_token& stop) {
auto result = std::expected<void, AuthError>{};
if (job == Job::logout)
result = logout(stop);
else {
if (job == Job::login) {
account.clear();
result = login(stop);
}
if (result && !stop.stop_requested())
result = fetch_grant(stop);
}
std::lock_guard lock{mutex};
if (stop.stop_requested()) {
if (grant)
grant->bytes.fill(0);
grant.reset();
result = std::unexpected{AuthError::cancelled};
}
state.busy = false;
state.signed_in = !tokens.refresh.empty();
state.phase = result ? (state.signed_in ? AuthPhase::ready : AuthPhase::signed_out)
: AuthPhase::failed;
if (!result)
state.error = result.error();
}};
return true;
}
};
AuthClient::AuthClient(std::unique_ptr<AuthPlatform> platform)
: impl_{std::make_unique<Impl>(std::move(platform))} {}
AuthClient::~AuthClient() = default;
bool AuthClient::sign_in() {
return impl_->start(Impl::Job::login);
}
bool AuthClient::request_grant() {
return impl_->start(Impl::Job::grant);
}
bool AuthClient::sign_out() {
return impl_->start(Impl::Job::logout);
}
void AuthClient::cancel() {
impl_->worker.request_stop();
}
AuthStatus AuthClient::status() const {
std::lock_guard lock{impl_->mutex};
return impl_->state;
}
std::optional<AuthGrant> AuthClient::take_grant() {
std::lock_guard lock{impl_->mutex};
return std::exchange(impl_->grant, {});
}
#ifndef _WIN32
std::unique_ptr<AuthPlatform> native_auth_platform() {
return {};
}
#endif
} // namespace evo::client
+256
View File
@@ -0,0 +1,256 @@
#include "evo/client/auth.hpp"
#include "evo/serialization/json.hpp"
#include <algorithm>
#include <array>
#include <vector>
namespace evo::client {
namespace {
using serialization::JsonValue;
constexpr std::string_view issuer = "https://auth.aeternalisgames.com/realms/aeternalis";
std::optional<std::string_view> string_member(const JsonValue& value, std::string_view name) {
const auto* member = value.member(name);
return member ? member->string() : std::nullopt;
}
std::optional<std::uint64_t> number_member(const JsonValue& value, std::string_view name) {
const auto* member = value.member(name);
return member ? member->integer() : std::nullopt;
}
AuthError reply_error(const AuthHttpReply& reply) {
if (reply.status == 429)
return AuthError::throttled;
if (reply.status >= 500)
return AuthError::service_unavailable;
const auto json = JsonValue::parse(reply.body);
if (json) {
const auto error = string_member(*json, "error").value_or("");
if (error == "email_not_verified")
return AuthError::email_unverified;
if (error == "invalid_grant" || error == "token_expired" || reply.status == 401)
return AuthError::token_expired;
}
return AuthError::denied;
}
int hex(char ch) {
if (ch >= '0' && ch <= '9')
return ch - '0';
if (ch >= 'a' && ch <= 'f')
return ch - 'a' + 10;
if (ch >= 'A' && ch <= 'F')
return ch - 'A' + 10;
return -1;
}
std::optional<std::string> unescape(std::string_view text) {
std::string out;
for (std::size_t i = 0; i < text.size(); ++i) {
unsigned char ch = static_cast<unsigned char>(text[i]);
if (ch == '%') {
if (i + 2 >= text.size() || hex(text[i + 1]) < 0 || hex(text[i + 2]) < 0)
return {};
ch = static_cast<unsigned char>(hex(text[i + 1]) * 16 + hex(text[i + 2]));
i += 2;
} else if (ch == '+')
ch = ' ';
if (ch < 0x20 || ch == 0x7f)
return {};
out.push_back(static_cast<char>(ch));
}
return out;
}
std::uint64_t grant_field(const GrantRecord& bytes, std::size_t offset) {
std::uint64_t value = 0;
for (std::size_t i = 0; i < 8; ++i)
value |= static_cast<std::uint64_t>(bytes[offset + i]) << (i * 8);
return value;
}
bool token_text(std::string_view text) {
return !text.empty() && text.size() <= 4096 &&
std::ranges::all_of(text, [](unsigned char ch) { return ch > 0x20 && ch < 0x7f; });
}
} // namespace
std::string_view auth_error_text(AuthError error) {
switch (error) {
case AuthError::unavailable:
return "Browser sign-in is available in the Windows network client.";
case AuthError::cancelled:
return "Sign-in cancelled.";
case AuthError::listener:
return "The sign-in return port (47600) is in use. Close the other sign-in attempt and "
"retry.";
case AuthError::timeout:
return "Sign-in timed out. Please try again.";
case AuthError::browser:
return "The system browser could not be opened.";
case AuthError::transport:
return "The secure login service could not be reached. Please retry.";
case AuthError::invalid_response:
return "The login service returned an invalid response.";
case AuthError::denied:
return "Sign-in was refused. Check your account and try again.";
case AuthError::token_expired:
return "Your login expired or could not be renewed. Sign in again.";
case AuthError::email_unverified:
return "Verify your email in Keycloak, then try again.";
case AuthError::throttled:
return "Please wait a few seconds before requesting another connection.";
case AuthError::service_unavailable:
return "The grant service is temporarily unavailable.";
case AuthError::credential_store:
return "Windows Credential Manager could not save or clear your login.";
case AuthError::logout_incomplete:
return "Signed out locally. Server revocation could not be confirmed; issued grants may "
"remain valid until expiry.";
}
return "Sign-in failed.";
}
std::string auth_form_escape(std::string_view value) {
constexpr std::string_view digits = "0123456789ABCDEF";
std::string out;
for (const char raw : value) {
const auto ch = static_cast<unsigned char>(raw);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') ||
ch == '-' || ch == '_' || ch == '.' || ch == '~')
out.push_back(static_cast<char>(ch));
else {
out.push_back('%');
out.push_back(digits[ch >> 4U]);
out.push_back(digits[ch & 15U]);
}
}
return out;
}
std::string auth_base64url(std::span<const std::uint8_t> bytes) {
constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
std::string out;
std::uint32_t value = 0;
unsigned bits = 0;
for (const auto byte : bytes) {
value = (value << 8U) | byte;
bits += 8;
while (bits >= 6) {
bits -= 6;
out.push_back(alphabet[(value >> bits) & 63U]);
}
}
if (bits != 0)
out.push_back(alphabet[(value << (6U - bits)) & 63U]);
return out;
}
std::string auth_authorization_url(std::string_view state, std::string_view challenge) {
return std::string{issuer} +
"/protocol/openid-connect/auth?client_id=" + std::string{auth_client_id} +
"&response_type=code&scope=openid%20email%20profile" +
"&redirect_uri=" + auth_form_escape(auth_redirect) + "&code_challenge_method=S256" +
"&code_challenge=" + auth_form_escape(challenge) + "&state=" + auth_form_escape(state) +
"&prompt=select_account";
}
std::expected<std::string, AuthError> auth_callback(std::string_view target,
std::string_view state) {
if (!target.starts_with("/callback?") || target.size() > 8192 || state.empty())
return std::unexpected{AuthError::invalid_response};
target.remove_prefix(10);
std::vector<std::pair<std::string, std::string>> fields;
while (!target.empty()) {
const auto end = target.find('&');
const auto field = target.substr(0, end);
const auto equal = field.find('=');
if (equal == std::string_view::npos || fields.size() >= 8)
return std::unexpected{AuthError::invalid_response};
auto key = unescape(field.substr(0, equal)), value = unescape(field.substr(equal + 1));
if (!key || !value ||
std::ranges::any_of(fields, [&](const auto& old) { return old.first == *key; }))
return std::unexpected{AuthError::invalid_response};
fields.emplace_back(std::move(*key), std::move(*value));
if (end == std::string_view::npos)
break;
target.remove_prefix(end + 1);
}
const auto get = [&](std::string_view name) -> std::string_view {
for (const auto& field : fields)
if (field.first == name)
return field.second;
return {};
};
if (get("state") != state || (!get("iss").empty() && get("iss") != issuer))
return std::unexpected{AuthError::invalid_response};
if (!get("error").empty())
return std::unexpected{AuthError::denied};
if (!token_text(get("code")))
return std::unexpected{AuthError::invalid_response};
return std::string{get("code")};
}
std::expected<AuthTokens, AuthError> auth_tokens(const AuthHttpReply& reply) {
if (reply.status != 200)
return std::unexpected{reply_error(reply)};
const auto json = JsonValue::parse(reply.body);
if (!json)
return std::unexpected{AuthError::invalid_response};
const auto access = string_member(*json, "access_token").value_or("");
const auto refresh = string_member(*json, "refresh_token").value_or("");
const auto type = string_member(*json, "token_type").value_or("");
const auto lifetime = number_member(*json, "expires_in").value_or(0);
if (!token_text(access) || !token_text(refresh) || (type != "Bearer" && type != "bearer") ||
lifetime < 1 || lifetime > 3600)
return std::unexpected{AuthError::invalid_response};
return AuthTokens{std::string{access}, std::string{refresh}, lifetime};
}
std::expected<AuthGrant, AuthError> auth_grant(const AuthHttpReply& reply,
std::uint64_t now_seconds) {
if (reply.status != 200)
return std::unexpected{reply_error(reply)};
const auto json = JsonValue::parse(reply.body);
if (!json)
return std::unexpected{AuthError::invalid_response};
AuthGrant result;
result.account = string_member(*json, "account").value_or("");
result.endpoint = string_member(*json, "endpoint").value_or("");
result.server_name = string_member(*json, "server_name").value_or("");
result.region = number_member(*json, "region").value_or(0);
result.expires_at = number_member(*json, "expires_at").value_or(0);
const auto encoded = string_member(*json, "grant").value_or("");
if (encoded.size() != 216 || !encoded.ends_with("==") || !parse_endpoint(result.endpoint) ||
result.server_name.empty() || !parse_endpoint(result.server_name + ":1") ||
result.server_name.find_first_of(":[]") != std::string::npos || result.region == 0 ||
result.expires_at <= now_seconds || result.expires_at - now_seconds > 900 ||
result.account.size() != 36)
return std::unexpected{AuthError::invalid_response};
constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::uint32_t value = 0;
unsigned bits = 0;
std::size_t at = 0;
for (const auto ch : encoded.substr(0, 214)) {
const auto digit = alphabet.find(ch);
if (digit == std::string_view::npos)
return std::unexpected{AuthError::invalid_response};
value = (value << 6U) | static_cast<std::uint32_t>(digit);
bits += 6;
if (bits >= 8) {
bits -= 8;
result.bytes.at(at++) = static_cast<std::uint8_t>(value >> bits);
}
}
if (at != 160 || (value & 15U) != 0)
return std::unexpected{AuthError::invalid_response};
constexpr std::array<std::uint8_t, 16> marker{'E', 'V', 'O', '-', 'G', 'R', 'A', 'N', 'T'};
if (!std::equal(marker.begin(), marker.end(), result.bytes.begin()) || result.bytes[16] != 1 ||
result.bytes[17] != 0 || result.bytes[18] != 1 || result.bytes[19] != 0 ||
grant_field(result.bytes, 72) != result.region ||
grant_field(result.bytes, 88) != result.expires_at || grant_field(result.bytes, 48) == 0)
return std::unexpected{AuthError::invalid_response};
at = 32;
for (std::size_t i = 0; i < result.account.size();) {
if (i == 8 || i == 13 || i == 18 || i == 23) {
if (result.account[i++] != '-')
return std::unexpected{AuthError::invalid_response};
continue;
}
if (hex(result.account[i]) < 0 || hex(result.account[i + 1]) < 0 ||
result.bytes[at++] != hex(result.account[i]) * 16 + hex(result.account[i + 1]))
return std::unexpected{AuthError::invalid_response};
i += 2;
}
return result; // The region verifies signature/scope; JSON cannot override grant claims.
}
} // namespace evo::client
+264
View File
@@ -0,0 +1,264 @@
#include "evo/client/auth.hpp"
// Order matters: winsock2.h before windows.h, and windows.h before the other SDK headers.
#include <winsock2.h>
#include <windows.h>
#include <bcrypt.h>
#include <shellapi.h>
#include <wincred.h>
#include <winhttp.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <limits>
namespace evo::client {
namespace {
constexpr wchar_t credential_name[] = L"AeternalisEvolution/DEV/refresh-token/v1";
struct InternetHandle {
HINTERNET value{};
~InternetHandle() {
if (value)
WinHttpCloseHandle(value);
}
};
struct Socket {
SOCKET value{INVALID_SOCKET};
~Socket() {
if (value != INVALID_SOCKET)
closesocket(value);
}
};
struct Winsock {
bool ready{};
Winsock() {
WSADATA data{};
ready = WSAStartup(MAKEWORD(2, 2), &data) == 0;
}
~Winsock() {
if (ready)
WSACleanup();
}
};
struct Algorithm {
BCRYPT_ALG_HANDLE value{};
~Algorithm() {
if (value)
BCryptCloseAlgorithmProvider(value, 0);
}
};
std::wstring wide(std::string_view value) {
return {value.begin(), value.end()};
}
bool readable(SOCKET socket, long microseconds) {
fd_set read{};
FD_ZERO(&read);
FD_SET(socket, &read);
timeval timeout{0, microseconds};
return select(0, &read, nullptr, nullptr, &timeout) > 0;
}
class WindowsAuth final : public AuthPlatform {
public:
std::expected<AuthorizationCode, AuthError> authorize(std::stop_token stop) override {
Winsock winsock;
if (!winsock.ready)
return std::unexpected{AuthError::listener};
Socket listener{socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)};
if (listener.value == INVALID_SOCKET)
return std::unexpected{AuthError::listener};
const BOOL exclusive = TRUE;
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
address.sin_port = htons(47600);
if (setsockopt(listener.value, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
reinterpret_cast<const char*>(&exclusive), sizeof(exclusive)) != 0 ||
bind(listener.value, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0 ||
listen(listener.value, 4) != 0)
return std::unexpected{AuthError::listener};
std::array<std::uint8_t, 64> secret{};
std::array<std::uint8_t, 32> random_state{}, digest{};
if (BCryptGenRandom(nullptr, secret.data(), static_cast<ULONG>(secret.size()),
BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0 ||
BCryptGenRandom(nullptr, random_state.data(), static_cast<ULONG>(random_state.size()),
BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0)
return std::unexpected{AuthError::unavailable};
auto verifier = auth_base64url(secret);
SecureZeroMemory(secret.data(), secret.size());
const auto state = auth_base64url(random_state);
Algorithm sha;
if (BCryptOpenAlgorithmProvider(&sha.value, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0 ||
BCryptHash(sha.value, nullptr, 0, reinterpret_cast<PUCHAR>(verifier.data()),
static_cast<ULONG>(verifier.size()), digest.data(),
static_cast<ULONG>(digest.size())) < 0)
return std::unexpected{AuthError::unavailable};
const auto url = wide(auth_authorization_url(state, auth_base64url(digest)));
if (reinterpret_cast<INT_PTR>(ShellExecuteW(nullptr, L"open", url.c_str(), nullptr, nullptr,
SW_SHOWNORMAL)) <= 32)
return std::unexpected{AuthError::browser};
const auto deadline = std::chrono::steady_clock::now() + std::chrono::minutes{5};
while (!stop.stop_requested() && std::chrono::steady_clock::now() < deadline) {
if (!readable(listener.value, 100000))
continue;
Socket connection{accept(listener.value, nullptr, nullptr)};
if (connection.value == INVALID_SOCKET)
continue;
const DWORD timeout = 1000;
static_cast<void>(setsockopt(connection.value, SOL_SOCKET, SO_SNDTIMEO,
reinterpret_cast<const char*>(&timeout), sizeof(timeout)));
std::string request;
const auto read_until = std::chrono::steady_clock::now() + std::chrono::seconds{2};
while (!stop.stop_requested() && request.size() < 8192 &&
std::chrono::steady_clock::now() < read_until &&
request.find("\r\n\r\n") == std::string::npos) {
if (!readable(connection.value, 100000))
continue;
std::array<char, 1024> buffer{};
const auto count =
recv(connection.value, buffer.data(), static_cast<int>(buffer.size()), 0);
if (count <= 0)
break;
request.append(buffer.data(), static_cast<std::size_t>(count));
}
const auto line_end = request.find("\r\n");
const auto end = request.find(" HTTP/1.1\r\n");
auto headers = line_end == std::string::npos ? std::string{} : request.substr(line_end);
std::ranges::transform(headers, headers.begin(), [](unsigned char ch) {
return static_cast<char>(std::tolower(ch));
});
auto code =
std::expected<std::string, AuthError>{std::unexpected{AuthError::invalid_response}};
if (request.size() <= 8192 && request.find("\r\n\r\n") != std::string::npos &&
request.starts_with("GET ") && end != std::string::npos &&
headers.find("\r\nhost: 127.0.0.1:47600\r\n") != std::string::npos)
code = auth_callback(std::string_view{request}.substr(4, end - 4), state);
const bool finished = code || code.error() == AuthError::denied;
const std::string response =
std::string{finished ? "HTTP/1.1 200 OK\r\n" : "HTTP/1.1 400 Bad Request\r\n"} +
"Content-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n"
"Content-Security-Policy: default-src 'none'; frame-ancestors 'none'\r\n"
"Referrer-Policy: no-referrer\r\nConnection: close\r\n\r\n" +
(code ? "Login response received. Return to Aeternalis Evolution to continue."
: "Login response not accepted. Return to Aeternalis Evolution.");
static_cast<void>(
send(connection.value, response.data(), static_cast<int>(response.size()), 0));
SecureZeroMemory(request.data(), request.size());
if (code)
return AuthorizationCode{std::move(*code), std::move(verifier)};
if (finished)
return std::unexpected{AuthError::denied};
}
return std::unexpected{stop.stop_requested() ? AuthError::cancelled : AuthError::timeout};
}
std::expected<AuthHttpReply, AuthError> post(AuthEndpoint endpoint, std::string_view body,
std::string_view bearer,
std::stop_token stop) override {
if (stop.stop_requested())
return std::unexpected{AuthError::cancelled};
if (body.size() > 16384 || bearer.size() > 4096 ||
bearer.find_first_of("\r\n") != std::string_view::npos)
return std::unexpected{AuthError::invalid_response};
const bool broker = endpoint == AuthEndpoint::grant || endpoint == AuthEndpoint::logout;
const wchar_t* host = broker ? L"grants.aeternalisgames.com" : L"auth.aeternalisgames.com";
const wchar_t* path = endpoint == AuthEndpoint::grant ? L"/grant"
: endpoint == AuthEndpoint::logout ? L"/logout"
: endpoint == AuthEndpoint::token
? L"/realms/aeternalis/protocol/openid-connect/token"
: L"/realms/aeternalis/protocol/openid-connect/revoke";
InternetHandle session{WinHttpOpen(L"AeternalisEvolution/1",
WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)};
if (!session.value || !WinHttpSetTimeouts(session.value, 5000, 5000, 5000, 5000))
return std::unexpected{AuthError::transport};
InternetHandle connection{
WinHttpConnect(session.value, host, INTERNET_DEFAULT_HTTPS_PORT, 0)};
if (!connection.value)
return std::unexpected{AuthError::transport};
InternetHandle request{WinHttpOpenRequest(connection.value, L"POST", path, nullptr,
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE)};
if (!request.value)
return std::unexpected{AuthError::transport};
DWORD disable = WINHTTP_DISABLE_REDIRECTS | WINHTTP_DISABLE_COOKIES;
DWORD logon = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
if (!WinHttpSetOption(request.value, WINHTTP_OPTION_DISABLE_FEATURE, &disable,
sizeof(disable)) ||
!WinHttpSetOption(request.value, WINHTTP_OPTION_AUTOLOGON_POLICY, &logon,
sizeof(logon)))
return std::unexpected{AuthError::transport};
auto headers = std::wstring{
L"Content-Type: application/x-www-form-urlencoded\r\nAccept: application/json\r\n"};
if (!bearer.empty())
headers += L"Authorization: Bearer " + wide(bearer) + L"\r\n";
const bool sent =
WinHttpSendRequest(
request.value, headers.c_str(), static_cast<DWORD>(headers.size()),
body.empty() ? WINHTTP_NO_REQUEST_DATA : const_cast<char*>(body.data()),
static_cast<DWORD>(body.size()), static_cast<DWORD>(body.size()), 0) != 0;
SecureZeroMemory(headers.data(), headers.size() * sizeof(wchar_t));
if (!sent || stop.stop_requested() || !WinHttpReceiveResponse(request.value, nullptr))
return std::unexpected{stop.stop_requested() ? AuthError::cancelled
: AuthError::transport};
DWORD status = 0, size = sizeof(status);
if (!WinHttpQueryHeaders(
request.value, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX))
return std::unexpected{AuthError::invalid_response};
AuthHttpReply reply{status, {}};
while (!stop.stop_requested()) {
std::array<char, 4096> buffer{};
DWORD count = 0;
if (!WinHttpReadData(request.value, buffer.data(), static_cast<DWORD>(buffer.size()),
&count))
return std::unexpected{AuthError::transport};
if (count == 0)
return reply;
if (reply.body.size() + count > 16384)
return std::unexpected{AuthError::invalid_response};
reply.body.append(buffer.data(), count);
}
return std::unexpected{AuthError::cancelled};
}
std::expected<std::string, AuthError> load_refresh() override {
PCREDENTIALW credential = nullptr;
if (!CredReadW(credential_name, CRED_TYPE_GENERIC, 0, &credential)) {
if (GetLastError() == ERROR_NOT_FOUND)
return std::string{};
return std::unexpected{AuthError::credential_store};
}
std::string token;
if (credential->CredentialBlobSize <= 4096 && credential->CredentialBlob)
token.assign(reinterpret_cast<const char*>(credential->CredentialBlob),
credential->CredentialBlobSize);
SecureZeroMemory(credential->CredentialBlob, credential->CredentialBlobSize);
CredFree(credential);
if (token.empty() ||
!std::ranges::all_of(token, [](unsigned char ch) { return ch > 0x20 && ch < 0x7f; }))
return std::unexpected{AuthError::credential_store};
return token;
}
bool save_refresh(std::string_view token) override {
if (token.empty() || token.size() > CRED_MAX_CREDENTIAL_BLOB_SIZE)
return false;
CREDENTIALW credential{};
credential.Type = CRED_TYPE_GENERIC;
credential.TargetName = const_cast<wchar_t*>(credential_name);
credential.UserName = const_cast<wchar_t*>(L"aevolution-game");
credential.CredentialBlobSize = static_cast<DWORD>(token.size());
credential.CredentialBlob = reinterpret_cast<LPBYTE>(const_cast<char*>(token.data()));
credential.Persist = CRED_PERSIST_LOCAL_MACHINE;
return CredWriteW(&credential, 0) != 0;
}
bool erase_refresh() override {
return CredDeleteW(credential_name, CRED_TYPE_GENERIC, 0) != 0 ||
GetLastError() == ERROR_NOT_FOUND;
}
};
} // namespace
std::unique_ptr<AuthPlatform> native_auth_platform() {
return std::make_unique<WindowsAuth>();
}
} // namespace evo::client
+20 -5
View File
@@ -91,7 +91,8 @@ std::expected<Endpoint, LaunchError> parse_endpoint(std::string_view text) {
return Endpoint{host, static_cast<std::uint16_t>(port)};
}
std::expected<ConnectMaterial, LaunchError> load_connect(const ConnectForm& form) {
std::expected<ConnectMaterial, LaunchError> load_connect(const ConnectForm& form,
std::span<const GrantRecord> grants) {
const auto endpoint = parse_endpoint(form.endpoint);
if (!endpoint)
return std::unexpected(endpoint.error());
@@ -99,8 +100,6 @@ std::expected<ConnectMaterial, LaunchError> load_connect(const ConnectForm& form
return std::unexpected(LaunchError::server_name);
if (!plain_text(form.authority_path))
return std::unexpected(LaunchError::authority_path);
if (!plain_text(form.grants_path))
return std::unexpected(LaunchError::grants_path);
const auto authority =
read_bounded(form.authority_path, max_authority_bytes, LaunchError::authority_unreadable,
LaunchError::authority_invalid);
@@ -110,17 +109,33 @@ std::expected<ConnectMaterial, LaunchError> load_connect(const ConnectForm& form
if (pem.find("-----BEGIN CERTIFICATE-----") == std::string::npos ||
pem.find('\0') != std::string::npos)
return std::unexpected(LaunchError::authority_invalid);
if (grants.empty() || grants.size() > max_grant_records)
return std::unexpected(LaunchError::grants_invalid);
return ConnectMaterial{*endpoint,
form.server_name,
std::move(pem),
form.authority_path,
{grants.begin(), grants.end()}};
}
std::expected<ConnectMaterial, LaunchError> load_connect(const ConnectForm& form) {
// Validate the endpoint/CA first, preserving the manual launcher's error order.
const std::array<GrantRecord, 1> placeholder{};
auto material = load_connect(form, placeholder);
if (!material)
return material;
if (!plain_text(form.grants_path))
return std::unexpected(LaunchError::grants_path);
const auto bundle = read_bounded(form.grants_path, grant_record_bytes * max_grant_records,
LaunchError::grants_unreadable, LaunchError::grants_invalid);
if (!bundle)
return std::unexpected(bundle.error());
if (bundle->size() % grant_record_bytes != 0)
return std::unexpected(LaunchError::grants_invalid);
ConnectMaterial material{*endpoint, form.server_name, std::move(pem), form.authority_path, {}};
material->grants.clear();
for (std::size_t at = 0; at < bundle->size(); at += grant_record_bytes) {
GrantRecord grant{};
std::copy_n(bundle->begin() + static_cast<std::ptrdiff_t>(at), grant.size(), grant.begin());
material.grants.push_back(grant);
material->grants.push_back(grant);
}
return material;
}
@@ -1,9 +1,9 @@
#include "evo/server/broker/json.hpp"
#include "evo/serialization/json.hpp"
#include <charconv>
#include <limits>
namespace evo::server::broker {
namespace evo::serialization {
namespace {
void append_utf8(std::string& out, std::uint32_t code) {
if (code < 0x80) {
@@ -298,4 +298,4 @@ const JsonValue* JsonValue::member(std::string_view name) const {
const std::vector<JsonValue>* JsonValue::array() const {
return kind_ == Kind::array ? &items_ : nullptr;
}
} // namespace evo::server::broker
} // namespace evo::serialization
+380
View File
@@ -0,0 +1,380 @@
// ADR-0131 client sign-in: the loopback callback, token and grant replies, and the
// AuthClient worker against a scripted platform (no browser, network or credential store).
#include "evo/client/auth.hpp"
#include <chrono>
#include <cstdio>
#include <deque>
#include <map>
#include <mutex>
#include <source_location>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace {
using namespace evo::client;
using namespace std::chrono_literals;
void check(bool ok, std::source_location at = std::source_location::current()) {
if (!ok)
throw std::runtime_error("client auth line " + std::to_string(at.line()));
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
constexpr std::uint64_t now_s = 1'800'000'000;
constexpr std::string_view account_text = "11111111-2222-3333-4444-555555555555";
std::string base64(std::span<const std::uint8_t> bytes) {
constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
std::size_t i = 0;
for (; i + 3 <= bytes.size(); i += 3) {
const auto v =
(std::uint32_t{bytes[i]} << 16U) | (std::uint32_t{bytes[i + 1]} << 8U) | bytes[i + 2];
for (int s = 18; s >= 0; s -= 6)
out.push_back(alphabet[(v >> static_cast<unsigned>(s)) & 63U]);
}
if (bytes.size() - i == 1) {
const auto v = std::uint32_t{bytes[i]} << 16U;
out += {alphabet[(v >> 18U) & 63U], alphabet[(v >> 12U) & 63U], '=', '='};
} else if (bytes.size() - i == 2) {
const auto v = (std::uint32_t{bytes[i]} << 16U) | (std::uint32_t{bytes[i + 1]} << 8U);
out += {alphabet[(v >> 18U) & 63U], alphabet[(v >> 12U) & 63U], alphabet[(v >> 6U) & 63U],
'='};
}
return out;
}
void put(GrantRecord& g, std::size_t at, std::uint64_t value) {
for (std::size_t i = 0; i < 8; ++i)
g[at + i] = static_cast<std::uint8_t>(value >> (8 * i));
}
// The grant layout of schemas/network/session-grant-v1.md; the signature is not checked
// by the client (the region verifies it).
GrantRecord grant_bytes(std::uint64_t serial, std::uint64_t region, std::uint64_t expires) {
GrantRecord g{};
const std::string_view marker = "EVO-GRANT";
std::copy(marker.begin(), marker.end(), g.begin());
g[16] = 1; // Version 1, little-endian.
g[18] = 1; // Dev.
g[20] = 1; // Key id 1.
put(g, 24, 0xABCDEF); // Grant id.
const std::array<std::uint8_t, 16> account{0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x33, 0x33,
0x44, 0x44, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55};
std::copy(account.begin(), account.end(), g.begin() + 32);
put(g, 48, serial);
put(g, 56, 100);
put(g, 64, 9);
put(g, 72, region);
put(g, 80, now_s);
put(g, 88, expires);
return g;
}
std::string grant_json(const GrantRecord& g, std::uint64_t region, std::uint64_t expires,
std::string_view account = account_text) {
return R"({"grant":")" + base64(g) + R"(","account":")" + std::string(account) +
R"(","region":)" + std::to_string(region) +
R"(,"endpoint":"void.example.test:7400","server_name":"void.example.test","expires_at":)" +
std::to_string(expires) + "}\n";
}
std::string token_json(std::string_view access, std::string_view refresh,
std::uint64_t lifetime = 300) {
return R"({"access_token":")" + std::string(access) + R"(","expires_in":)" +
std::to_string(lifetime) + R"(,"refresh_expires_in":1800,"refresh_token":")" +
std::string(refresh) + R"(","token_type":"Bearer","scope":"openid email profile"})";
}
void protocol_tests() {
CHECK(auth_form_escape("a b/~-_.Z9") == "a%20b%2F~-_.Z9");
CHECK(auth_base64url(std::array<std::uint8_t, 2>{0xFB, 0xFF}) == "-_8");
CHECK(auth_base64url(std::array<std::uint8_t, 3>{1, 2, 3}) == "AQID");
const auto url = auth_authorization_url("st", "ch");
CHECK(url.starts_with(
"https://auth.aeternalisgames.com/realms/aeternalis/protocol/openid-connect/auth?"));
for (const std::string_view part :
{"client_id=aevolution-game", "response_type=code", "code_challenge_method=S256",
"code_challenge=ch", "state=st",
"redirect_uri=http%3A%2F%2F127.0.0.1%3A47600%2Fcallback"})
CHECK(url.find(part) != std::string::npos);
// Callback: exact path, the one state, one code; denial and anything else refused.
CHECK(auth_callback("/callback?state=st&code=abc.DEF-1&session_state=x", "st") == "abc.DEF-1");
CHECK(auth_callback("/callback?code=c&state=st&iss=https%3A%2F%2Fauth.aeternalisgames.com%2F"
"realms%2Faeternalis",
"st") == "c");
const auto refused = [](std::string_view target, AuthError expected) {
const auto code = auth_callback(target, "st");
return !code && code.error() == expected;
};
CHECK(refused("/callback?state=st&error=access_denied", AuthError::denied));
CHECK(refused("/callback?state=other&code=c", AuthError::invalid_response));
CHECK(refused("/callback?state=st&state=st&code=c", AuthError::invalid_response));
CHECK(refused("/callback?state=st&code=c&iss=https%3A%2F%2Fevil.example",
AuthError::invalid_response));
CHECK(refused("/other?state=st&code=c", AuthError::invalid_response));
CHECK(refused("/callback?state=st&code=a%0Ab", AuthError::invalid_response));
CHECK(refused("/callback?state=st&code=a%2", AuthError::invalid_response));
CHECK(refused("/callback?state=st", AuthError::invalid_response));
CHECK(!auth_callback("/callback?state=&code=c", ""));
// Token replies.
const auto tokens = auth_tokens({200, token_json("acc", "ref")});
CHECK(tokens && tokens->access == "acc" && tokens->refresh == "ref" && tokens->lifetime == 300);
const auto token_error = [](const AuthHttpReply& reply, AuthError expected) {
const auto result = auth_tokens(reply);
return !result && result.error() == expected;
};
CHECK(token_error({400, R"({"error":"invalid_grant"})"}, AuthError::token_expired));
CHECK(token_error({429, ""}, AuthError::throttled));
CHECK(token_error({503, ""}, AuthError::service_unavailable));
CHECK(token_error({400, R"({"error":"unauthorized_client"})"}, AuthError::denied));
CHECK(token_error({200, token_json("acc", "")}, AuthError::invalid_response));
CHECK(token_error({200, token_json("a c", "ref")}, AuthError::invalid_response));
CHECK(token_error({200, token_json("acc", "ref", 0)}, AuthError::invalid_response));
CHECK(token_error({200, "not json"}, AuthError::invalid_response));
// Grant replies: the JSON must agree with the grant's own claims.
const auto g = grant_bytes(7, 4, now_s + 600);
const auto grant = auth_grant({200, grant_json(g, 4, now_s + 600)}, now_s);
CHECK(grant && grant->bytes == g && grant->region == 4 && grant->expires_at == now_s + 600 &&
grant->account == account_text && grant->endpoint == "void.example.test:7400" &&
grant->server_name == "void.example.test");
const auto grant_error = [](const AuthHttpReply& reply, AuthError expected) {
const auto result = auth_grant(reply, now_s);
return !result && result.error() == expected;
};
CHECK(grant_error({200, grant_json(g, 5, now_s + 600)}, AuthError::invalid_response));
CHECK(grant_error({200, grant_json(g, 4, now_s + 601)}, AuthError::invalid_response));
CHECK(grant_error({200, grant_json(g, 4, now_s + 600, "11111111-2222-3333-4444-555555555556")},
AuthError::invalid_response));
const auto expired = grant_bytes(7, 4, now_s);
CHECK(grant_error({200, grant_json(expired, 4, now_s)}, AuthError::invalid_response));
const auto too_long = grant_bytes(7, 4, now_s + 901);
CHECK(grant_error({200, grant_json(too_long, 4, now_s + 901)}, AuthError::invalid_response));
auto stage = g;
stage[18] = 2;
CHECK(grant_error({200, grant_json(stage, 4, now_s + 600)}, AuthError::invalid_response));
auto unserialed = grant_bytes(0, 4, now_s + 600);
CHECK(grant_error({200, grant_json(unserialed, 4, now_s + 600)}, AuthError::invalid_response));
auto truncated = grant_json(g, 4, now_s + 600);
truncated.erase(truncated.find("==\""), 2);
CHECK(grant_error({200, truncated}, AuthError::invalid_response));
CHECK(grant_error({401, R"({"error":"email_not_verified"})"}, AuthError::email_unverified));
CHECK(grant_error({401, R"({"error":"token_expired"})"}, AuthError::token_expired));
CHECK(grant_error({429, R"({"error":"too_many_requests"})"}, AuthError::throttled));
CHECK(grant_error({503, R"({"error":"unavailable"})"}, AuthError::service_unavailable));
for (int e = 0; e <= static_cast<int>(AuthError::logout_incomplete); ++e)
CHECK(!auth_error_text(static_cast<AuthError>(e)).empty());
}
// A scripted platform: replies are queued per endpoint and every request is recorded.
struct Script {
std::mutex mutex;
std::map<AuthEndpoint, std::deque<AuthHttpReply>> replies;
std::vector<std::pair<AuthEndpoint, std::string>> sent; // Body or bearer.
std::string stored;
bool save_fails{}, block_authorize{};
int authorizations{};
};
class FakePlatform final : public AuthPlatform {
public:
explicit FakePlatform(Script& script) : s_{script} {}
std::expected<AuthorizationCode, AuthError> authorize(std::stop_token stop) override {
{
std::lock_guard lock{s_.mutex};
++s_.authorizations;
}
while (s_.block_authorize && !stop.stop_requested())
std::this_thread::sleep_for(5ms);
if (stop.stop_requested())
return std::unexpected{AuthError::cancelled};
return AuthorizationCode{"the-code", "the-verifier"};
}
std::expected<AuthHttpReply, AuthError> post(AuthEndpoint endpoint, std::string_view body,
std::string_view bearer,
std::stop_token) override {
std::lock_guard lock{s_.mutex};
s_.sent.emplace_back(endpoint, bearer.empty() ? std::string(body) : std::string(bearer));
auto& queue = s_.replies[endpoint];
if (queue.empty())
return std::unexpected{AuthError::transport};
auto reply = queue.front();
queue.pop_front();
return reply;
}
std::expected<std::string, AuthError> load_refresh() override {
std::lock_guard lock{s_.mutex};
return s_.stored;
}
bool save_refresh(std::string_view token) override {
std::lock_guard lock{s_.mutex};
if (s_.save_fails)
return false;
s_.stored = token;
return true;
}
bool erase_refresh() override {
std::lock_guard lock{s_.mutex};
s_.stored.clear();
return true;
}
private:
Script& s_;
};
AuthStatus settle(const AuthClient& client) {
for (int i = 0; i < 1000; ++i) {
const auto status = client.status();
if (!status.busy)
return status;
std::this_thread::sleep_for(5ms);
}
throw std::runtime_error("client auth worker did not settle");
}
std::uint64_t utc_now() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
AuthHttpReply live_grant(std::uint64_t serial) {
const auto expires = utc_now() + 600;
return {200, grant_json(grant_bytes(serial, 4, expires), 4, expires)};
}
void client_tests() {
{
AuthClient unsupported{nullptr};
CHECK(!unsupported.status().supported && !unsupported.sign_in());
}
{
// First login: browser code with PKCE, tokens saved, then a grant.
Script s;
s.replies[AuthEndpoint::token].push_back({200, token_json("access-1", "refresh-1")});
s.replies[AuthEndpoint::grant].push_back(live_grant(1));
AuthClient client{std::make_unique<FakePlatform>(s)};
CHECK(client.status().supported && !client.request_grant()); // Not signed in.
CHECK(client.sign_in());
CHECK(!client.sign_in()); // One job at a time.
auto status = settle(client);
CHECK(status.phase == AuthPhase::ready && status.signed_in && !status.error);
CHECK(s.authorizations == 1 && s.stored == "refresh-1");
CHECK(s.sent.size() == 2 && s.sent[0].first == AuthEndpoint::token &&
s.sent[0].second.find("grant_type=authorization_code") != std::string::npos &&
s.sent[0].second.find("code=the-code") != std::string::npos &&
s.sent[0].second.find("code_verifier=the-verifier") != std::string::npos);
CHECK(s.sent[1] == std::pair{AuthEndpoint::grant, std::string{"access-1"}});
const auto grant = client.take_grant();
CHECK(grant && grant->account == account_text && !client.take_grant());
// Next grant reuses the access token; a different account is refused.
s.replies[AuthEndpoint::grant].push_back(live_grant(2));
CHECK(client.request_grant());
CHECK(settle(client).phase == AuthPhase::ready && client.take_grant());
auto other = live_grant(3);
other.body.replace(other.body.find(account_text), account_text.size(),
"99999999-2222-3333-4444-555555555555");
s.replies[AuthEndpoint::grant].push_back(other);
CHECK(client.request_grant());
status = settle(client);
CHECK(status.phase == AuthPhase::failed && status.error == AuthError::invalid_response &&
!client.take_grant());
// Logout: broker revocation with the access token, then the refresh token revoked.
s.replies[AuthEndpoint::logout].push_back({200, R"({"revoked":true})"});
s.replies[AuthEndpoint::revoke].push_back({200, ""});
CHECK(client.sign_out());
status = settle(client);
CHECK(status.phase == AuthPhase::signed_out && !status.signed_in && !status.error);
CHECK(s.stored.empty());
CHECK(s.sent[s.sent.size() - 2] ==
std::pair{AuthEndpoint::logout, std::string{"access-1"}});
CHECK(s.sent.back().first == AuthEndpoint::revoke &&
s.sent.back().second.find("token=refresh-1") != std::string::npos);
}
{
// A saved login rotates its refresh token without the browser.
Script s;
s.stored = "saved";
s.replies[AuthEndpoint::token].push_back({200, token_json("access-2", "rotated")});
s.replies[AuthEndpoint::grant].push_back(live_grant(1));
AuthClient client{std::make_unique<FakePlatform>(s)};
CHECK(client.sign_in());
CHECK(settle(client).signed_in && s.authorizations == 0 && s.stored == "rotated");
CHECK(s.sent[0].second.find("grant_type=refresh_token") != std::string::npos &&
s.sent[0].second.find("refresh_token=saved") != std::string::npos);
}
{
// A revoked saved login falls back to the browser.
Script s;
s.stored = "revoked";
s.replies[AuthEndpoint::token].push_back({400, R"({"error":"invalid_grant"})"});
s.replies[AuthEndpoint::token].push_back({200, token_json("access-3", "fresh")});
s.replies[AuthEndpoint::grant].push_back(live_grant(1));
AuthClient client{std::make_unique<FakePlatform>(s)};
CHECK(client.sign_in());
CHECK(settle(client).signed_in && s.authorizations == 1 && s.stored == "fresh");
}
{
// Logout that the broker cannot confirm still signs out locally, and says so.
Script s;
s.replies[AuthEndpoint::token].push_back({200, token_json("a", "r")});
s.replies[AuthEndpoint::grant].push_back(live_grant(1));
AuthClient client{std::make_unique<FakePlatform>(s)};
CHECK(client.sign_in() && settle(client).signed_in);
s.replies[AuthEndpoint::revoke].push_back({200, ""}); // No logout reply: transport.
CHECK(client.sign_out());
const auto status = settle(client);
CHECK(!status.signed_in && status.error == AuthError::logout_incomplete &&
s.stored.empty());
}
{
// Unverified email: signed in, but no grant.
Script s;
s.replies[AuthEndpoint::token].push_back({200, token_json("a", "r")});
s.replies[AuthEndpoint::grant].push_back({401, R"({"error":"email_not_verified"})"});
AuthClient client{std::make_unique<FakePlatform>(s)};
CHECK(client.sign_in());
const auto status = settle(client);
CHECK(status.phase == AuthPhase::failed && status.error == AuthError::email_unverified &&
status.signed_in && !client.take_grant());
}
{
// The credential store refusing the new refresh token fails the sign-in.
Script s;
s.save_fails = true;
s.replies[AuthEndpoint::token].push_back({200, token_json("a", "r")});
AuthClient client{std::make_unique<FakePlatform>(s)};
CHECK(client.sign_in());
const auto status = settle(client);
CHECK(status.error == AuthError::credential_store && !status.signed_in);
}
{
// Cancel while the browser is open; destruction while waiting also joins.
Script s;
s.block_authorize = true;
AuthClient client{std::make_unique<FakePlatform>(s)};
CHECK(client.sign_in());
std::this_thread::sleep_for(20ms);
CHECK(client.status().busy && client.status().phase == AuthPhase::signing_in);
client.cancel();
const auto status = settle(client);
CHECK(status.phase == AuthPhase::failed && status.error == AuthError::cancelled &&
!status.signed_in);
AuthClient abandoned{std::make_unique<FakePlatform>(s)};
CHECK(abandoned.sign_in());
}
}
} // namespace
int main() {
try {
protocol_tests();
client_tests();
std::puts("client auth passed");
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
return 1;
}
}