Files
aevolution/tests/client_auth.cpp
T
dingoandClaude Opus 5.5 2a5c0d0e22
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
ADR-0131: Keycloak sign-in in the Windows engineering client
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>
2026-10-15 15:31:33 -04:00

381 lines
18 KiB
C++

// 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;
}
}