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
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:
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user