#include "evo/server/admin/admin_api.hpp" #include #include #include #include #include #include #include namespace evo::server::admin { namespace { using broker::TokenError; OpsResponse json(int status, std::string body) { return {status, std::move(body), "application/json"}; } OpsResponse error(int status, std::string_view code) { return json(status, "{\"error\":\"" + std::string(code) + "\"}\n"); } const char* token_error(TokenError e) { switch (e) { case TokenError::expired: return "token_expired"; case TokenError::missing_role: return "not_an_admin"; case TokenError::wrong_audience: case TokenError::wrong_party: case TokenError::wrong_issuer: case TokenError::wrong_type: return "token_not_for_this_service"; default: return "invalid_token"; } } bool is_uuid(std::string_view text) { if (text.size() != 36) return false; for (std::size_t i = 0; i < text.size(); ++i) { const char ch = text[i]; if (i == 8 || i == 13 || i == 18 || i == 23 ? ch != '-' : !((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f'))) return false; } return true; } std::optional number(std::string_view text) { std::uint64_t value{}; const auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), value); if (text.empty() || ec != std::errc{} || end != text.data() + text.size()) return std::nullopt; return value; } // Columns as JSON values: absent is null. Identities and ticks go out as strings (they may // exceed 2^53); counts and wall seconds as numbers. std::string text_value(const std::optional& value) { return value ? json_string(*value) : "null"; } std::string count_value(const std::optional& value) { return value && number(*value) ? *value : "null"; } std::string seconds_value(const std::optional& value) { // Wall seconds before 1970 do not occur; a negative or absent value is null. return value && number(*value) ? *value : "null"; } std::string bool_value(const std::optional& value) { return value == "t" ? "true" : value == "f" ? "false" : "null"; } const std::optional& at(const std::vector>& row, std::size_t index) { static const std::optional none; return index < row.size() ? row[index] : none; } std::string account_json(const std::vector>& row) { // 0 account, 1 created, 2 issuer, 3 subject, 4 control region, 5 control expires, // 6 logged in, 7 lives, 8 deaths, 9 active life, 10 active region, 11 mutation choices. const auto lives = number(at(row, 7).value_or("0")).value_or(0); const bool alive = at(row, 9).has_value(); const char* status = alive ? "alive" : lives > 0 ? "dead" : "no_life"; return "{\"account\":" + text_value(at(row, 0)) + ",\"created_at\":" + seconds_value(at(row, 1)) + ",\"issuer\":" + text_value(at(row, 2)) + ",\"subject\":" + text_value(at(row, 3)) + ",\"control_region\":" + text_value(at(row, 4)) + ",\"control_expires\":" + seconds_value(at(row, 5)) + ",\"logged_in\":" + (at(row, 6) == "t" ? "true" : "false") + ",\"status\":\"" + status + "\",\"lives\":" + std::to_string(lives) + ",\"deaths\":" + count_value(at(row, 8)) + ",\"resets\":" + std::to_string(lives > 0 ? lives - 1 : 0) + ",\"active_life\":" + text_value(at(row, 9)) + ",\"active_region\":" + text_value(at(row, 10)) + ",\"mutation_choices\":" + count_value(at(row, 11)) + "}"; } const std::string accounts_sql = "SELECT account_id::text, floor(extract(epoch FROM created_at))::bigint, issuer, subject, " "control_region, floor(extract(epoch FROM control_expires))::bigint, " "control_expires > clock_timestamp(), lives, deaths, active_life, active_region, " "mutation_choices FROM evolution.admin_accounts_v1($1)"; struct Socket { int fd{-1}; Socket(const Socket&) = delete; Socket& operator=(const Socket&) = delete; explicit Socket(int value) : fd{value} {} ~Socket() { if (fd >= 0) ::close(fd); } }; // Waits for `events` on the socket until the deadline. bool wait(int fd, short events, std::chrono::steady_clock::time_point deadline) { for (;;) { const auto left = std::chrono::duration_cast( deadline - std::chrono::steady_clock::now()); if (left.count() <= 0) return false; pollfd entry{fd, events, 0}; const int ready = ::poll(&entry, 1, static_cast(left.count())); if (ready > 0) return true; if (ready < 0 && errno != EINTR) return false; } } } // namespace std::string json_string(std::string_view text) { constexpr std::string_view digits = "0123456789abcdef"; std::string out = "\""; for (const char ch : text) { const auto byte = static_cast(ch); if (ch == '"' || ch == '\\') { out.push_back('\\'); out.push_back(ch); } else if (byte < 0x20 || byte == 0x7F) { out += "\\u00"; out.push_back(digits[byte >> 4U]); out.push_back(digits[byte & 0x0FU]); } else { out.push_back(ch); } } return out + "\""; } std::optional http_get(std::string_view address, std::string_view path, std::chrono::milliseconds timeout, std::size_t limit) { const auto colon = address.rfind(':'); if (colon == std::string_view::npos || colon == 0 || colon + 1 >= address.size() || path.empty() || path.front() != '/') return std::nullopt; auto host = std::string(address.substr(0, colon)); const auto port = std::string(address.substr(colon + 1)); if (host.size() >= 2 && host.front() == '[' && host.back() == ']') host = host.substr(1, host.size() - 2); const auto deadline = std::chrono::steady_clock::now() + timeout; addrinfo hints{}; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; addrinfo* found = nullptr; if (::getaddrinfo(host.c_str(), port.c_str(), &hints, &found) != 0 || found == nullptr) return std::nullopt; const std::unique_ptr results{found, ::freeaddrinfo}; for (const addrinfo* candidate = found; candidate != nullptr; candidate = candidate->ai_next) { Socket socket{::socket(candidate->ai_family, candidate->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, candidate->ai_protocol)}; if (socket.fd < 0) continue; if (::connect(socket.fd, candidate->ai_addr, candidate->ai_addrlen) != 0) { int failure = 0; socklen_t length = sizeof failure; if (errno != EINPROGRESS || !wait(socket.fd, POLLOUT, deadline) || ::getsockopt(socket.fd, SOL_SOCKET, SO_ERROR, &failure, &length) != 0 || failure != 0) continue; } const std::string request = "GET " + std::string(path) + " HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n"; std::size_t sent = 0; while (sent < request.size()) { if (!wait(socket.fd, POLLOUT, deadline)) return std::nullopt; const auto n = ::send(socket.fd, request.data() + sent, request.size() - sent, MSG_NOSIGNAL); if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) return std::nullopt; if (n > 0) sent += static_cast(n); } constexpr std::size_t header_room = 4096; std::string answer; for (;;) { if (!wait(socket.fd, POLLIN, deadline)) return std::nullopt; char chunk[16384]; const auto n = ::recv(socket.fd, chunk, sizeof chunk, 0); if (n == 0) break; if (n < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue; return std::nullopt; } answer.append(chunk, static_cast(n)); if (answer.size() > limit + header_room) return std::nullopt; } const auto end = answer.find("\r\n\r\n"); if (end == std::string::npos || answer.rfind("HTTP/1.1 200 ", 0) != 0) return std::nullopt; auto body = answer.substr(end + 4); if (body.size() > limit) return std::nullopt; return body; } return std::nullopt; } AdminApi::AdminApi(AdminConfig config, broker::TokenVerifier verifier, AdminConnect connect, AdminRegionView view, std::vector assets) : config_{std::move(config)}, verifier_{std::move(verifier)}, connect_{std::move(connect)}, view_{std::move(view)}, assets_{std::move(assets)} {} OpsResponse AdminApi::handle(const ApiRequest& request, std::uint64_t now_seconds, std::chrono::steady_clock::time_point now) { auto path = request.path.substr(0, request.path.find('?')); if (request.method != "GET") return {405, "method not allowed\n"}; if (path == "/healthz") return {200, "ok\n"}; if (path == "/config.json") return json(200, config_.portal_config_json); if (!path.starts_with("/api/")) { if (path == "/") path = "/index.html"; const auto asset = std::ranges::find(assets_, path, &AdminAsset::path); if (asset == assets_.end()) return {404, "not found\n"}; OpsResponse response{200, asset->body, asset->content_type}; response.headers = "Content-Security-Policy: " + config_.content_security_policy + "\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer" "\r\nX-Frame-Options: DENY\r\n"; return response; } auto authorization = request.authorization; constexpr std::string_view scheme = "bearer "; if (authorization.size() <= scheme.size() || !std::ranges::equal(authorization.substr(0, scheme.size()), scheme, [](char a, char b) { return (a | 0x20) == b; })) return error(401, "missing_token"); authorization.remove_prefix(scheme.size()); const auto claims = verifier_.verify(authorization, now_seconds); if (!claims) return error(claims.error() == TokenError::missing_role ? 403 : 401, token_error(claims.error())); return api(path, *claims, now); } OpsResponse AdminApi::api(std::string_view path, const broker::AccessTokenClaims& admin, std::chrono::steady_clock::time_point now) { if (path == "/api/me") return json(200, "{\"subject\":" + json_string(admin.subject) + ",\"email\":" + json_string(admin.email) + ",\"world\":" + std::to_string(config_.world) + "}\n"); if (path == "/api/accounts") return accounts(std::nullopt); constexpr std::string_view account_prefix = "/api/accounts/"; if (path.starts_with(account_prefix)) { const auto id = path.substr(account_prefix.size()); return is_uuid(id) ? accounts(id) : error(404, "not_found"); } if (path == "/api/regions") return regions(); constexpr std::string_view region_prefix = "/api/regions/"; constexpr std::string_view view_suffix = "/view"; if (path.starts_with(region_prefix) && path.ends_with(view_suffix)) { const auto region = number(path.substr( region_prefix.size(), path.size() - region_prefix.size() - view_suffix.size())); return region ? view(*region, now) : error(404, "not_found"); } return error(404, "not_found"); } std::optional AdminApi::query(const std::string& sql, std::vector parameters) { if (!db_ && connect_) db_ = connect_(); if (!db_) return std::nullopt; auto rows = db_->query(sql, parameters, config_.db_timeout); if (!rows) { db_.reset(); return std::nullopt; } return std::move(*rows); } OpsResponse AdminApi::accounts(std::optional account) { const auto world = std::to_string(config_.world); if (!account) { const auto rows = query(accounts_sql, {world}); if (!rows) return error(503, "unavailable"); std::string out = "{\"world\":" + world + ",\"accounts\":["; for (std::size_t i = 0; i < rows->size(); ++i) out += (i == 0 ? "" : ",") + account_json((*rows)[i]); return json(200, out + "]}\n"); } const auto rows = query(accounts_sql + " WHERE account_id = $2::uuid", {world, std::string(*account)}); if (!rows) return error(503, "unavailable"); if (rows->empty()) return error(404, "not_found"); const auto lives = query("SELECT request_id, identity, region_id, rejection, born, ended_tick, " "floor(extract(epoch FROM ended_at))::bigint " "FROM evolution.admin_account_lives_v1($1, $2::uuid)", {world, std::string(*account)}); if (!lives) return error(503, "unavailable"); std::string out = "{\"world\":" + world + ",\"account\":" + account_json(rows->front()) + ",\"lives\":["; for (std::size_t i = 0; i < lives->size(); ++i) { const auto& row = (*lives)[i]; out += std::string(i == 0 ? "" : ",") + "{\"request\":" + text_value(at(row, 0)) + ",\"identity\":" + text_value(at(row, 1)) + ",\"region\":" + text_value(at(row, 2)) + ",\"rejection\":" + count_value(at(row, 3)) + ",\"born\":" + text_value(at(row, 4)) + ",\"ended_tick\":" + text_value(at(row, 5)) + ",\"ended_at\":" + seconds_value(at(row, 6)) + "}"; } return json(200, out + "]}\n"); } OpsResponse AdminApi::regions() { const auto world = std::to_string(config_.world); const auto rows = query("SELECT region_id, frame_id, lease_epoch, lease_held, " "floor(extract(epoch FROM lease_expires))::bigint, commit_sequence, " "end_tick, floor(extract(epoch FROM committed_at))::bigint, " "build_identity FROM evolution.admin_regions_v1($1)", {world}); if (!rows) return error(503, "unavailable"); std::string out = "{\"world\":" + world + ",\"regions\":["; for (std::size_t i = 0; i < rows->size(); ++i) { const auto& row = (*rows)[i]; const auto region = number(at(row, 0).value_or("")); const bool viewable = region && std::ranges::contains(config_.view_regions, *region); out += std::string(i == 0 ? "" : ",") + "{\"region\":" + text_value(at(row, 0)) + ",\"frame\":" + text_value(at(row, 1)) + ",\"lease_epoch\":" + text_value(at(row, 2)) + ",\"lease_held\":" + bool_value(at(row, 3)) + ",\"lease_expires\":" + seconds_value(at(row, 4)) + ",\"sequence\":" + text_value(at(row, 5)) + ",\"tick\":" + text_value(at(row, 6)) + ",\"committed_at\":" + seconds_value(at(row, 7)) + ",\"build\":" + text_value(at(row, 8)) + ",\"viewable\":" + (viewable ? "true" : "false") + "}"; } return json(200, out + "]}\n"); } OpsResponse AdminApi::view(std::uint64_t region, std::chrono::steady_clock::time_point now) { if (!std::ranges::contains(config_.view_regions, region)) return error(404, "not_viewable"); const auto cached = views_.find(region); if (cached != views_.end() && now - cached->second.at < config_.view_cache) return json(200, cached->second.body); auto body = view_ ? view_(region) : std::nullopt; if (!body) return error(503, "region_unavailable"); views_[region] = {now, *body}; return json(200, std::move(*body)); } } // namespace evo::server::admin