diff --git a/CMakeLists.txt b/CMakeLists.txt index 0fcaaa8..f0876ef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -103,7 +103,7 @@ add_library(evo_lifecycle STATIC src/server/lifecycle/primitive_lives.cpp src/server/lifecycle/cellular_schedule.cpp src/server/lifecycle/cellular_population_batch.cpp src/server/lifecycle/cellular_environment.cpp src/server/lifecycle/cellular_environment_batch.cpp src/server/lifecycle/cellular_light.cpp src/server/lifecycle/cellular_liquid.cpp - src/server/lifecycle/cellular_revamp.cpp) + src/server/lifecycle/cellular_revamp.cpp src/server/lifecycle/cellular_admin_view.cpp) add_library(evo::lifecycle ALIAS evo_lifecycle) target_link_libraries(evo_lifecycle PUBLIC evo::biology evo::world) evo_owned_target(evo_lifecycle) @@ -311,6 +311,13 @@ if(EVO_BUILD_POSTGRES) add_executable(evo-grant-broker apps/evo-grant-broker/main.cpp) target_link_libraries(evo-grant-broker PRIVATE evo_grant_broker) evo_owned_target(evo-grant-broker) + # ADR-0182 read-only admin API and portal host (schema v61). + add_library(evo_admin_api STATIC src/server/admin/admin_api.cpp) + target_link_libraries(evo_admin_api PUBLIC evo_grant_broker) + evo_owned_target(evo_admin_api) + add_executable(evo-admin-api apps/evo-admin-api/main.cpp) + target_link_libraries(evo-admin-api PRIVATE evo_admin_api) + evo_owned_target(evo-admin-api) endif() # M7.9 clone and history audit tool (ADR-0067). add_executable(evo-world-clone apps/evo-world-clone/main.cpp) @@ -337,7 +344,7 @@ if(EVO_BUILD_POSTGRES) target_sources(evo-postgres-tests PRIVATE tests/region_session_tests.cpp tests/grant_broker_tests.cpp) target_link_libraries(evo-postgres-tests PRIVATE evo_network_session evo_control_ledger_postgres - evo_grant_broker OpenSSL::Crypto) + evo_grant_broker evo_admin_api OpenSSL::Crypto) target_compile_definitions(evo-postgres-tests PRIVATE EVO_POSTGRES_SESSIONS=1) endif() if(EVO_BUILD_QUIC) @@ -787,6 +794,11 @@ if(BUILD_TESTING) evo_owned_target(evo-cellular-revamp-owner-tests) add_test(NAME cellular-revamp-owner-contracts COMMAND evo-cellular-revamp-owner-tests) set_tests_properties(cellular-revamp-owner-contracts PROPERTIES TIMEOUT 300) + add_executable(evo-cellular-admin-view-tests tests/cellular_admin_view_tests.cpp) + target_include_directories(evo-cellular-admin-view-tests PRIVATE tests) + target_link_libraries(evo-cellular-admin-view-tests PRIVATE evo::lifecycle) + evo_owned_target(evo-cellular-admin-view-tests) + add_test(NAME cellular-admin-view-contracts COMMAND evo-cellular-admin-view-tests) add_executable(evo-photosynthesis-tests tests/photosynthesis_tests.cpp) target_link_libraries(evo-photosynthesis-tests PRIVATE evo::lifecycle) evo_owned_target(evo-photosynthesis-tests) diff --git a/apps/evo-admin-api/main.cpp b/apps/evo-admin-api/main.cpp new file mode 100644 index 0000000..0ec808e --- /dev/null +++ b/apps/evo-admin-api/main.cpp @@ -0,0 +1,201 @@ +// ADR-0182 read-only admin API and portal host for one world (DEV). +// +// evo-admin-api --listen ADDRESS:PORT --world N --jwks JSON --oidc-issuer URL +// --audience NAME --client NAME --role NAME --assets DIR +// --pg-passfile F --pg-service F [--region REGION=HOST:PORT ...] +// +// --assets holds the portal's index.html, app.js and style.css. Each --region names a +// region's operations address, whose /admin/view the portal may show. No token is printed. +#include "evo/persistence/postgres.hpp" +#include "evo/server/admin/admin_api.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo; +using namespace std::chrono_literals; + +volatile std::sig_atomic_t stop_requested = 0; +void on_stop(int) { + stop_requested = 1; +} + +struct Options { + std::string listen, jwks, oidc_issuer, audience, client, role, assets; + std::uint64_t world{}; + std::map regions; // Region to its operations address. + persistence::PgOptions pg; +}; + +std::optional number(std::string_view text) { + std::uint64_t value{}; + const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value); + if (error != std::errc{} || end != text.data() + text.size()) + return std::nullopt; + return value; +} + +std::optional parse(int argc, char** argv) { + Options o; + std::string pg_service, pg_passfile; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string_view flag = argv[i]; + const std::string_view value = argv[i + 1]; + const auto n = number(value); + if (flag == "--listen") + o.listen = value; + else if (flag == "--world" && n && *n > 0) + o.world = *n; + else if (flag == "--jwks") + o.jwks = value; + else if (flag == "--oidc-issuer") + o.oidc_issuer = value; + else if (flag == "--audience") + o.audience = value; + else if (flag == "--client") + o.client = value; + else if (flag == "--role") + o.role = value; + else if (flag == "--assets") + o.assets = value; + else if (flag == "--pg-service") + pg_service = value; + else if (flag == "--pg-passfile") + pg_passfile = value; + else if (flag == "--region") { + const auto equals = value.find('='); + const auto region = + equals == std::string_view::npos ? std::nullopt : number(value.substr(0, equals)); + const auto address = + equals == std::string_view::npos ? std::string_view{} : value.substr(equals + 1); + if (!region || *region == 0 || address.empty() || address.size() > 128 || + !o.regions.emplace(*region, std::string(address)).second) + return std::nullopt; + } else + return std::nullopt; + } + // Names are embedded in the portal's JSON settings: printable ASCII without quotes. + const auto plain = [](std::string_view text) { + return !text.empty() && text.size() <= 256 && std::ranges::all_of(text, [](char ch) { + return ch > ' ' && ch <= '~' && ch != '"' && ch != '\\'; + }); + }; + if (argc % 2 != 1 || o.listen.empty() || o.world == 0 || o.jwks.empty() || + !plain(o.oidc_issuer) || !o.oidc_issuer.starts_with("https://") || !plain(o.audience) || + !plain(o.client) || !plain(o.role) || o.assets.empty() || pg_service.empty() || + pg_passfile.empty()) + return std::nullopt; + auto service = persistence::read_pg_service(pg_service, "evolution"); + if (!service) + return std::nullopt; + o.pg = *service; + o.pg.password_file = pg_passfile; + return o; +} + +std::optional read_file(const std::string& path) { + std::ifstream file{path, std::ios::binary}; + if (!file) + return std::nullopt; + std::string body{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; + if (body.empty() || body.size() > (std::size_t{1} << 20U)) + return std::nullopt; + return body; +} + +std::uint64_t wall_seconds() { + return static_cast(std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count()); +} +} // namespace + +int main(int argc, char** argv) { + const auto options = parse(argc, argv); + if (!options) { + std::fputs("usage: evo-admin-api (see apps/evo-admin-api/main.cpp)\n", stderr); + return 2; + } + std::signal(SIGTERM, on_stop); + std::signal(SIGINT, on_stop); + std::signal(SIGPIPE, SIG_IGN); + + auto verifier = server::broker::TokenVerifier::from_jwks( + options->jwks, + {options->oidc_issuer, options->audience, options->client, 30, options->role}); + if (!verifier) { + std::puts("error jwks"); + return 2; + } + std::vector assets; + for (const auto& [name, type] : {std::pair{"index.html", "text/html; charset=utf-8"}, + std::pair{"app.js", "text/javascript; charset=utf-8"}, + std::pair{"style.css", "text/css; charset=utf-8"}}) { + auto body = read_file(options->assets + "/" + name); + if (!body) { + std::printf("error assets %s\n", name); + return 2; + } + assets.push_back({std::string("/") + name, type, std::move(*body)}); + } + // The realm's origin: sign-in redirects there and the portal exchanges tokens with it. + const auto origin_end = options->oidc_issuer.find('/', std::string_view{"https://"}.size()); + const auto origin = options->oidc_issuer.substr(0, origin_end); + server::admin::AdminConfig config; + config.world = options->world; + for (const auto& [region, address] : options->regions) + config.view_regions.push_back(region); + config.portal_config_json = "{\"issuer\":\"" + options->oidc_issuer + "\",\"client_id\":\"" + + options->client + "\",\"world\":" + std::to_string(options->world) + + "}\n"; + config.content_security_policy = + "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; " + "connect-src 'self' " + + origin + "; form-action 'self' " + origin + "; frame-ancestors 'none'; base-uri 'none'"; + + auto listening = server::OpsServer::listen(options->listen, + server::OpsServer::max_configurable_response_bytes); + if (!listening) { + std::puts("error listen"); + return 2; + } + const auto pg = options->pg; + const auto regions = options->regions; + server::admin::AdminApi api{std::move(config), std::move(*verifier), + [pg]() -> std::unique_ptr { + auto db = persistence::Postgres::connect(pg, 3s); + return db ? std::move(*db) : nullptr; + }, + [regions](std::uint64_t region) -> std::optional { + const auto found = regions.find(region); + if (found == regions.end()) + return std::nullopt; + return server::admin::http_get( + found->second, "/admin/view", 1500ms, + server::OpsServer::max_configurable_response_bytes); + }, + std::move(assets)}; + std::printf("admin api listening %u world %llu\n", static_cast((*listening)->port()), + static_cast(options->world)); + std::fflush(stdout); + while (stop_requested == 0) { + (*listening)->serve_api([&](const server::ApiRequest& request) { + return api.handle(request, wall_seconds(), std::chrono::steady_clock::now()); + }); + std::this_thread::sleep_for(5ms); + } + std::puts("admin api stopped"); + return 0; +} diff --git a/apps/evo-admin-api/portal/app.js b/apps/evo-admin-api/portal/app.js new file mode 100644 index 0000000..3dec857 --- /dev/null +++ b/apps/evo-admin-api/portal/app.js @@ -0,0 +1,558 @@ +// ADR-0182 read-only admin portal. Keycloak sign-in (authorization code with PKCE), then the +// admin API on this origin. Tokens stay in this tab: the access token in memory, the refresh +// and ID tokens in sessionStorage so a reload keeps the session. No third-party code. + +const store = { + get: (k) => { try { return sessionStorage.getItem(k); } catch { return null; } }, + set: (k, v) => { try { sessionStorage.setItem(k, v); } catch { /* private mode */ } }, + drop: (...ks) => { try { ks.forEach((k) => sessionStorage.removeItem(k)); } catch { /* */ } }, +}; + +let config = null; +let access = null; // { token, expires (ms) } +let refreshing = null; // In-flight refresh promise. + +// ---------- DOM helpers (textContent only: nothing from the API is parsed as HTML) ---------- +function h(tag, attrs = {}, ...children) { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (v === null || v === undefined || v === false) continue; + if (k === 'class') el.className = v; + else if (k.startsWith('on')) el.addEventListener(k.slice(2), v); + else if (v === true) el.setAttribute(k, ''); + else el.setAttribute(k, String(v)); + } + for (const c of children.flat()) { + if (c === null || c === undefined || c === false) continue; + el.append(c instanceof Node ? c : document.createTextNode(String(c))); + } + return el; +} +const main = () => document.getElementById('main'); +function show(...nodes) { main().replaceChildren(...nodes); } + +// ---------- Formatting ---------- +const fmtInt = (n) => (n === null || n === undefined ? '—' : Number(n).toLocaleString()); +function fmtUnit(value, units) { + if (value === null || value === undefined) return '—'; + let v = Number(value), i = 0; + while (Math.abs(v) >= 1000 && i < units.length - 1) { v /= 1000; i++; } + return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(v >= 10 ? 1 : 2)} ${units[i]}`; +} +const fmtEnergy = (pj) => fmtUnit(pj, ['pJ', 'nJ', 'µJ', 'mJ', 'J']); +const fmtMass = (fg) => fmtUnit(fg, ['fg', 'pg', 'ng', 'µg', 'mg']); +const fmtLength = (um) => fmtUnit(um, ['µm', 'mm', 'm']); +function fmtTime(seconds) { + if (!seconds) return '—'; + return new Date(seconds * 1000).toLocaleString(); +} +function fmtAgo(seconds) { + if (!seconds) return '—'; + const d = Math.round(Date.now() / 1000 - seconds); + if (Math.abs(d) < 60) return d >= 0 ? `${d}s ago` : `in ${-d}s`; + const m = Math.round(d / 60); + if (Math.abs(m) < 60) return m >= 0 ? `${m}m ago` : `in ${-m}m`; + const hr = Math.round(m / 60); + if (Math.abs(hr) < 48) return hr >= 0 ? `${hr}h ago` : `in ${-hr}h`; + return `${Math.round(hr / 24)}d ago`; +} +const short = (id) => (id ? `${id.slice(0, 8)}…` : '—'); + +// ---------- Sign-in ---------- +function b64url(bytes) { + let s = ''; + bytes.forEach((b) => { s += String.fromCharCode(b); }); + return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} +function randomText(n) { + const a = new Uint8Array(n); + crypto.getRandomValues(a); + return b64url(a); +} +const endpoint = (name) => `${config.issuer}/protocol/openid-connect/${name}`; +const redirectUri = () => `${location.origin}/`; + +async function signIn() { + const verifier = randomText(48); + const state = randomText(16); + const challenge = b64url(new Uint8Array( + await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))); + store.set('pkce_verifier', verifier); + store.set('pkce_state', state); + store.set('return_to', location.hash || '#/accounts'); + const url = new URL(endpoint('auth')); + url.search = new URLSearchParams({ + client_id: config.client_id, redirect_uri: redirectUri(), response_type: 'code', + response_mode: 'query', scope: 'openid email', state, code_challenge: challenge, + code_challenge_method: 'S256', + }); + location.assign(url); +} + +async function tokenRequest(body) { + const res = await fetch(endpoint('token'), { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ client_id: config.client_id, ...body }), + }); + if (!res.ok) throw new Error(`token endpoint ${res.status}`); + const t = await res.json(); + access = { token: t.access_token, expires: Date.now() + (t.expires_in || 60) * 1000 }; + if (t.refresh_token) store.set('refresh_token', t.refresh_token); + if (t.id_token) store.set('id_token', t.id_token); + return access.token; +} + +async function finishSignIn() { + const params = new URLSearchParams(location.search); + const code = params.get('code'); + if (!code && !params.get('error')) return false; + const expected = store.get('pkce_state'); + const verifier = store.get('pkce_verifier'); + const returnTo = store.get('return_to') || '#/accounts'; + store.drop('pkce_state', 'pkce_verifier', 'return_to'); + history.replaceState(null, '', `/${returnTo}`); + if (params.get('error') || !expected || params.get('state') !== expected || !verifier) { + throw new Error(`sign-in was not completed (${params.get('error') || 'state mismatch'})`); + } + await tokenRequest({ grant_type: 'authorization_code', code, redirect_uri: redirectUri(), + code_verifier: verifier }); + return true; +} + +async function token() { + if (access && access.expires - Date.now() > 30000) return access.token; + const refresh = store.get('refresh_token'); + if (!refresh) return null; + refreshing = refreshing || tokenRequest({ grant_type: 'refresh_token', refresh_token: refresh }) + .catch(() => { store.drop('refresh_token'); access = null; return null; }) + .finally(() => { refreshing = null; }); + return refreshing; +} + +function signOut() { + const idToken = store.get('id_token'); + store.drop('refresh_token', 'id_token'); + access = null; + const url = new URL(endpoint('logout')); + url.search = new URLSearchParams({ + client_id: config.client_id, post_logout_redirect_uri: redirectUri(), + ...(idToken ? { id_token_hint: idToken } : {}), + }); + location.assign(url); +} + +class ApiError extends Error { + constructor(status, code) { super(code || `HTTP ${status}`); this.status = status; this.code = code; } +} +async function api(path, retry = true) { + const t = await token(); + if (!t) throw new ApiError(401, 'signed_out'); + const res = await fetch(path, { headers: { Authorization: `Bearer ${t}` }, cache: 'no-store' }); + if (res.status === 401 && retry) { access = null; return api(path, false); } + if (!res.ok) { + let code = null; + try { code = (await res.json()).error; } catch { /* plain text */ } + throw new ApiError(res.status, code); + } + return res.json(); +} + +// ---------- Sortable tables ---------- +function table(columns, rows, { onRow, sortKey, sortUp = false } = {}) { + let key = sortKey, up = sortUp; + const wrap = h('div', { class: 'table-wrap' }); + const draw = () => { + const col = columns.find((c) => c.key === key); + const sorted = col ? [...rows].sort((a, b) => { + const va = col.sort ? col.sort(a) : a[col.key]; + const vb = col.sort ? col.sort(b) : b[col.key]; + const r = va === vb ? 0 : va === null || va === undefined ? 1 : vb === null || vb === undefined ? -1 : va < vb ? -1 : 1; + return up ? r : -r; + }) : rows; + const head = h('tr', {}, columns.map((c) => h('th', { + class: [c.num ? 'num' : '', c.key === key ? `sorted${up ? ' up' : ''}` : ''].join(' ').trim() || null, + onclick: () => { if (key === c.key) up = !up; else { key = c.key; up = !c.num; } draw(); }, + }, c.label))); + const body = sorted.map((r) => h('tr', { class: onRow ? 'clickable' : null, onclick: onRow ? () => onRow(r) : null }, + columns.map((c) => h('td', { class: c.num ? 'num' : null }, c.render ? c.render(r) : (r[c.key] ?? '—'))))); + wrap.replaceChildren(h('table', {}, h('thead', {}, head), h('tbody', {}, body.length ? body + : h('tr', {}, h('td', { colspan: columns.length, class: 'muted' }, 'Nothing to show.'))))); + }; + draw(); + return wrap; +} + +function statusBadge(a) { + return h('span', { class: `badge ${a.status === 'alive' ? 'alive' : a.status === 'dead' ? 'dead' : ''}` }, + a.status === 'no_life' ? 'no life' : a.status); +} +function sessionBadge(a) { + return a.logged_in ? h('span', { class: 'badge online' }, `online · region ${a.control_region}`) + : h('span', { class: 'muted' }, 'offline'); +} + +// ---------- Pages ---------- +let stopPage = () => {}; + +async function accountsPage() { + const data = await api('/api/accounts'); + const search = h('input', { type: 'search', placeholder: 'Filter by account, subject or status' }); + const holder = h('div'); + const columns = [ + { key: 'account', label: 'Account', render: (a) => h('span', { class: 'mono', title: a.account }, short(a.account)) }, + { key: 'subject', label: 'Keycloak subject', render: (a) => h('span', { class: 'mono muted', title: a.subject || '' }, a.subject ? short(a.subject) : '—') }, + { key: 'status', label: 'Status', render: statusBadge }, + { key: 'logged_in', label: 'Session', render: sessionBadge, sort: (a) => (a.logged_in ? 1 : 0) }, + { key: 'active_region', label: 'Region', render: (a) => a.active_region ?? '—', sort: (a) => Number(a.active_region ?? -1) }, + { key: 'lives', label: 'Lives', num: true }, + { key: 'deaths', label: 'Deaths', num: true }, + { key: 'resets', label: 'Resets', num: true }, + { key: 'mutation_choices', label: 'Mutation choices', num: true }, + { key: 'created_at', label: 'Created', render: (a) => (a.created_at ? fmtAgo(a.created_at) : '—'), sort: (a) => a.created_at ?? 0 }, + ]; + const draw = () => { + const q = search.value.trim().toLowerCase(); + const rows = data.accounts.filter((a) => !q || [a.account, a.subject, a.status].some((v) => (v || '').toLowerCase().includes(q))); + holder.replaceChildren(table(columns, rows, { sortKey: 'created_at', onRow: (a) => { location.hash = `#/accounts/${a.account}`; } })); + }; + search.addEventListener('input', draw); + const n = data.accounts.length; + const online = data.accounts.filter((a) => a.logged_in).length; + const alive = data.accounts.filter((a) => a.status === 'alive').length; + show( + h('div', { class: 'head' }, h('div', {}, h('h1', {}, 'Accounts'), h('span', { class: 'muted' }, `World ${data.world}`)), + h('div', { class: 'tools' }, search, h('button', { onclick: () => route() }, 'Refresh'))), + h('div', { class: 'stats' }, + stat('Accounts', fmtInt(n)), stat('Online', fmtInt(online)), stat('Alive', fmtInt(alive)), + stat('Deaths', fmtInt(data.accounts.reduce((s, a) => s + (a.deaths || 0), 0)))), + holder); + draw(); +} + +function stat(label, value, sub) { + return h('div', { class: 'stat' }, h('div', { class: 'label' }, label), + h('div', { class: 'value' }, value, sub ? h('small', {}, ` ${sub}`) : null)); +} + +// persistence::LifeRefusal. +const rejections = ['accepted', 'refused: not enough funding', 'refused: no placement', 'cancelled', 'refused: already alive']; + +async function accountPage(id) { + const data = await api(`/api/accounts/${id}`); + const a = data.account; + const facts = h('dl', { class: 'facts' }, + h('dt', {}, 'Account'), h('dd', { class: 'mono' }, a.account), + h('dt', {}, 'Keycloak subject'), h('dd', { class: 'mono' }, a.subject || '—'), + h('dt', {}, 'Issuer'), h('dd', { class: 'mono' }, a.issuer || '—'), + h('dt', {}, 'Status'), h('dd', {}, statusBadge(a)), + h('dt', {}, 'Session'), h('dd', {}, sessionBadge(a), + a.control_expires ? h('span', { class: 'muted' }, ` control ${a.logged_in ? 'until' : 'ended'} ${fmtTime(a.control_expires)}`) : null), + h('dt', {}, 'Active life'), h('dd', { class: 'mono' }, a.active_life ?? '—', + a.active_region ? h('span', {}, ' ', h('a', { href: `#/regions/${a.active_region}?account=${a.account}` }, `show in region ${a.active_region}`)) : null), + h('dt', {}, 'Created'), h('dd', {}, fmtTime(a.created_at))); + const lives = table([ + { key: 'request', label: 'Request', sort: (l) => Number(l.request) }, + { key: 'identity', label: 'Life', render: (l) => h('span', { class: 'mono' }, l.identity) }, + { key: 'region', label: 'Region' }, + { key: 'rejection', label: 'Outcome', render: (l) => (l.rejection ? h('span', { class: 'badge warn' }, rejections[l.rejection] || `refused ${l.rejection}`) + : l.born === null ? h('span', { class: 'muted' }, 'reserved') : l.ended_tick ? h('span', { class: 'badge dead' }, 'died') : h('span', { class: 'badge alive' }, 'alive')) }, + { key: 'born', label: 'Born (tick)', num: true, sort: (l) => Number(l.born ?? -1) }, + { key: 'ended_tick', label: 'Ended (tick)', num: true, sort: (l) => Number(l.ended_tick ?? -1) }, + { key: 'ended_at', label: 'Ended', render: (l) => fmtTime(l.ended_at), sort: (l) => l.ended_at ?? 0 }, + ], data.lives, { sortKey: 'request' }); + show( + h('div', { class: 'head' }, h('div', {}, h('a', { href: '#/accounts' }, '← Accounts'), h('h1', {}, `Account ${short(a.account)}`))), + h('div', { class: 'stats' }, + stat('Lives', fmtInt(a.lives)), stat('Deaths', fmtInt(a.deaths)), stat('Resets', fmtInt(a.resets)), + stat('Mutation choices', fmtInt(a.mutation_choices))), + h('div', { class: 'card' }, facts), + h('h2', {}, 'Lives'), lives, + h('p', { class: 'muted' }, 'Time played, bans, current mutations and living offspring arrive with the next admin phase (ADR-0182).')); +} + +async function regionsPage() { + const data = await api('/api/regions'); + show( + h('div', { class: 'head' }, h('div', {}, h('h1', {}, 'Regions'), h('span', { class: 'muted' }, `World ${data.world}`)), + h('div', { class: 'tools' }, h('button', { onclick: () => route() }, 'Refresh'))), + table([ + { key: 'region', label: 'Region', sort: (r) => Number(r.region) }, + { key: 'frame', label: 'Frame' }, + { key: 'lease_held', label: 'Lease', render: (r) => (r.lease_held ? h('span', { class: 'badge alive' }, `held · epoch ${r.lease_epoch}`) : h('span', { class: 'muted' }, 'free')) }, + { key: 'lease_expires', label: 'Lease expires', render: (r) => fmtAgo(r.lease_expires) }, + { key: 'tick', label: 'Head tick', num: true, render: (r) => fmtInt(r.tick), sort: (r) => Number(r.tick ?? -1) }, + { key: 'sequence', label: 'Commits', num: true, render: (r) => fmtInt(r.sequence), sort: (r) => Number(r.sequence ?? -1) }, + { key: 'committed_at', label: 'Last commit', render: (r) => fmtAgo(r.committed_at), sort: (r) => r.committed_at ?? 0 }, + { key: 'build', label: 'Build', render: (r) => h('span', { class: 'mono', title: r.build || '' }, r.build ? r.build.slice(0, 12) : '—') }, + { key: 'viewable', label: '', render: (r) => (r.viewable ? h('a', { href: `#/regions/${r.region}` }, 'Open view →') : h('span', { class: 'muted' }, 'no view')) }, + ], data.regions, { sortKey: 'region' })); +} + +// ---------- Region view ---------- +const channelNames = ['energy', 'carbon', 'nitrogen', 'phosphorus', 'other']; +const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(`--${name}`).trim(); + +async function regionPage(region, params) { + const highlight = params.get('account') || ''; + const canvas = h('canvas'); + const tip = h('div', { class: 'tooltip', hidden: true }); + const note = h('div', { class: 'overlay-note' }, 'Scroll to zoom, drag to pan, double-click to reset.'); + const statsBox = h('div', { class: 'stats' }); + const detail = h('div', { class: 'card' }, h('span', { class: 'muted' }, 'Select a cell to see it here.')); + const status = h('span', { class: 'muted' }); + const show_ = { players: true, wildlife: true, pools: true, bubbles: true }; + const toggle = (k, label) => h('label', {}, h('input', { type: 'checkbox', checked: true, onchange: (e) => { show_[k] = e.target.checked; paint(); } }), label); + const live = h('input', { type: 'checkbox', checked: true }); + let view = null, selected = null, timer = null; + let zoom = 1, panX = 0, panY = 0, drag = null; + + show( + h('div', { class: 'head' }, h('div', {}, h('a', { href: '#/regions' }, '← Regions'), h('h1', {}, `Region ${region}`), status), + h('div', { class: 'tools' }, h('label', {}, live, ' Live (1 s)'), h('button', { onclick: () => load() }, 'Refresh'))), + statsBox, + h('div', { class: 'region-layout' }, + h('div', { class: 'canvas-wrap' }, canvas, tip, note), + h('div', { class: 'side' }, + detail, + h('div', { class: 'card' }, h('h2', {}, 'Show'), h('div', { class: 'toggles' }, + toggle('players', 'Player cells'), toggle('wildlife', 'Wildlife'), toggle('pools', 'Pools'), toggle('bubbles', 'Bubbles'))), + h('div', { class: 'card' }, h('h2', {}, 'Legend'), h('div', { class: 'legend' }, + h('span', { class: 'swatch player' }), 'Player cell', + h('span', { class: 'swatch online' }), 'Player cell, connected', + h('span', { class: 'swatch wildlife' }), 'Wildlife', + h('span', { class: 'swatch pool' }), 'Pool', + ...channelNames.flatMap((c) => [h('span', { class: `swatch ${c}` }), `Bubble, mostly ${c}`])))))); + + const cellObj = (c) => ({ + life: c[0], organism: c[1], account: c[2], x: c[3], y: c[4], extent: c[5], flags: c[6], members: c[7], + reserve: c.slice(8, 13), bodyMass: c[13], + }); + const depObj = (d) => ({ id: d[0], kind: d[1], x: d[2], y: d[3], r: d[4], stock: d.slice(5, 10) }); + + function geometry() { + const rect = canvas.getBoundingClientRect(); + const dpr = window.devicePixelRatio || 1; + const w = Math.max(1, Math.round(rect.width * dpr)), hgt = Math.max(1, Math.round(rect.height * dpr)); + if (canvas.width !== w || canvas.height !== hgt) { canvas.width = w; canvas.height = hgt; } + const [aw, ah] = view ? view.area : [1, 1]; + const base = Math.min(w / aw, hgt / ah); + const s = base * zoom; + const ox = (w - aw * s) / 2 + panX * dpr, oy = (hgt - ah * s) / 2 + panY * dpr; + // World y grows upward; the canvas grows downward. + return { dpr, s, toX: (x) => ox + x * s, toY: (y) => oy + (ah - y) * s, fromX: (px) => (px - ox) / s, fromY: (py) => ah - (py - oy) / s }; + } + + function paint() { + const ctx = canvas.getContext('2d'); + const g = geometry(); + ctx.clearRect(0, 0, canvas.width, canvas.height); + if (!view) return; + const [aw, ah] = view.area; + ctx.strokeStyle = css('line'); + ctx.lineWidth = g.dpr; + ctx.strokeRect(g.toX(0), g.toY(ah), aw * g.s, ah * g.s); + if (show_.pools) { + ctx.fillStyle = css('pool'); + ctx.strokeStyle = css('accent'); + for (const d of view.deps) if (d.kind !== 2) { + ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 2 * g.dpr), 0, Math.PI * 2); ctx.fill(); + } + } + if (show_.bubbles) { + const colors = channelNames.map(css); + for (const d of view.deps) if (d.kind === 2) { + // Energy counts in pJ, matter in fg; ~17 pJ per fg of food, so compare on that scale. + const weights = [d.stock[0] / 17, d.stock[1], d.stock[2], d.stock[3], d.stock[4]]; + const top = weights.indexOf(Math.max(...weights)); + ctx.fillStyle = colors[top]; + ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 1.5 * g.dpr), 0, Math.PI * 2); ctx.fill(); + } + } + for (const c of view.cells) { + const wild = (c.flags & 1) !== 0; + if ((wild && !show_.wildlife) || (!wild && !show_.players)) continue; + const online = (c.flags & 2) !== 0, faded = (c.flags & 12) !== 0; + const size = Math.max(c.extent * g.s, 3 * g.dpr); + const x = g.toX(c.x + c.extent / 2), y = g.toY(c.y + c.extent / 2); + ctx.globalAlpha = faded ? 0.4 : 0.9; + ctx.fillStyle = wild ? css('wildlife') : online ? css('online') : css('player'); + ctx.beginPath(); ctx.arc(x, y, size / 2, 0, Math.PI * 2); ctx.fill(); + ctx.globalAlpha = 1; + const marked = (highlight && c.account === highlight) || (selected && selected.life === c.life); + if (marked) { + ctx.strokeStyle = css('warn'); ctx.lineWidth = 2 * g.dpr; + ctx.beginPath(); ctx.arc(x, y, size / 2 + 4 * g.dpr, 0, Math.PI * 2); ctx.stroke(); + } + } + } + + function hit(px, py) { + const g = geometry(); + const wx = g.fromX(px * g.dpr), wy = g.fromY(py * g.dpr); + const slack = 4 / g.s * g.dpr; + for (const c of view ? view.cells : []) { + const wild = (c.flags & 1) !== 0; + if ((wild && !show_.wildlife) || (!wild && !show_.players)) continue; + if (wx >= c.x - slack && wx <= c.x + c.extent + slack && wy >= c.y - slack && wy <= c.y + c.extent + slack) return { cell: c }; + } + if (show_.bubbles || show_.pools) { + for (const d of view ? view.deps : []) { + if ((d.kind === 2 && !show_.bubbles) || (d.kind !== 2 && !show_.pools)) continue; + const r = Math.max(d.r, slack); + if ((wx - d.x) ** 2 + (wy - d.y) ** 2 <= r * r) return { dep: d }; + } + } + return null; + } + + function cellLines(c) { + const kind = c.flags & 1 ? 'Wildlife' : c.flags & 2 ? 'Player (connected)' : 'Player'; + return [ + ['Kind', kind], ['Life', c.life], ['Organism', c.organism], ['Account', c.account || '—'], + ['Members', c.members], ['Size', fmtLength(c.extent)], ['Body mass', fmtMass(c.bodyMass)], + ['Reserve energy', fmtEnergy(c.reserve[0])], + ['Reserve C / N / P / other', c.reserve.slice(1).map(fmtMass).join(' / ')], + ['Position', `${fmtLength(c.x)}, ${fmtLength(c.y)}`], + ]; + } + function showDetail(c) { + selected = c; + detail.replaceChildren(h('h2', {}, c.flags & 1 ? 'Wildlife cell' : 'Player cell'), + h('dl', { class: 'facts' }, cellLines(c).flatMap(([k, v]) => [h('dt', {}, k), h('dd', { class: k === 'Life' || k === 'Account' ? 'mono' : null }, v)])), + c.account ? h('p', {}, h('a', { href: `#/accounts/${c.account}` }, 'Open account →')) : null); + paint(); + } + + canvas.addEventListener('mousemove', (e) => { + const rect = canvas.getBoundingClientRect(); + if (drag) { + panX = drag.panX + (e.clientX - drag.x); panY = drag.panY + (e.clientY - drag.y); + paint(); return; + } + const found = hit(e.clientX - rect.left, e.clientY - rect.top); + if (!found) { tip.hidden = true; return; } + const lines = found.cell + ? cellLines(found.cell).slice(0, 7) + : [['Kind', found.dep.kind === 2 ? 'Bubble' : 'Pool'], ['Energy', fmtEnergy(found.dep.stock[0])], + ['C / N / P / other', found.dep.stock.slice(1).map(fmtMass).join(' / ')], ['Radius', fmtLength(found.dep.r)]]; + tip.replaceChildren(...lines.map(([k, v]) => h('div', {}, h('span', { class: 'muted' }, `${k}: `), String(v)))); + tip.hidden = false; + tip.style.left = `${Math.min(e.clientX - rect.left + 14, rect.width - 290)}px`; + tip.style.top = `${e.clientY - rect.top + 14}px`; + }); + canvas.addEventListener('mouseleave', () => { tip.hidden = true; drag = null; }); + canvas.addEventListener('mousedown', (e) => { drag = { x: e.clientX, y: e.clientY, panX, panY, moved: false }; }); + canvas.addEventListener('mouseup', (e) => { + const wasDrag = drag && (Math.abs(e.clientX - drag.x) > 3 || Math.abs(e.clientY - drag.y) > 3); + drag = null; + if (wasDrag) return; + const rect = canvas.getBoundingClientRect(); + const found = hit(e.clientX - rect.left, e.clientY - rect.top); + if (found && found.cell) showDetail(found.cell); + }); + canvas.addEventListener('wheel', (e) => { + e.preventDefault(); + const rect = canvas.getBoundingClientRect(); + const mx = e.clientX - rect.left - rect.width / 2, my = e.clientY - rect.top - rect.height / 2; + const factor = Math.exp(-e.deltaY * 0.0015); + const next = Math.min(64, Math.max(1, zoom * factor)); + const k = next / zoom; + panX = mx - (mx - panX) * k; panY = my - (my - panY) * k; + zoom = next; + if (zoom === 1) { panX = 0; panY = 0; } + paint(); + }, { passive: false }); + canvas.addEventListener('dblclick', () => { zoom = 1; panX = 0; panY = 0; paint(); }); + const onResize = () => paint(); + window.addEventListener('resize', onResize); + + async function load() { + try { + const raw = await api(`/api/regions/${region}/view`); + view = { ...raw, cells: raw.cells.map(cellObj), deps: raw.deposits.map(depObj) }; + const players = view.cells.filter((c) => !(c.flags & 1)); + const online = players.filter((c) => c.flags & 2).length; + const wild = view.cells.length - players.length; + const bubbles = view.deps.filter((d) => d.kind === 2).length; + const spentMatter = raw.spent.slice(1).reduce((s, v) => s + v, 0); + statsBox.replaceChildren( + stat('Tick', fmtInt(raw.tick)), stat('Cells', fmtInt(raw.cells_total)), + stat('Players', fmtInt(players.length), `${online} connected`), stat('Wildlife', fmtInt(wild)), + stat('Bubbles', fmtInt(bubbles), `${fmtInt(raw.deposits_total - bubbles)} pools`), + stat('Spent pool', fmtEnergy(raw.spent[0]), fmtMass(spentMatter)), + stat('Area', `${fmtLength(raw.area[0])} × ${fmtLength(raw.area[1])}`)); + const truncated = raw.cells_total > raw.cells.length || raw.deposits_total > raw.deposits.length; + status.textContent = ` rules ${raw.rules}${truncated ? ' · view truncated' : ''} · updated ${new Date().toLocaleTimeString()}`; + status.className = truncated ? 'error' : 'muted'; + if (selected) { + const again = view.cells.find((c) => c.life === selected.life); + if (again) showDetail(again); else { selected = null; detail.replaceChildren(h('span', { class: 'muted' }, 'The selected cell is gone (died or left).')); } + } + paint(); + } catch (e) { + status.textContent = ` ${e.status === 503 ? 'region not ready or unreachable' : e.message}`; + status.className = 'error'; + } + } + const tick = () => { timer = setTimeout(async () => { if (live.checked && !document.hidden) await load(); tick(); }, 1000); }; + await load(); + tick(); + stopPage = () => { clearTimeout(timer); window.removeEventListener('resize', onResize); }; +} + +// ---------- Routing ---------- +async function route() { + stopPage(); + stopPage = () => {}; + const [path, query] = (location.hash.slice(1) || '/accounts').split('?'); + const parts = path.split('/').filter(Boolean); + const params = new URLSearchParams(query || ''); + for (const a of document.querySelectorAll('[data-route]')) a.classList.toggle('active', a.dataset.route === parts[0]); + try { + if (parts[0] === 'accounts' && parts[1]) await accountPage(parts[1]); + else if (parts[0] === 'regions' && parts[1]) await regionPage(parts[1], params); + else if (parts[0] === 'regions') await regionsPage(); + else await accountsPage(); + main().focus({ preventScroll: true }); + } catch (e) { + if (e instanceof ApiError && e.status === 401) return signedOut(); + if (e instanceof ApiError && e.status === 403) { + return show(h('div', { class: 'center' }, h('div', {}, h('h1', {}, 'Not an administrator'), + h('p', { class: 'muted' }, 'Your account does not have the aevolution-admin role.'), + h('button', { onclick: signOut }, 'Sign out')))); + } + show(h('p', { class: 'error' }, `Could not load this page: ${e.message}`), h('button', { onclick: () => route() }, 'Try again')); + } +} + +function signedOut() { + document.getElementById('who').textContent = ''; + document.getElementById('sign-out').hidden = true; + show(h('div', { class: 'center' }, h('div', {}, h('h1', {}, 'AEvolution admin'), + h('p', { class: 'muted' }, 'Sign in with an account that has the aevolution-admin role.'), + h('button', { class: 'primary', onclick: signIn }, 'Sign in')))); +} + +async function start() { + config = await (await fetch('/config.json', { cache: 'no-store' })).json(); + document.getElementById('sign-out').addEventListener('click', signOut); + try { + await finishSignIn(); + } catch (e) { + show(h('p', { class: 'error' }, e.message), h('button', { class: 'primary', onclick: signIn }, 'Sign in again')); + return; + } + if (!(await token())) return signedOut(); + try { + const me = await api('/api/me'); + document.getElementById('who').textContent = me.email || me.subject; + document.getElementById('sign-out').hidden = false; + } catch (e) { + if (e instanceof ApiError && e.status === 401) return signedOut(); + } + window.addEventListener('hashchange', route); + await route(); +} + +start(); diff --git a/apps/evo-admin-api/portal/index.html b/apps/evo-admin-api/portal/index.html new file mode 100644 index 0000000..6378fa5 --- /dev/null +++ b/apps/evo-admin-api/portal/index.html @@ -0,0 +1,30 @@ + + + + + + + AEvolution Admin + + + + +
+ AEvolution admin + +
+ + +
+
+
+

Loading…

+
+ + diff --git a/apps/evo-admin-api/portal/style.css b/apps/evo-admin-api/portal/style.css new file mode 100644 index 0000000..7c53eeb --- /dev/null +++ b/apps/evo-admin-api/portal/style.css @@ -0,0 +1,184 @@ +/* ADR-0182 admin portal. Tokens first; dark is the default, light follows the system. */ +:root { + --bg: #0f1419; + --panel: #161d24; + --panel-2: #1c252e; + --line: #2a3640; + --text: #dbe3ea; + --muted: #8a99a6; + --accent: #4fb3ff; + --good: #3ecf8e; + --warn: #f2b84b; + --bad: #ff6b6b; + --player: #4f8dff; + --online: #5ff2ff; + --wildlife: #3ecf8e; + --pool: rgba(120, 170, 255, 0.16); + --energy: #ffd84d; + --carbon: #b0b7bf; + --nitrogen: #9b7bff; + --phosphorus: #ff9a3c; + --other: #ff6fb5; + --radius: 8px; + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + color-scheme: dark; +} +@media (prefers-color-scheme: light) { + :root { + --bg: #f5f7f9; + --panel: #ffffff; + --panel-2: #eef2f5; + --line: #d6dde3; + --text: #18212a; + --muted: #5d6b77; + --accent: #0b6bcb; + --pool: rgba(30, 90, 200, 0.12); + --carbon: #59626b; + color-scheme: light; + } +} +* { box-sizing: border-box; } +html, body { margin: 0; } +body { + background: var(--bg); + color: var(--text); + font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +button { + font: inherit; + color: var(--text); + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 6px; + padding: 5px 12px; + cursor: pointer; +} +button:hover { border-color: var(--accent); } +button.primary { background: var(--accent); border-color: var(--accent); color: #fff; } +button.ghost { background: transparent; } +input[type="search"] { + font: inherit; + color: var(--text); + background: var(--panel); + border: 1px solid var(--line); + border-radius: 6px; + padding: 5px 10px; + min-width: 240px; +} +.muted { color: var(--muted); } +.mono { font-family: var(--mono); font-size: 12.5px; } + +.bar { + display: flex; + align-items: center; + gap: 24px; + padding: 10px 20px; + background: var(--panel); + border-bottom: 1px solid var(--line); + position: sticky; + top: 0; + z-index: 2; +} +.brand { font-weight: 700; color: var(--text); letter-spacing: 0.02em; } +.brand span { color: var(--accent); font-weight: 500; } +.sections { display: flex; gap: 20px; flex: 1; } +.section { display: flex; align-items: center; gap: 4px; } +.section-name { + text-transform: uppercase; + font-size: 11px; + letter-spacing: 0.08em; + color: var(--muted); + margin-right: 6px; +} +.section a { padding: 5px 10px; border-radius: 6px; color: var(--text); } +.section a.active { background: var(--panel-2); color: var(--accent); } +.who { display: flex; align-items: center; gap: 10px; } + +main { padding: 20px; max-width: 1600px; margin: 0 auto; } +h1 { font-size: 20px; margin: 0 0 4px; } +h2 { font-size: 15px; margin: 20px 0 8px; } +.head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; } +.tools { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } + +.card { + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 14px 16px; +} +.stats { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; margin-bottom: 14px; } +.stat { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 10px 12px; } +.stat .label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); } +.stat .value { font-size: 18px; font-weight: 600; margin-top: 2px; } +.stat .value small { font-size: 12px; font-weight: 400; color: var(--muted); } + +.table-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); } +table { border-collapse: collapse; width: 100%; background: var(--panel); } +th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; } +th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: var(--panel-2); cursor: pointer; user-select: none; } +th.sorted::after { content: " ▾"; } +th.sorted.up::after { content: " ▴"; } +td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; } +tbody tr:hover { background: var(--panel-2); } +tbody tr.clickable { cursor: pointer; } + +.badge { + display: inline-block; + font-size: 11.5px; + padding: 1px 8px; + border-radius: 999px; + border: 1px solid var(--line); + color: var(--muted); +} +.badge.alive { color: var(--good); border-color: var(--good); } +.badge.dead { color: var(--bad); border-color: var(--bad); } +.badge.online { color: var(--online); border-color: var(--online); } +.badge.warn { color: var(--warn); border-color: var(--warn); } + +dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; margin: 0; } +dl.facts dt { color: var(--muted); } +dl.facts dd { margin: 0; } + +.region-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 14px; } +@media (max-width: 1000px) { .region-layout { grid-template-columns: 1fr; } } +.canvas-wrap { + position: relative; + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + overflow: hidden; + aspect-ratio: 1 / 1; + max-height: calc(100vh - 230px); + width: 100%; +} +.canvas-wrap canvas { display: block; width: 100%; height: 100%; cursor: crosshair; } +.overlay-note { position: absolute; left: 10px; bottom: 8px; font-size: 12px; color: var(--muted); pointer-events: none; } +.tooltip { + position: absolute; + pointer-events: none; + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 6px; + padding: 6px 8px; + font-size: 12px; + max-width: 280px; + z-index: 1; +} +.side { display: flex; flex-direction: column; gap: 12px; } +.legend { display: grid; grid-template-columns: 14px 1fr; gap: 6px 8px; align-items: center; font-size: 13px; } +.swatch { width: 12px; height: 12px; border-radius: 50%; } +.swatch.player { background: var(--player); } +.swatch.online { background: var(--online); } +.swatch.wildlife { background: var(--wildlife); } +.swatch.pool { background: var(--pool); border: 1px solid var(--accent); } +.swatch.energy { background: var(--energy); } +.swatch.carbon { background: var(--carbon); } +.swatch.nitrogen { background: var(--nitrogen); } +.swatch.phosphorus { background: var(--phosphorus); } +.swatch.other { background: var(--other); } +.toggles { display: flex; flex-direction: column; gap: 6px; } +.toggles label { display: flex; gap: 8px; align-items: center; cursor: pointer; } +.error { color: var(--bad); } +.center { display: grid; place-items: center; min-height: 50vh; text-align: center; } diff --git a/apps/evo-server/main.cpp b/apps/evo-server/main.cpp index ec1b939..656a54a 100644 --- a/apps/evo-server/main.cpp +++ b/apps/evo-server/main.cpp @@ -55,6 +55,7 @@ #include "evo/biology/founder.hpp" #include "evo/processes/development_opening.hpp" #include "evo/server/cellular_session_batch.hpp" +#include "evo/server/lifecycle/cellular_admin_view.hpp" #include "evo/server/lifecycle/cellular_schedule.hpp" #include "evo/server/lifecycle/primitive_lives.hpp" #include "evo/server/lifecycle/wildlife_controller.hpp" @@ -925,7 +926,9 @@ int serve_cellular(Options& o) { return 2; std::unique_ptr ops; if (!o.ops_listen.empty()) { - auto listening = server::OpsServer::listen(o.ops_listen); + // Room for /admin/view (ADR-0182); probes and metrics stay small. + auto listening = server::OpsServer::listen( + o.ops_listen, server::OpsServer::max_configurable_response_bytes); if (!listening) { std::puts("error ops-listen"); return 2; @@ -1092,6 +1095,20 @@ int serve_cellular(Options& o) { counters.checkpoint_age_ms = schedule.status().head_age_us / 1000; return {200, server::render_metrics(paced, counters)}; } + // ADR-0182: the admin portal's read-only region view. The port admits only + // Prometheus and the admin API (NetworkPolicy). + if (path == "/admin/view") { + const auto* state = host.state(); + if (!current.ready || state == nullptr) + return {503, "not ready\n"}; + const auto online = [&](const server::LifeAccount& account) { + network::AccountId id; + id.bytes = account; + return bridge->sessions().holder(id).has_value(); + }; + return {200, server::render_cellular_admin_view(*state, online), + "application/json"}; + } return {404, "not found\n"}; }; ops->serve(handler); diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index a0d7ac5..5202bc6 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -145,7 +145,8 @@ RUN cmake --preset release -B build/postgres -DCMAKE_CXX_COMPILER=g++-14 \ -DCMAKE_C_COMPILER=gcc-14 -DEVO_BUILD_NETWORK=ON \ -DEVO_BUILD_QUIC=ON -DEVO_BUILD_POSTGRES=ON \ -DPostgreSQL_ROOT=/source/.cache/postgres/install \ - && cmake --build build/postgres --target evo-server evo-session-probe evo-world-clone evo-grant-broker --parallel "${PG_BUILD_JOBS}" + && cmake --build build/postgres --target evo-server evo-session-probe evo-world-clone evo-grant-broker \ + evo-admin-api --parallel "${PG_BUILD_JOBS}" FROM postgres-build AS postgres-test-build ARG PG_BUILD_JOBS=6 @@ -202,6 +203,9 @@ COPY --from=postgres-build /source/build/postgres/evo-server /usr/local/bin/evo- COPY --from=postgres-build /source/build/postgres/evo-world-clone /usr/local/bin/evo-world-clone # ADR-0131 grant broker (Keycloak tokens to session grants); its own Deployment. COPY --from=postgres-build /source/build/postgres/evo-grant-broker /usr/local/bin/evo-grant-broker +# ADR-0182 read-only admin API and the portal's static files; its own Deployment. +COPY --from=postgres-build /source/build/postgres/evo-admin-api /usr/local/bin/evo-admin-api +COPY apps/evo-admin-api/portal/ /usr/local/share/evo-admin-portal/ COPY --from=postgres-build /source/.cache/postgres/install/lib/libpq.so* /opt/postgres/lib/ COPY --from=postgres-build /source/build/postgres/msquic/bin/Release/libmsquic.so* /opt/msquic/lib/ COPY --from=postgres-build /source/.cache/postgres/postgresql-18.6/COPYRIGHT /usr/share/doc/evo-postgres/COPYRIGHT diff --git a/deploy/kubernetes/admin-portal-dev/deployment.yaml b/deploy/kubernetes/admin-portal-dev/deployment.yaml new file mode 100644 index 0000000..3e91688 --- /dev/null +++ b/deploy/kubernetes/admin-portal-dev/deployment.yaml @@ -0,0 +1,88 @@ +# ADR-0182 read-only admin API and portal. One replica; it holds no state but a short view +# cache. The realm's public signing key is pinned below (ADMIN_JWKS, the same key as the grant +# broker's); a Keycloak key rotation needs a Git update in both. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: evo-admin-portal + annotations: + argocd.argoproj.io/sync-wave: "2" # After migration (schema v61). + labels: + app.kubernetes.io/name: evo-admin-portal + app.kubernetes.io/component: admin-portal +spec: + replicas: 1 + revisionHistoryLimit: 3 + progressDeadlineSeconds: 180 + selector: + matchLabels: + app.kubernetes.io/name: evo-admin-portal + template: + metadata: + labels: + app.kubernetes.io/name: evo-admin-portal + app.kubernetes.io/component: admin-portal + app.kubernetes.io/part-of: aevolution + spec: + serviceAccountName: aevolution-admin-portal + automountServiceAccountToken: false + terminationGracePeriodSeconds: 10 + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + fsGroup: 10001 + seccompProfile: {type: RuntimeDefault} + containers: + - name: evo-admin-api + image: aevolution-server + command: ["/bin/bash", "-c"] + args: + - | + set -eu + regions=() + for region in $ADMIN_REGIONS; do regions+=(--region "$region"); done + exec /usr/local/bin/evo-admin-api --listen 0.0.0.0:8080 --world "$ADMIN_WORLD" \ + --jwks "$ADMIN_JWKS" --oidc-issuer "$ADMIN_OIDC_ISSUER" \ + --audience aevolution-admin --client aevolution-admin-portal \ + --role aevolution-admin --assets /usr/local/share/evo-admin-portal \ + --pg-service /run/postgres/pg_service.conf --pg-passfile /run/postgres/pgpass \ + "${regions[@]}" + env: + - {name: ADMIN_WORLD, value: "100"} + # Space-separated REGION=HOST:PORT: each region's operations address for /admin/view. + - {name: ADMIN_REGIONS, value: "16=evo-region-ops:9100"} + - {name: ADMIN_OIDC_ISSUER, value: "https://auth.aeternalisgames.com/realms/aeternalis"} + # Public RS256 signing key(s) of realm aeternalis, from its JWKS endpoint. + - name: ADMIN_JWKS + value: '{"keys":[{"alg":"RS256","e":"AQAB","kid":"NGQG4QzQuBCIHVEomUPy-OoWOTVQIuyf3RXqeNbP8JI","kty":"RSA","n":"vvOpu1xxdyH_mB8LkJG6cwc6UVmmAj6mwQi1oEwrpJDLerBI2OZr2kpgMAUJ3-hMIkz5tRtSjHieMFteVrpDDQaCViIPCIvJTL3T7ujTGFNReSE6ho7h0DB_kybFeEWVpLqm6SSXWFYls5TKo6_t8Hw4G3njiRW9pX_NxyaBHqLkrCi63EyIGHOkdgUczg2d4pM4JTt-q25bcFSlYz8bhD3WEORQmbp-bU7aPPluCqCEAZRrbzf8Iy7svNemP5daDdlWQ3LaNy-ixC2HRjiPZdqK5BgAE800BigI-l1dkyJ4X172TLIPVPLW1WKlvdm3kHOpBXwACYiy8boSNDW7gQ","use":"sig"}]}' + ports: + - {name: http, containerPort: 8080, protocol: TCP} + readinessProbe: + httpGet: {path: /healthz, port: http} + periodSeconds: 5 + timeoutSeconds: 1 + livenessProbe: + httpGet: {path: /healthz, port: http} + initialDelaySeconds: 5 + periodSeconds: 10 + timeoutSeconds: 2 + failureThreshold: 3 + resources: + requests: {cpu: 10m, memory: 16Mi} + limits: {memory: 128Mi} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + volumeMounts: + - {name: connection, mountPath: /run/postgres, readOnly: true} + volumes: + - name: connection + secret: + secretName: aevolution-admin-pg + defaultMode: 0440 + items: + - {key: pg_service.conf, path: pg_service.conf} + - {key: pgpass, path: pgpass} + - {key: ca.crt, path: ca.crt} diff --git a/deploy/kubernetes/admin-portal-dev/kustomization.yaml b/deploy/kubernetes/admin-portal-dev/kustomization.yaml new file mode 100644 index 0000000..c3c1bff --- /dev/null +++ b/deploy/kubernetes/admin-portal-dev/kustomization.yaml @@ -0,0 +1,15 @@ +# ADR-0182 read-only admin API and portal for evolution-dev ONLY: verifies Keycloak access +# tokens (realm aeternalis, realm role aevolution-admin, audience aevolution-admin) and reads +# world 100 through the schema v61 views and region 16's /admin/view. +# Public route, 443 only: https://srs.aeternalisgames.com -> ingress-nginx (TLS; Ingress +# created out of band, since the aevolution-dev Argo project admits none) -> ClusterIP +# Service evo-admin-portal:8080, in-cluster only. +# Out-of-band Secret in evolution-dev: aevolution-admin-pg (pg_service.conf, pgpass, ca.crt +# for a login in the runtime group, as aevolution-grant-broker-pg). +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - serviceaccount.yaml + - deployment.yaml + - service.yaml + - networkpolicy.yaml diff --git a/deploy/kubernetes/admin-portal-dev/networkpolicy.yaml b/deploy/kubernetes/admin-portal-dev/networkpolicy.yaml new file mode 100644 index 0000000..36bd11a --- /dev/null +++ b/deploy/kubernetes/admin-portal-dev/networkpolicy.yaml @@ -0,0 +1,58 @@ +# Admin portal traffic on top of the namespace default-deny. Admins reach it only at +# https://srs.aeternalisgames.com on 443, where ingress-nginx terminates TLS; port 8080 is +# admitted from the ingress-nginx pods and nothing else. Egress: PostgreSQL on pg-forge-01 +# and the region's operations port (9100) for /admin/view. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: evo-admin-portal + annotations: + argocd.argoproj.io/sync-wave: "-1" +spec: + podSelector: + matchLabels: + app.kubernetes.io/name: evo-admin-portal + policyTypes: [Ingress, Egress] + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + app.kubernetes.io/name: rke2-ingress-nginx + ports: + - {protocol: TCP, port: 8080} + egress: + - to: + - ipBlock: + cidr: 172.10.1.127/32 + ports: + - {protocol: TCP, port: 5432} + - to: + - podSelector: + matchLabels: + app.kubernetes.io/name: evo-region + ports: + - {protocol: TCP, port: 9100} +--- +# The region's operations port also admits the admin portal (alongside Prometheus, +# evo-region-scrape). Only 9100: never the session port. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: evo-region-admin-view + annotations: + argocd.argoproj.io/sync-wave: "-1" +spec: + podSelector: + matchLabels: + app.kubernetes.io/name: evo-region + policyTypes: [Ingress] + ingress: + - from: + - podSelector: + matchLabels: + app.kubernetes.io/name: evo-admin-portal + ports: + - {protocol: TCP, port: 9100} diff --git a/deploy/kubernetes/admin-portal-dev/service.yaml b/deploy/kubernetes/admin-portal-dev/service.yaml new file mode 100644 index 0000000..2f571e6 --- /dev/null +++ b/deploy/kubernetes/admin-portal-dev/service.yaml @@ -0,0 +1,15 @@ +# Cluster-internal; the Ingress for srs.aeternalisgames.com terminates TLS and forwards here. +apiVersion: v1 +kind: Service +metadata: + name: evo-admin-portal + annotations: + argocd.argoproj.io/sync-wave: "2" + labels: + app.kubernetes.io/name: evo-admin-portal +spec: + type: ClusterIP + selector: + app.kubernetes.io/name: evo-admin-portal + ports: + - {name: http, port: 8080, targetPort: http, protocol: TCP} diff --git a/deploy/kubernetes/admin-portal-dev/serviceaccount.yaml b/deploy/kubernetes/admin-portal-dev/serviceaccount.yaml new file mode 100644 index 0000000..8a5de18 --- /dev/null +++ b/deploy/kubernetes/admin-portal-dev/serviceaccount.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: aevolution-admin-portal + annotations: + argocd.argoproj.io/sync-wave: "-1" +automountServiceAccountToken: false +# Create this pull-only Secret separately in evolution-dev; never commit credentials. +imagePullSecrets: + - name: harbor-pull diff --git a/deploy/kubernetes/region/dev/kustomization.yaml b/deploy/kubernetes/region/dev/kustomization.yaml index 952c38b..2a3a51b 100644 --- a/deploy/kubernetes/region/dev/kustomization.yaml +++ b/deploy/kubernetes/region/dev/kustomization.yaml @@ -9,6 +9,7 @@ resources: components: - ../dev-session-route - ../../grant-broker-dev + - ../../admin-portal-dev - ../../worker-only-dev images: - name: aevolution-server diff --git a/docs/STATUS.md b/docs/STATUS.md index dcf70a6..086b88a 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,17 @@ # Project status and next steps +## Read-only admin portal - 2026-10-27 + +[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) records the admin portal direction +(world tuning in SQL adopted per tick, admin commands, data-defined mutations) and delivers +its read-only first step: `evo-admin-api` and the portal at `https://srs.aeternalisgames.com` +behind the Keycloak realm role `aevolution-admin`. It lists accounts (session, status, +lives, deaths, resets, mutation choices), one account's lives, the world's regions, and a +live 2D view of a region's cells, wildlife, pools and bubbles from the region's new +`/admin/view` ops route. Schema 61 adds only read functions. Nothing in the simulation, +wire protocol or checkpoints changed. Not yet deployed: it needs a new server image, the +Keycloak client, an Ingress and a database Secret. See [validation](engineering/VALIDATION.md). + ## Reproduction safety trial and resizable cards - 2026-10-27 [ADR-0181](adr/0181-cellular-reproduction-safety.md) declares opt-in safety diff --git a/docs/adr/0182-admin-portal-and-world-tuning.md b/docs/adr/0182-admin-portal-and-world-tuning.md index 9dc4aff..087f2c8 100644 --- a/docs/adr/0182-admin-portal-and-world-tuning.md +++ b/docs/adr/0182-admin-portal-and-world-tuning.md @@ -23,7 +23,7 @@ may change a running region except an event recorded at a tick. ### 1. World tuning lives in SQL -- Schema 61 adds append-only `world_tuning_revisions(world, revision, parent_revision, +- Schema 62 adds append-only `world_tuning_revisions(world, revision, parent_revision, format, canonical_text, digest, author_subject, reason, created_at)`. A revision is the complete canonical tuning text (`encode_cellular_revamp_tuning`), never a diff, so the existing parser and validator are the only interpretation. @@ -51,7 +51,7 @@ may change a running region except an event recorded at a tick. ### 3. Admin commands -- Schema 61 adds `admin_commands(world, region, command_id, kind, payload, author_subject, +- Schema 62 adds `admin_commands(world, region, command_id, kind, payload, author_subject, reason, created_at, applied_tick, outcome)`. The admin API inserts and the region host drains them at tick boundaries in id order, publishing each with that tick. This is the same pattern as the durable mutation queue (schema 59). @@ -121,24 +121,53 @@ pool holds. For the source, scale multiplies the import. ### 7. Admin API and portal - `evo-admin-api`: a C++ service built like the grant broker. It verifies Keycloak access - tokens against the realm keys pinned in Git, requires audience `aevolution-admin` and - realm role `aevolution-admin`, and has its own database login limited to the read views - and the admin tables. Configured world allowlist; World0 is refused in code. + tokens against the realm keys pinned in Git, requires audience `aevolution-admin`, + authorized party `aevolution-admin-portal` and realm role `aevolution-admin`, and serves + one configured world. Its component exists only in the evolution-dev overlay; World0 and + stage have no admin portal (World0 has no fixed world id to refuse in code). - Every write records the token subject and a reason. - The region view: the region host's internal ops port gains a bounded snapshot route (cell - id, position, radius, wildlife/player and account, bubbles), reachable only from the admin + id, position, extent, wildlife/player and account, bubbles), reachable only from the admin API by NetworkPolicy. The admin API serves it to the portal at up to 1 Hz. - The portal is a static browser application at `https://srs.aeternalisgames.com` - (section **Cellular** now, **3D** later) using authorization code with PKCE. Its toolchain is chosen in the implementation change - with dependency evidence (DEPENDENCY_EVALUATION.md). + (section **Cellular** now, **3D** later) using authorization code with PKCE. It is plain + HTML, CSS and JavaScript with no third-party code, so no dependency evaluation is needed. - Keycloak (maintainer setup): realm role `aevolution-admin`; public client - `aevolution-admin-portal` with PKCE S256; an audience mapper adding `aevolution-admin`; - MFA required for the role. + `aevolution-admin-portal` with standard flow and PKCE S256, redirect URI + `https://srs.aeternalisgames.com/*`, web origin `https://srs.aeternalisgames.com` and + post-logout redirect `https://srs.aeternalisgames.com/`; an audience mapper adding + `aevolution-admin`; MFA required for the role. + +### 8. Read-only portal (delivered first, schema 61) + +- **Schema 61** adds three bounded, read-only SECURITY DEFINER functions, executable by the + runtime group and listed in the privilege audit: `admin_accounts_v1(world)` (every account + with its identity, session control, lives, deaths, active life and mutation-choice count), + `admin_account_lives_v1(world, account)` (its life requests and endings) and + `admin_regions_v1(world)` (leases and heads). No table or existing function changes. The + runtime group still has no table privilege. DEV's admin API logs in with its own login in + that group, as the grant broker does; a dedicated read role is a later least-privilege step. +- **Derived values.** A life is a published, unrefused reservation; a death is an ended one; + resets are lives after the first; logged in means the session control has not expired. +- **Region view.** `GET /admin/view` on the cellular region's ops port renders the committed + in-memory owner (`render_cellular_admin_view`): every cell (life and organism ids as + strings, account, footprint, extent, wildlife/connected/lingering/suspended flags, + members, reserve, body mass) and every pool and bubble, bounded to 4,096 cells and 16,384 + deposits with totals. It reads without changing anything; the ops server's response + bound becomes configurable (4 MiB for this port), default 16 KiB elsewhere. +- **Portal files and headers.** The image ships the portal under + `/usr/local/share/evo-admin-portal`. Files go out with a strict Content-Security-Policy + (`'self'` scripts and styles, connections only to this origin and the realm), `nosniff`, + `no-referrer` and `DENY` framing; every answer is `no-store`. The access token stays in + page memory and the rotating refresh token in the tab's sessionStorage. +- **Not yet available** (they need the schema-62 records): time played, bans, current + mutations and living offspring. ## Delivery order -1. Read-only portal: login, accounts (from existing data), regions, census, region view. -2. Schema 61 and the new owner format: world revisions, adoption records, admin commands, +1. Read-only portal: login, accounts (from existing data), regions, region view (schema 61, + section 8). +2. Schema 62 and the new owner format: world revisions, adoption records, admin commands, game source, drip settings, the score vector, session intervals and bans. One new opening on that format. 3. Admin commands and account actions in the portal. diff --git a/docs/adr/README.md b/docs/adr/README.md index d75adb9..689d1b1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -1,6 +1,6 @@ # Architecture decision records -- [ADR-0182: Admin portal, world tuning in SQL and per-tick amendments](0182-admin-portal-and-world-tuning.md) - accepted direction: world tuning revisions in SQL adopted per tick and recorded in region history, admin commands with a named game source, drip/source settings, data-defined mutations, bans and session intervals, and a Keycloak-gated admin API and portal; migration and new matter types deferred. +- [ADR-0182: Admin portal, world tuning in SQL and per-tick amendments](0182-admin-portal-and-world-tuning.md) - accepted direction: world tuning revisions in SQL adopted per tick and recorded in region history, admin commands with a named game source, drip/source settings, data-defined mutations, bans and session intervals, and a Keycloak-gated admin API and portal; the read-only portal (schema 61 read views and the region view) comes first; migration and new matter types deferred. - [ADR-0181: Reproduction safety revision 1](0181-cellular-reproduction-safety.md) - opt-in controlled-cell mutation share, retained budding provision, outward mutation launch and a protected growth fuel buffer; historical declarations unchanged. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 9f74a99..689fe55 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -10414,3 +10414,60 @@ command, and another unique session activation expiring four hours ahead. No credential values, credential file, remote URL change or credential-store change are included in the repository; temporary helpers stay in ignored build output. No deployment or live-reachability claim follows from publication. + +## 2026-10-27 - Read-only admin portal (ADR-0182 step 1, schema 61) + +Scope: ADR-0182's read-only first step. `evo-admin-api` (Keycloak realm role +`aevolution-admin`, audience `aevolution-admin`, client `aevolution-admin-portal`) serves +the static portal and read-only JSON for world 100; schema 61 adds three bounded +SECURITY DEFINER read functions; the cellular region's ops port gains `/admin/view`. +The token verifier gains an optional realm-role rule and returns the email; the ops +server's response bound becomes configurable (default unchanged). No simulation rule, +checkpoint, manifest, wire protocol, genome or golden changed; `extent_of` reads the +existing phenotype budget. + +Also fixed a pre-existing PostgreSQL failure (`region store test line 826`, also seen in +Gitea run 542): since 054e485 the DEV revamp tuning file seeds 100 wildlife, which +`evo-world-clone provision` refuses without an audited `--playtest-wildlife-first-id` +range. The cellular-v10 provisioning test now provisions the Git file's rules with its +DEV opening fixture set to zero; seeded wildlife keeps its own suite. Earlier push builds +skipped the PostgreSQL gate, and the 09:00 nightly (run 539) stopped at the format check, +so the failure had not surfaced. + +Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, existing build/m97-postgres with network, +QUIC and PostgreSQL): + +- Built evo-server, evo-world-clone, evo-grant-broker, evo-admin-api, evo-postgres-tests + and evo-cellular-admin-view-tests with -Werror (two missing-field-initializer errors + from the new aggregate members were fixed with default initializers). +- `cellular-admin-view-contracts` passed: header, totals, every cell row (id strings, + account text, position, extent, connected flag, members), the cell and deposit limits + keeping the lowest ids, empty lists, and an unchanged owner snapshot after rendering. +- `tools/ci/postgres-check.sh --suite-only` passed after the fixes above: token role + checks (required role present, absent, wrong shape; email), the admin API over world + 9831 (public files with CSP/nosniff headers, `/config.json`, 405 for POST, 401 without or + with a foreign token, 403 without the role, no database contact before verification, + accounts with session/status/lives/resets, one account, 404s, regions, the view cache, + unviewable and unreachable regions, an offline database as 503, and the runtime role + still refused direct table reads), the migration path to schema 61 with the privilege + audit's new fenced functions, and the updated migration history expectation. +- `tools/ci/postgres-check.sh --full` passed (634 s: suite, migration partitions, life + reservations, backup, DR, upgrade, migration history, permission audit, checksum drift). + Two CI scripts that pin the newest schema were updated: history-domain-check's schema-50 + rewind now drops the three schema-61 functions first, and the unknown-future-version + probe moves from 61 to 62. +- clang-tidy 19 with warnings as errors on every new or changed source passed after one + unchecked-optional fix in the view test; clang-format 19.1.5 applied to changed C++. +- Deploy suite (deploy-policy-check 80 objects / 150 rendered in 17 overlays, selftest, + ops-lib-check) passed with the new admin-portal-dev component. +- Local process smoke of the built evo-admin-api with the realm's pinned JWKS and a + placeholder (unreachable) database: `/`, `/app.js`, `/style.css`, `/config.json`, + `/healthz` answered 200 with the expected types and security headers, `/api/accounts` + 401 for a malformed token, `/missing` 404; no arguments exit 2 with usage. +- `node --check` on the portal script. + +Limits: no Keycloak sign-in, browser session or live region view was exercised (the +Keycloak client, Ingress, Secret and a new server image are not in place yet); account +lives and deaths were checked only on accounts without lives. The MSVC and sanitizer +presets and the image build/smoke were not run locally. Nothing was deployed, pushed or +synced; no World0, stage or live database operation occurred. diff --git a/include/evo/server/admin/admin_api.hpp b/include/evo/server/admin/admin_api.hpp new file mode 100644 index 0000000..c1ec522 --- /dev/null +++ b/include/evo/server/admin/admin_api.hpp @@ -0,0 +1,83 @@ +#pragma once + +#include "evo/persistence/postgres.hpp" +#include "evo/server/broker/access_token.hpp" +#include "evo/server/ops_http.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ADR-0182 read-only admin API and portal host. One world; every /api route needs a Keycloak +// access token carrying the admin realm role. The portal's static files and its OIDC settings +// are public; they carry no secret. +// +// GET /healthz ok +// GET / and the portal's files the portal (index.html, app.js, style.css) +// GET /config.json issuer, client id and world for the portal's sign-in +// GET /api/me the signed-in admin's subject and email +// GET /api/accounts every account with session, lives, deaths and resets +// GET /api/accounts/ one account and its life requests +// GET /api/regions the world's regions, leases and heads +// GET /api/regions//view the region's live view (render_cellular_admin_view) +namespace evo::server::admin { +struct AdminAsset { + std::string path; // "/index.html", ...; "/" serves "/index.html". + std::string content_type, body; +}; +struct AdminConfig { + std::uint64_t world{}; + std::vector view_regions; // Regions whose live view can be fetched. + std::string portal_config_json; // Served at /config.json. + std::string content_security_policy; // Sent with every portal file. + std::chrono::milliseconds db_timeout{3000}; + std::chrono::milliseconds view_cache{750}; // A fetched view answers repeats this long. +}; +using AdminConnect = std::function()>; +// The region's /admin/view body, or nullopt when it cannot be reached or is not ready. +using AdminRegionView = std::function(std::uint64_t region)>; + +class AdminApi { + public: + AdminApi(AdminConfig config, broker::TokenVerifier verifier, AdminConnect connect, + AdminRegionView view, std::vector assets); + // `now_seconds` is wall time (token expiry); `now` paces the view cache. + [[nodiscard]] OpsResponse handle(const ApiRequest& request, std::uint64_t now_seconds, + std::chrono::steady_clock::time_point now); + + private: + [[nodiscard]] OpsResponse api(std::string_view path, const broker::AccessTokenClaims& admin, + std::chrono::steady_clock::time_point now); + [[nodiscard]] OpsResponse accounts(std::optional account); + [[nodiscard]] OpsResponse regions(); + [[nodiscard]] OpsResponse view(std::uint64_t region, std::chrono::steady_clock::time_point now); + [[nodiscard]] std::optional query(const std::string& sql, + std::vector parameters); + + AdminConfig config_; + broker::TokenVerifier verifier_; + AdminConnect connect_; + AdminRegionView view_; + std::vector assets_; + std::unique_ptr db_; + struct CachedView { + std::chrono::steady_clock::time_point at; + std::string body; + }; + std::map views_; +}; + +// Bounded blocking HTTP/1.1 GET of `path` from "host:port" (a name is resolved): the body of +// a 200 answer of at most `limit` bytes, or nullopt on any error, other status or timeout. +[[nodiscard]] std::optional http_get(std::string_view address, std::string_view path, + std::chrono::milliseconds timeout, + std::size_t limit); +// JSON string literal (quotes included) with control characters escaped. +[[nodiscard]] std::string json_string(std::string_view text); +} // namespace evo::server::admin diff --git a/include/evo/server/broker/access_token.hpp b/include/evo/server/broker/access_token.hpp index d3d303b..54d6802 100644 --- a/include/evo/server/broker/access_token.hpp +++ b/include/evo/server/broker/access_token.hpp @@ -17,10 +17,13 @@ struct AccessTokenRules { std::string audience; // Must appear in `aud` (string or array). std::string authorized_party; // `azp`: the game's public client. std::uint64_t leeway_seconds{30}; + // ADR-0182: when set, the role must appear in `realm_access.roles` (the admin portal). + std::string realm_role{}; }; struct AccessTokenClaims { std::string issuer, subject; std::uint64_t expires_at{}; + std::string email{}; // Empty when absent; shown to the admin, never used as identity. }; enum class TokenError : std::uint8_t { malformed, @@ -34,7 +37,8 @@ enum class TokenError : std::uint8_t { expired, not_yet_valid, unverified_email, - missing_subject + missing_subject, + missing_role }; inline constexpr std::size_t max_access_token_bytes = 6144; diff --git a/include/evo/server/lifecycle/cellular_admin_view.hpp b/include/evo/server/lifecycle/cellular_admin_view.hpp new file mode 100644 index 0000000..cdb6334 --- /dev/null +++ b/include/evo/server/lifecycle/cellular_admin_view.hpp @@ -0,0 +1,36 @@ +#pragma once + +#include "evo/server/lifecycle/cellular_lives.hpp" + +#include +#include +#include + +// ADR-0182 read-only region view for the admin portal: every cell, pool and bubble of a +// cellular owner as compact JSON. It reads the committed in-memory state and changes nothing; +// it is not a simulation output, a checkpoint or a client protocol. +// +// {"world":W,"region":R,"tick":T,"rules":N,"area":[w,h], +// "spent":[e,c,n,p,o],"cells_total":N,"deposits_total":N, +// "cells":[["life","organism","account",x,y,extent,flags,members, +// reserve_e,reserve_c,reserve_n,reserve_p,reserve_o,body_mass],...], +// "deposits":[[id,kind,x,y,radius,e,c,n,p,o],...]} +// +// Cell positions are the lower-left corner of the square footprint and deposits their centre, +// in micrometres. Life and organism ids are decimal strings (bud ids exceed 2^53); `account` +// is the lowercase UUID, empty for wildlife. Flags: 1 wildlife, 2 the account's session is +// connected, 4 lingering, 8 suspended. Deposit kind: 0 patch, 1 pool, 2 bubble. Energy in +// pJ, matter in fg. Cells and deposits beyond the limits are left out (by ascending life id +// and deposit id); the totals still count them. +namespace evo::server { +struct CellularAdminViewLimits { + std::size_t cells{4096}, deposits{16384}; +}; +// True when the account's session is connected to this region. +using CellularAdminOnline = std::function; +[[nodiscard]] std::string render_cellular_admin_view(const CellularLives& state, + const CellularAdminOnline& online, + CellularAdminViewLimits limits = {}); +// Lowercase 8-4-4-4-12 text of a 16-byte account. +[[nodiscard]] std::string cellular_account_text(const LifeAccount& account); +} // namespace evo::server diff --git a/include/evo/server/lifecycle/cellular_lives.hpp b/include/evo/server/lifecycle/cellular_lives.hpp index 0a8a96c..eeb0e03 100644 --- a/include/evo/server/lifecycle/cellular_lives.hpp +++ b/include/evo/server/lifecycle/cellular_lives.hpp @@ -328,6 +328,9 @@ class CellularLives { [[nodiscard]] accounting::Inventory heat() const noexcept; // Rules 13: burned matter and kill remainders waiting to drip back as bubbles. [[nodiscard]] accounting::Inventory spent() const noexcept; + // ADR-0182 observers: a life's square footprint side in micrometres, as the step uses it; + // nullopt when its genome cannot be costed. Reads the state; changes nothing. + [[nodiscard]] std::optional extent_of(const CellularOwnedLife& life) const; [[nodiscard]] accounting::Inventory opening_total() const noexcept; [[nodiscard]] accounting::Inventory current_total() const noexcept; [[nodiscard]] const CellularBoundaryLedger& boundary_ledger() const noexcept; diff --git a/include/evo/server/ops_http.hpp b/include/evo/server/ops_http.hpp index d9f5b76..7b6ed8e 100644 --- a/include/evo/server/ops_http.hpp +++ b/include/evo/server/ops_http.hpp @@ -19,6 +19,7 @@ struct OpsResponse { int status{200}; std::string body; std::string content_type{"text/plain; charset=utf-8"}; + std::string headers{}; // Extra header lines, each ending in CRLF (ADR-0182 portal). }; // Receives the request path (no query handling: probes use exact paths). using OpsHandler = std::function; @@ -38,12 +39,16 @@ class OpsServer { static constexpr std::size_t max_accepts_per_serve = 4; static constexpr std::size_t max_request_bytes = 4096; static constexpr std::size_t max_api_request_bytes = 8192; // Room for an access token. - static constexpr std::size_t max_response_bytes = 16384; + static constexpr std::size_t max_response_bytes = 16384; // The default bound. + // ADR-0182: the admin view and portal answer up to this many bytes when asked to. + static constexpr std::size_t max_configurable_response_bytes = std::size_t{4} << 20U; static constexpr std::chrono::milliseconds connection_deadline{1000}; - // Numeric address only ("127.0.0.1:9100" or "[::1]:9100"); port 0 picks one. + // Numeric address only ("127.0.0.1:9100" or "[::1]:9100"); port 0 picks one. A + // response over `response_limit` bytes (at most max_configurable_response_bytes) is + // replaced by a 500. [[nodiscard]] static std::expected, OpsError> - listen(std::string_view address); + listen(std::string_view address, std::size_t response_limit = max_response_bytes); OpsServer(const OpsServer&) = delete; OpsServer& operator=(const OpsServer&) = delete; OpsServer(OpsServer&&) = delete; @@ -72,12 +77,14 @@ class OpsServer { std::size_t sent{}; std::chrono::steady_clock::time_point deadline{}; }; - OpsServer(int fd, std::uint16_t port) : fd_(fd), port_(port) {} + OpsServer(int fd, std::uint16_t port, std::size_t response_limit) + : fd_(fd), port_(port), response_limit_(response_limit) {} void respond(Connection& c, const OpsHandler& handler); void respond_api(Connection& c, const ApiHandler& handler); template void serve_with(std::size_t request_limit, const Answer& answer); int fd_; std::uint16_t port_; + std::size_t response_limit_; std::vector connections_; std::uint64_t refused_{}; }; diff --git a/migrations/0061_admin_read_views.sql b/migrations/0061_admin_read_views.sql new file mode 100644 index 0000000..610d9de --- /dev/null +++ b/migrations/0061_admin_read_views.sql @@ -0,0 +1,82 @@ +-- Admin portal read views (ADR-0182, 2026-10-27). Three read-only, bounded SECURITY DEFINER +-- functions for the DEV admin API: a world's accounts with their lives and session control, +-- one account's lives, and a world's regions with their heads. Nothing is written; no table, +-- row, constraint or existing function changes. The runtime group may execute them; DEV's +-- admin API logs in within that group, as the grant broker does (ADR-0131). + +-- Every account known to the world: Keycloak identities and accounts that reserved a life. +-- A life is a published, unrefused reservation; a death is an ended one. The control row is +-- the account's session claim (region and expiry), as the region last renewed it. +CREATE FUNCTION evolution.admin_accounts_v1(p_world evolution.u64) +RETURNS TABLE (account_id uuid, created_at timestamptz, issuer text, subject text, + control_region evolution.u64, control_expires timestamptz, lives bigint, deaths bigint, + active_life evolution.u64, active_region evolution.u64, mutation_choices bigint) +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ + WITH accounts AS ( + SELECT i.account_id FROM evolution.account_identities i + UNION + SELECT r.account_id FROM evolution.life_reservations r WHERE r.world_id = p_world + ), lives AS ( + SELECT r.account_id, r.identity, r.region_id, r.request_id, r.ended_commit + FROM evolution.life_reservations r + JOIN evolution.primitive_life_bindings b ON b.world_id = r.world_id + AND b.account_id = r.account_id AND b.request_id = r.request_id + WHERE r.world_id = p_world AND r.rejection = 0 + ) + SELECT a.account_id, i.created_at, i.issuer, i.subject, c.region_id, c.expires_at, + (SELECT count(*) FROM lives l WHERE l.account_id = a.account_id), + (SELECT count(*) FROM lives l WHERE l.account_id = a.account_id + AND l.ended_commit IS NOT NULL), + active.identity, active.region_id, + (SELECT count(*) FROM evolution.cellular_mutation_reservations m + WHERE m.world_id = p_world AND m.account_id = a.account_id) + FROM accounts a + LEFT JOIN evolution.account_identities i ON i.account_id = a.account_id + LEFT JOIN evolution.account_controls c ON c.world_id = p_world AND c.account_id = a.account_id + LEFT JOIN LATERAL (SELECT l.identity, l.region_id FROM lives l + WHERE l.account_id = a.account_id AND l.ended_commit IS NULL + ORDER BY l.request_id DESC LIMIT 1) active ON true + ORDER BY i.created_at NULLS LAST, a.account_id + LIMIT 10000 +$$; +REVOKE ALL ON FUNCTION evolution.admin_accounts_v1(evolution.u64) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION evolution.admin_accounts_v1(evolution.u64) TO :"runtime_role"; + +-- One account's life requests in order: published or not, refused or not, and when an +-- ended life's commit was published (its last tick and time). +CREATE FUNCTION evolution.admin_account_lives_v1(p_world evolution.u64, p_account uuid) +RETURNS TABLE (request_id evolution.u64, identity evolution.u64, region_id evolution.u64, + rejection smallint, born evolution.u64, ended_tick evolution.u64, ended_at timestamptz) +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ + SELECT r.request_id, r.identity, r.region_id, r.rejection, b.born, e.end_tick, e.committed_at + FROM evolution.life_reservations r + LEFT JOIN evolution.primitive_life_bindings b ON b.world_id = r.world_id + AND b.account_id = r.account_id AND b.request_id = r.request_id + LEFT JOIN evolution.region_commits e ON e.commit_id = r.ended_commit + WHERE r.world_id = p_world AND r.account_id = p_account + ORDER BY r.request_id + LIMIT 1000 +$$; +REVOKE ALL ON FUNCTION evolution.admin_account_lives_v1(evolution.u64, uuid) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION evolution.admin_account_lives_v1(evolution.u64, uuid) + TO :"runtime_role"; + +-- A world's regions: lease (epoch, whether held and until when) and the head commit. +CREATE FUNCTION evolution.admin_regions_v1(p_world evolution.u64) +RETURNS TABLE (region_id evolution.u64, frame_id evolution.u64, lease_epoch evolution.u64, + lease_held boolean, lease_expires timestamptz, commit_sequence evolution.u64, + end_tick evolution.u64, committed_at timestamptz, build_identity text) +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ + SELECT l.region_id, l.frame_id, l.epoch, l.holder IS NOT NULL, l.expires_at, + h.commit_sequence, h.end_tick, c.committed_at, encode(c.build_identity, 'hex') + FROM evolution.region_leases l + LEFT JOIN evolution.region_heads h ON h.world_id = l.world_id AND h.region_id = l.region_id + LEFT JOIN evolution.region_commits c ON c.commit_id = h.commit_id + WHERE l.world_id = p_world + ORDER BY l.region_id + LIMIT 1000 +$$; +REVOKE ALL ON FUNCTION evolution.admin_regions_v1(evolution.u64) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION evolution.admin_regions_v1(evolution.u64) TO :"runtime_role"; + +INSERT INTO evolution.schema_migrations(version,sha256) VALUES(61,:'migration_sha_61'); diff --git a/migrations/apply.sql b/migrations/apply.sql index de1c022..91cfc78 100644 --- a/migrations/apply.sql +++ b/migrations/apply.sql @@ -136,6 +136,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') SELECT :'history_v57' || ',58:' || :'migration_sha_58' AS history_v58 \gset SELECT :'history_v58' || ',59:' || :'migration_sha_59' AS history_v59 \gset SELECT :'history_v59' || ',60:' || :'migration_sha_60' AS history_v60 \gset + SELECT :'history_v60' || ',61:' || :'migration_sha_61' AS history_v61 \gset SELECT :'history' = :'history_v22' AS at_v22, :'history' = :'history_v23' AS at_v23, :'history' = :'history_v24' AS at_v24, @@ -174,8 +175,10 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') :'history' = :'history_v57' AS at_v57, :'history' = :'history_v58' AS at_v58, :'history' = :'history_v59' AS at_v59, - :'history' = :'history_v60' AS at_v60 \gset - \if :at_v60 + :'history' = :'history_v60' AS at_v60, + :'history' = :'history_v61' AS at_v61 \gset + \if :at_v61 + \elif :at_v60 \elif :at_v59 \elif :at_v58 \elif :at_v57 @@ -589,7 +592,8 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, coalesce(max(version), 0) = 57 AS at_v57, coalesce(max(version), 0) = 58 AS at_v58, coalesce(max(version), 0) = 59 AS at_v59, - coalesce(max(version), 0) = 60 AS at_v60 + coalesce(max(version), 0) = 60 AS at_v60, + coalesce(max(version), 0) = 61 AS at_v61 FROM evolution.schema_migrations \gset \if :at_v24 \ir 0025_cellular_v2_bundle.sql @@ -818,6 +822,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \elif :at_v58 \elif :at_v59 \elif :at_v60 +\elif :at_v61 \else \echo 'Unknown or changed migration history after v43' DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$; @@ -890,6 +895,10 @@ SELECT coalesce(max(version), 0) = 59 AS needs_v60 FROM evolution.schema_migrati \if :needs_v60 \ir 0060_cellular_revamp_bundle.sql \endif +SELECT coalesce(max(version), 0) = 60 AS needs_v61 FROM evolution.schema_migrations \gset +\if :needs_v61 + \ir 0061_admin_read_views.sql +\endif -- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes -- alone are insufficient: predefined roles such as pg_write_all_data, PUBLIC -- grants or SET-able memberships would bypass the fenced functions. Checks the @@ -963,6 +972,9 @@ BEGIN ('evolution.load_cellular_mutation_publications(evolution.u64,evolution.u64,uuid,evolution.u64,uuid)'::regprocedure::oid), ('evolution.end_cellular_lives(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,bytea)'::regprocedure::oid), ('evolution.issue_account_grant(evolution.u64,text,text)'::regprocedure::oid), + ('evolution.admin_accounts_v1(evolution.u64)'::regprocedure::oid), + ('evolution.admin_account_lives_v1(evolution.u64,uuid)'::regprocedure::oid), + ('evolution.admin_regions_v1(evolution.u64)'::regprocedure::oid), ('evolution.revoke_account_grants(evolution.u64,text,text)'::regprocedure::oid), ('evolution.load_cellular_publication_actions(evolution.u64,evolution.u64,uuid,evolution.u64,uuid)'::regprocedure::oid), ('evolution.load_cellular_publication_births(evolution.u64,evolution.u64,uuid,evolution.u64,uuid)'::regprocedure::oid), diff --git a/src/server/admin/admin_api.cpp b/src/server/admin/admin_api.cpp new file mode 100644 index 0000000..38dd9ff --- /dev/null +++ b/src/server/admin/admin_api.cpp @@ -0,0 +1,375 @@ +#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 diff --git a/src/server/broker/access_token.cpp b/src/server/broker/access_token.cpp index eaca08a..a6906ca 100644 --- a/src/server/broker/access_token.cpp +++ b/src/server/broker/access_token.cpp @@ -211,6 +211,17 @@ TokenVerifier::verify(std::string_view token, std::uint64_t now_seconds) const { const auto subject = text("sub"); if (!subject || subject->empty() || subject->size() > 255) return std::unexpected{TokenError::missing_subject}; - return AccessTokenClaims{rules_.issuer, std::string(*subject), *expires}; + if (!rules_.realm_role.empty()) { + const auto* realm = payload->member("realm_access"); + const auto* roles = realm ? realm->member("roles") : nullptr; + if (!roles || !roles->array() || + std::ranges::none_of(*roles->array(), [&](const JsonValue& role) { + return role.string() == rules_.realm_role; + })) + return std::unexpected{TokenError::missing_role}; + } + const auto email = text("email"); + return AccessTokenClaims{rules_.issuer, std::string(*subject), *expires, + email && email->size() <= 254 ? std::string(*email) : std::string{}}; } } // namespace evo::server::broker diff --git a/src/server/lifecycle/cellular_admin_view.cpp b/src/server/lifecycle/cellular_admin_view.cpp new file mode 100644 index 0000000..0d3a958 --- /dev/null +++ b/src/server/lifecycle/cellular_admin_view.cpp @@ -0,0 +1,134 @@ +#include "evo/server/lifecycle/cellular_admin_view.hpp" + +#include +#include +#include +#include + +namespace evo::server { +namespace { +void append(std::string& out, std::uint64_t value) { + out += std::to_string(value); +} +void append_inventory(std::string& out, const accounting::Inventory& inventory) { + append(out, inventory.energy.value); + for (const auto& channel : inventory.matter) { + out.push_back(','); + append(out, channel.value); + } +} +} // namespace + +std::string cellular_account_text(const LifeAccount& account) { + constexpr std::string_view digits = "0123456789abcdef"; + std::string out; + out.reserve(36); + for (std::size_t i = 0; i < account.size(); ++i) { + if (i == 4 || i == 6 || i == 8 || i == 10) + out.push_back('-'); + out.push_back(digits[account[i] >> 4U]); + out.push_back(digits[account[i] & 0x0FU]); + } + return out; +} + +std::string render_cellular_admin_view(const CellularLives& state, + const CellularAdminOnline& online, + CellularAdminViewLimits limits) { + const auto lives = state.lives(); + const auto patches = state.habitat().patches(); + std::string out; + out.reserve(256 + std::min(lives.size(), limits.cells) * 128 + + std::min(patches.size(), limits.deposits) * 64); + out += "{\"world\":"; + append(out, state.world()); + out += ",\"region\":"; + append(out, state.region()); + out += ",\"tick\":"; + append(out, state.tick()); + out += ",\"rules\":"; + append(out, state.rules_version()); + out += ",\"area\":["; + append(out, state.area().width_um); + out.push_back(','); + append(out, state.area().height_um); + out += "],\"spent\":["; + append_inventory(out, state.spent()); + out += "],\"cells_total\":"; + append(out, lives.size()); + out += ",\"deposits_total\":"; + append(out, patches.size()); + + // Lives are kept in ascending life id; a prefix is the lowest ids. + out += ",\"cells\":["; + const auto cells = std::min(lives.size(), limits.cells); + for (std::size_t i = 0; i < cells; ++i) { + const auto& life = lives[i]; + const bool wildlife = life.account == LifeAccount{}; + std::uint64_t flags = wildlife ? 1U : 0U; + if (!wildlife && online && online(life.account)) + flags |= 2U; + if (life.presence == CellularPresence::lingering) + flags |= 4U; + if (life.presence == CellularPresence::suspended) + flags |= 8U; + std::uint64_t body_mass{}; + for (const auto& channel : life.body.matter) + body_mass += channel.value; + if (i != 0) + out.push_back(','); + out += "[\""; + append(out, life.identity.life); + out += "\",\""; + append(out, life.identity.organism); + out += "\",\""; + if (!wildlife) + out += cellular_account_text(life.account); + out += "\","; + append(out, life.position.x_um); + out.push_back(','); + append(out, life.position.y_um); + out.push_back(','); + append(out, state.extent_of(life).value_or(0)); + out.push_back(','); + append(out, flags); + out.push_back(','); + append(out, life.revamp.members); + out.push_back(','); + append_inventory(out, life.reserve); + out.push_back(','); + append(out, body_mass); + out.push_back(']'); + } + + // Patches are kept by address; the view lists them by ascending id. + std::vector listed; + listed.reserve(patches.size()); + for (const auto& patch : patches) + listed.push_back(&patch); + const auto deposits = std::min(listed.size(), limits.deposits); + std::ranges::partial_sort(listed, listed.begin() + static_cast(deposits), {}, + [](const biology::CellularPatch* patch) { return patch->id; }); + out += "],\"deposits\":["; + for (std::size_t i = 0; i < deposits; ++i) { + const auto& patch = *listed[i]; + if (i != 0) + out.push_back(','); + out.push_back('['); + append(out, patch.id); + out.push_back(','); + append(out, static_cast(patch.kind)); + out.push_back(','); + append(out, patch.address.x_um); + out.push_back(','); + append(out, patch.address.y_um); + out.push_back(','); + append(out, patch.radius_um); + out.push_back(','); + append_inventory(out, patch.stock); + out.push_back(']'); + } + out += "]}\n"; + return out; +} +} // namespace evo::server diff --git a/src/server/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index f8629ac..7bf0f88 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -1127,6 +1127,13 @@ accounting::Inventory CellularLives::heat() const noexcept { accounting::Inventory CellularLives::spent() const noexcept { return state_->spent; } +std::optional CellularLives::extent_of(const CellularOwnedLife& life) const { + const auto budget = budget_for( + state_->archive, life, state_->config.ambient_temperature_millikelvin, state_->revamp.body); + if (!budget) + return std::nullopt; + return budget->phenotype.extent; +} accounting::Inventory CellularLives::opening_total() const noexcept { return state_->opening_total; } diff --git a/src/server/ops_http.cpp b/src/server/ops_http.cpp index 1f18f57..520d137 100644 --- a/src/server/ops_http.cpp +++ b/src/server/ops_http.cpp @@ -17,6 +17,8 @@ const char* reason(int status) { return "Bad Request"; case 401: return "Unauthorized"; + case 403: + return "Forbidden"; case 404: return "Not Found"; case 429: @@ -40,6 +42,7 @@ std::string encode(const OpsResponse& r) { out += "Allow: GET, POST\r\n"; if (r.status == 401) out += "WWW-Authenticate: Bearer\r\n"; + out += r.headers; return out + "\r\n" + r.body; } bool printable(std::string_view s) { @@ -50,7 +53,10 @@ bool printable(std::string_view s) { } } // namespace -std::expected, OpsError> OpsServer::listen(std::string_view address) { +std::expected, OpsError> OpsServer::listen(std::string_view address, + std::size_t response_limit) { + if (response_limit == 0 || response_limit > max_configurable_response_bytes) + return std::unexpected{OpsError::address}; const auto colon = address.rfind(':'); if (colon == std::string_view::npos || colon + 1 >= address.size()) return std::unexpected{OpsError::address}; @@ -96,7 +102,7 @@ std::expected, OpsError> OpsServer::listen(std::strin const auto actual = family == AF_INET6 ? ntohs(reinterpret_cast(&bound)->sin6_port) : ntohs(reinterpret_cast(&bound)->sin_port); - return std::unique_ptr(new OpsServer(fd, actual)); + return std::unique_ptr(new OpsServer(fd, actual, response_limit)); } OpsServer::~OpsServer() { @@ -123,7 +129,7 @@ void OpsServer::respond(Connection& c, const OpsHandler& handler) { else response = handler(path); } - if (response.body.size() > max_response_bytes) + if (response.body.size() > response_limit_) response = {500, "response too large\n"}; c.out = encode(response); } @@ -172,7 +178,7 @@ void OpsServer::respond_api(Connection& c, const ApiHandler& handler) { response = {400, "bad request\n"}; else response = handler({method, path, authorization}); - if (response.body.size() > max_response_bytes) + if (response.body.size() > response_limit_) response = {500, "response too large\n"}; c.out = encode(response); } diff --git a/tests/cellular_admin_view_tests.cpp b/tests/cellular_admin_view_tests.cpp new file mode 100644 index 0000000..2c2f689 --- /dev/null +++ b/tests/cellular_admin_view_tests.cpp @@ -0,0 +1,74 @@ +#include "evo/server/lifecycle/cellular_admin_view.hpp" +#include "fixtures/cellular_ecology.hpp" + +#include +#include + +// ADR-0182 admin region view: every cell and deposit of a cellular owner, read without change. +namespace { +using namespace evo; +using namespace evo::server; +using namespace evo::fixture; + +std::size_t count(const std::string& text, const std::string& part) { + std::size_t found = 0; + for (auto at = text.find(part); at != std::string::npos; at = text.find(part, at + 1)) + ++found; + return found; +} + +void renders_cells_and_deposits() { + const auto state = opening(7, true); + const auto before = state->snapshot(); + LifeAccount first{}; + first.back() = 1; + const auto view = render_cellular_admin_view( + *state, [&](const LifeAccount& account) { return account == first; }); + require(state->snapshot() == before, "rendering the view changed the owner"); + require(view.starts_with("{\"world\":207,\"region\":1,\"tick\":" + + std::to_string(state->tick()) + ",\"rules\":"), + "view header"); + require(view.ends_with("]}\n"), "view terminator"); + require(view.find("\"area\":[6000,6000]") != std::string::npos, "view area"); + require(view.find("\"cells_total\":4,") != std::string::npos, "cell total"); + require(view.find("\"deposits_total\":" + std::to_string(state->habitat().patches().size())) != + std::string::npos, + "deposit total"); + + // Four player cells, each with its account text; only the first is connected. + require(cellular_account_text(first) == "00000000-0000-0000-0000-000000000001", "account text"); + require(count(view, "[\"10") == 4, "every life listed with its id as a string"); + for (const auto& life : state->lives()) { + const auto extent = state->extent_of(life).value_or(0); + require(extent > 0, "a living cell has an extent"); + const auto row = + "[\"" + std::to_string(life.identity.life) + "\",\"" + + std::to_string(life.identity.organism) + "\",\"" + cellular_account_text(life.account) + + "\"," + std::to_string(life.position.x_um) + "," + std::to_string(life.position.y_um) + + "," + std::to_string(extent) + "," + (life.account == first ? "2" : "0") + ",1,"; + require(view.find(row) != std::string::npos, "cell row"); + } + + // Deposits by ascending id, and limits keep the lowest ids while totals stay complete. + const auto limited = render_cellular_admin_view(*state, {}, {.cells = 1, .deposits = 2}); + require(count(limited, "[\"10") == 1, "cell limit"); + require(limited.find("\"cells_total\":4,") != std::string::npos, "total beyond the limit"); + require(limited.find("\"deposits\":[[1,") != std::string::npos && + limited.find("],[2,") != std::string::npos && + limited.find("],[3,") == std::string::npos, + "deposit limit keeps ids 1 and 2"); + const auto none = render_cellular_admin_view(*state, {}, {.cells = 0, .deposits = 0}); + require(none.find("\"cells\":[],\"deposits\":[]}") != std::string::npos, "empty lists"); +} +} // namespace + +int main() { + try { + renders_cells_and_deposits(); + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } + std::puts("cellular admin view tests passed"); + return 0; +} diff --git a/tests/grant_broker_tests.cpp b/tests/grant_broker_tests.cpp index b45858f..146a288 100644 --- a/tests/grant_broker_tests.cpp +++ b/tests/grant_broker_tests.cpp @@ -1,8 +1,11 @@ // ADR-0131 grant broker: bounded JSON, offline RS256 access-token checks, and real // PostgreSQL schema v39 identities, serials and logout revocation. Isolated world 9831. +// ADR-0182 admin API: the admin realm role, the portal's files and the schema v61 read views +// over the same world. #include "evo/persistence/account_control_store.hpp" #include "evo/persistence/account_identity_store.hpp" #include "evo/persistence/region_lease_store.hpp" +#include "evo/server/admin/admin_api.hpp" #include "evo/server/broker/grant_broker.hpp" #include "evo/server/broker/json.hpp" @@ -194,6 +197,26 @@ void token_tests(const Realm& realm) { CHECK(failure(stranger.token(header, claims("user-a")), TokenError::bad_signature)); CHECK(failure("a.b", TokenError::malformed)); CHECK(failure(std::string(max_access_token_bytes + 1, 'a'), TokenError::malformed)); + + // ADR-0182: a required realm role, and the email returned for display. + auto admin_rules = rules(); + admin_rules.realm_role = "aevolution-admin"; + const auto admins = TokenVerifier::from_jwks(realm.jwks("sig-1"), admin_rules); + CHECK(admins); + const auto role = [&](std::string_view extra) { + return admins->verify(realm.token(header, claims("u", extra)), now); + }; + const auto granted = + role(R"(,"email":"ops@example.test","realm_access":{"roles":["x","aevolution-admin"]})"); + CHECK(granted && granted->email == "ops@example.test" && granted->subject == "u"); + CHECK(good->email.empty()); + for (const std::string_view without : + {"", R"(,"realm_access":{"roles":["x"]})", + R"(,"realm_access":{"roles":"aevolution-admin"})", R"(,"realm_access":{})", + R"(,"roles":["aevolution-admin"])"}) { + const auto refused = role(without); + CHECK(!refused && refused.error() == TokenError::missing_role); + } } struct Grant { @@ -331,6 +354,134 @@ void broker_tests(const Realm& realm) { // Runtime role cannot read or write identities except through the functions. CHECK(!region->query("SELECT count(*) FROM evolution.account_identities", {}, 5s)); } + +// ADR-0182 admin API over world 9831 as broker_tests left it: alice and bob have identities, +// alice holds session control in region 1, nobody has a life. +void admin_api_tests(const Realm& realm) { + using server::admin::AdminApi; + AccessTokenRules admin_rules{std::string(issuer), "aevolution-admin", "aevolution-admin-portal", + 30, "aevolution-admin"}; + const auto admin_claims = [](std::string_view subject, std::string_view roles) { + return claims(subject, + R"(,"email":"ops@example.test","realm_access":{"roles":)" + + std::string(roles) + "}", + R"(["account","aevolution-admin"])", "aevolution-admin-portal"); + }; + const auto admin = + "Bearer " + realm.token(header, admin_claims("ops", R"(["aevolution-admin"])")); + const auto player = "Bearer " + realm.token(header, admin_claims("ops", R"(["player"])")); + const auto game = "Bearer " + realm.token(header, claims("alice-sub")); + int connects = 0; + int fetches = 0; + const auto make = [&](bool online) { + server::admin::AdminConfig config; + config.world = 9831; + config.view_regions = {1, 3}; + config.portal_config_json = "{\"world\":9831}\n"; + config.content_security_policy = "default-src 'none'"; + return AdminApi{config, + *TokenVerifier::from_jwks(realm.jwks("sig-1"), admin_rules), + [&, online]() -> std::unique_ptr { + ++connects; + return online ? connect_as(env("EVO_PG_RUNTIME_USER")) : nullptr; + }, + [&](std::uint64_t region) -> std::optional { + ++fetches; + return region == 1 ? std::optional{"{\"region\":1}\n"} + : std::nullopt; + }, + {{"/index.html", "text/html; charset=utf-8", ""}, + {"/app.js", "text/javascript; charset=utf-8", "start();"}}}; + }; + auto api = make(true); + const auto t0 = std::chrono::steady_clock::time_point{} + 1h; + const auto get = [&](std::string_view path, const std::string& authorization = {}, + std::chrono::steady_clock::time_point at = {}) { + return api.handle({"GET", path, authorization}, now, at == decltype(at){} ? t0 : at); + }; + + // Public: health, the portal's files with their policy headers, and its settings. + CHECK(get("/healthz").status == 200); + const auto index = get("/"); + CHECK(index.status == 200 && index.body == "" && + index.content_type == "text/html; charset=utf-8" && + index.headers.find("Content-Security-Policy: default-src 'none'\r\n") == 0 && + index.headers.find("X-Content-Type-Options: nosniff\r\n") != std::string::npos); + CHECK(get("/app.js?v=2").body == "start();"); + CHECK(get("/style.css").status == 404 && get("/../etc/passwd").status == 404); + CHECK(get("/config.json").body == "{\"world\":9831}\n"); + CHECK(api.handle({"POST", "/api/me", admin}, now, t0).status == 405); + + // Every /api route needs an admin's token; nothing reaches the database before that. + CHECK(get("/api/accounts").status == 401); + const auto no_role = get("/api/accounts", player); + CHECK(no_role.status == 403 && no_role.body.find("not_an_admin") != std::string::npos); + const auto foreign = get("/api/accounts", game); + CHECK(foreign.status == 401 && + foreign.body.find("token_not_for_this_service") != std::string::npos); + CHECK(connects == 0); + const auto me = must(JsonValue::parse(get("/api/me", admin).body)); + CHECK(me.member("subject")->string() == "ops" && + me.member("email")->string() == "ops@example.test" && + me.member("world")->integer() == 9831); + + // Accounts: alice is connected to region 1; neither has a life yet. + const auto listed = get("/api/accounts", admin); + CHECK(listed.status == 200 && listed.content_type == "application/json"); + const auto accounts = must(JsonValue::parse(listed.body)); + CHECK(accounts.member("world")->integer() == 9831); + const JsonValue* alice = nullptr; + const JsonValue* bob = nullptr; + for (const auto& entry : *accounts.member("accounts")->array()) { + if (entry.member("subject")->string() == "alice-sub") + alice = &entry; + if (entry.member("subject")->string() == "bob-sub") + bob = &entry; + } + CHECK(alice && bob); + CHECK(alice->member("logged_in")->boolean() == true && + alice->member("control_region")->string() == "1" && + alice->member("status")->string() == "no_life" && + alice->member("lives")->integer() == 0 && alice->member("deaths")->integer() == 0 && + alice->member("resets")->integer() == 0 && + alice->member("mutation_choices")->integer() == 0 && + alice->member("issuer")->string() == issuer && alice->member("created_at")->integer()); + CHECK(bob->member("logged_in")->boolean() == false && + bob->member("control_region")->kind() == JsonValue::Kind::null); + const auto alice_id = std::string(must(alice->member("account")->string())); + const auto one = must(JsonValue::parse(get("/api/accounts/" + alice_id, admin).body)); + CHECK(one.member("account")->member("subject")->string() == "alice-sub" && + one.member("lives")->array() && one.member("lives")->array()->empty()); + CHECK(get("/api/accounts/00000000-0000-4000-8000-000000000000", admin).status == 404); + CHECK(get("/api/accounts/" + alice_id.substr(1), admin).status == 404); + CHECK(get("/api/accounts/" + std::string(36, 'A'), admin).status == 404); + + // Regions: the lease broker_tests took, and which views can be fetched. + const auto regions = must(JsonValue::parse(get("/api/regions", admin).body)); + const auto& region = regions.member("regions")->array()->at(0); + CHECK(region.member("region")->string() == "1" && region.member("frame")->string() == "7" && + region.member("lease_held")->boolean() == true && + region.member("viewable")->boolean() == true); + + // Views are cached briefly; unknown and unreachable regions are refused. + CHECK(get("/api/regions/1/view", admin).body == "{\"region\":1}\n" && fetches == 1); + CHECK(get("/api/regions/1/view", admin, t0 + 500ms).status == 200 && fetches == 1); + CHECK(get("/api/regions/1/view", admin, t0 + 800ms).status == 200 && fetches == 2); + CHECK(get("/api/regions/2/view", admin).status == 404 && fetches == 2); + CHECK(get("/api/regions/3/view", admin).status == 503 && fetches == 3); + CHECK(get("/api/regions/x/view", admin).status == 404 && + get("/api/other", admin).status == 404); + + // An unreachable database is a 503, retried on the next request. + auto offline = make(false); + CHECK(offline.handle({"GET", "/api/accounts", admin}, now, t0).status == 503); + CHECK(offline.handle({"GET", "/api/regions", admin}, now, t0).status == 503); + + // The read views are the only way in: the runtime role still cannot read the tables. + auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); + CHECK(!runtime->query("SELECT count(*) FROM evolution.life_reservations", {}, 5s)); + CHECK(server::admin::json_string("a\"b\\c\n\x01") == "\"a\\\"b\\\\c\\u000a\\u0001\""); +} } // namespace void run_grant_broker_tests() { @@ -338,4 +489,5 @@ void run_grant_broker_tests() { const Realm realm; token_tests(realm); broker_tests(realm); + admin_api_tests(realm); } diff --git a/tests/region_migration_tests.cpp b/tests/region_migration_tests.cpp index 1a34dbb..a561b30 100644 --- a/tests/region_migration_tests.cpp +++ b/tests/region_migration_tests.cpp @@ -226,6 +226,7 @@ void upgrade_across_migration_and_barrier() { " -v migration_sha_58=$(s 0058_liquid_bundle.sql)" " -v migration_sha_59=$(s 0059_durable_mutation_queue.sql)" " -v migration_sha_60=$(s 0060_cellular_revamp_bundle.sql)" + " -v migration_sha_61=$(s 0061_admin_read_views.sql)" " -v runtime_role=evo_runtime_test -f migrations/apply.sql" " > /dev/null 2>&1") != 0); CHECK(history(*owner_db) == "1,2,3,4,5,6,7"); @@ -243,7 +244,7 @@ void upgrade_across_migration_and_barrier() { "tools/migrate-postgres.sh\" > /dev/null") == 0); CHECK(history(*owner_db) == "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24," "25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46," - "47,48,49,50,51,52,53,54,55,56,57,58,59,60"); + "47,48,49,50,51,52,53,54,55,56,57,58,59,60,61"); CHECK(scalar(*owner_db, "SELECT (c.condeferrable AND c.condeferred AND " "c.confrelid = 'evolution.region_commits'::regclass)::text " "FROM pg_catalog.pg_constraint c WHERE c.conrelid = " diff --git a/tools/ci/history-domain-check.sh b/tools/ci/history-domain-check.sh index 2ad77bd..8f33789 100644 --- a/tools/ci/history-domain-check.sh +++ b/tools/ci/history-domain-check.sh @@ -75,6 +75,9 @@ awk '/^CREATE FUNCTION evolution\.(publish_cellular_checkpoint|publish_cellular_ awk '/^CREATE OR REPLACE FUNCTION evolution\.valid_cellular_action_input\(/ {capture=1} capture {print} capture && /^END \$\$;/ {capture=0}' \ "$root/migrations/0036_cellular_v5_budding_bundle.sql" | sql > /dev/null sql -v runtime_role="$EVO_PG_RUNTIME_ROLE" > /dev/null <<'SQL' +DROP FUNCTION evolution.admin_regions_v1(evolution.u64); +DROP FUNCTION evolution.admin_account_lives_v1(evolution.u64,uuid); +DROP FUNCTION evolution.admin_accounts_v1(evolution.u64); DROP FUNCTION evolution.publish_cellular_profile_migration(bytea); ALTER FUNCTION evolution.publish_cellular_profile_migration_v59(bytea) RENAME TO publish_cellular_profile_migration; DROP FUNCTION evolution.cellular_births(bytea,bytea); diff --git a/tools/ci/postgres-check.sh b/tools/ci/postgres-check.sh index 7b7c5f3..035e34e 100644 --- a/tools/ci/postgres-check.sh +++ b/tools/ci/postgres-check.sh @@ -168,7 +168,7 @@ PGDATABASE=upgrade_path psql -X -v ON_ERROR_STOP=1 -1 -v "migration_sha=$v1_sha" -f "$root/migrations/0001_region_bootstrap.sql" > /dev/null test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',') FROM evolution.schema_migrations")" = 1 PGDATABASE=upgrade_path bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60 +test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61 # v2 heads have no payload binding: v2->v3 fails closed and leaves history at v2. v2_sha="$(sha256sum "$root/migrations/0002_region_fencing.sql")" v2_sha="${v2_sha%% *}" @@ -189,7 +189,7 @@ PGDATABASE=v3_commits psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '01000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32), 'hex'))" > /dev/null PGDATABASE=v3_commits bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 60:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60 +test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 61:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61 test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) FROM evolution.region_commits")" = 1 # Review P1: a v4 database holding a published (possibly terminal) checkpoint has # no durable decisions for it. The v5 upgrade must refuse before changing anything. @@ -243,7 +243,7 @@ PGDATABASE=v6_populated psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '02000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32) || repeat('00', 80), 'hex'))" > /dev/null PGDATABASE=v6_populated bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60 +test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT count(*) FROM evolution.region_commits c, LATERAL evolution.parse_checkpoint_manifest(c.manifest) m WHERE m.commit_sequence = 0 AND m.predecessor_commit IS NULL")" = 1 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(conname, ',') FROM pg_constraint WHERE conrelid = 'evolution.region_heads'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%end_tick%'")" = region_heads_published_tick phase permission-audit @@ -301,9 +301,9 @@ expect_audit_failure 'REVOKE EXECUTE ON FUNCTION evolution.load_world_cellular_m expect_audit_failure 'GRANT EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) TO evo_runtime_test' 'REVOKE EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) FROM evo_runtime_test' phase checksum-drift # Unknown future versions and checksum drift must not be repaired silently. -psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=61 WHERE version=60' +psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=62 WHERE version=61' if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi -psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=60 WHERE version=61" +psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=61 WHERE version=62" psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=14" if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=13" diff --git a/tools/ci/server-image-smoke.sh b/tools/ci/server-image-smoke.sh index f4a22b2..b285681 100644 --- a/tools/ci/server-image-smoke.sh +++ b/tools/ci/server-image-smoke.sh @@ -26,12 +26,23 @@ if [[ "$code" -ne 2 ]] || ! grep -q '^usage: evo-world-clone ' <<<"$tool"; then printf 'evo-world-clone smoke failed (exit %s):\n%s\n' "$code" "$tool" >&2 exit 1 fi +# The admin API (ADR-0182) refuses to start without configuration, and its portal files ship. +set +e +admin="$(run --entrypoint /usr/local/bin/evo-admin-api "$image" 2>&1)" +code=$? +set -e +if [[ "$code" -ne 2 ]] || ! grep -q '^usage: evo-admin-api ' <<<"$admin"; then + printf 'evo-admin-api smoke failed (exit %s):\n%s\n' "$code" "$admin" >&2 + exit 1 +fi # Non-root, every shared library resolved, no credential material in the image. run --entrypoint /bin/sh "$image" -c ' set -eu test "$(id -u)" = 10001 && test "$(id -g)" = 10001 ! ldd /usr/local/bin/evo-server | grep -q "not found" ! ldd /usr/local/bin/evo-world-clone | grep -q "not found" + ! ldd /usr/local/bin/evo-admin-api | grep -q "not found" + for f in index.html app.js style.css; do test -s "/usr/local/share/evo-admin-portal/$f"; done test -z "$(find / -xdev \( -name "*pgpass*" -o -name "pg_service.conf" -o -name "*.pem" \ -o -name "*.key" \) -not -path "/etc/ssl/*" -not -path "/usr/lib/ssl/*" \ -not -path "/usr/share/*" -print 2>/dev/null)" diff --git a/tools/migrate-postgres.sh b/tools/migrate-postgres.sh index 4ebd519..0e5539a 100644 --- a/tools/migrate-postgres.sh +++ b/tools/migrate-postgres.sh @@ -132,6 +132,8 @@ digest_59="$(sha256sum "$root/migrations/0059_durable_mutation_queue.sql")" digest_59="${digest_59%% *}" digest_60="$(sha256sum "$root/migrations/0060_cellular_revamp_bundle.sql")" digest_60="${digest_60%% *}" +digest_61="$(sha256sum "$root/migrations/0061_admin_read_views.sql")" +digest_61="${digest_61%% *}" psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_2=$digest_2" --set="migration_sha_3=$digest_3" \ --set="migration_sha_4=$digest_4" --set="migration_sha_5=$digest_5" \ @@ -180,6 +182,6 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_53=$digest_53" --set="migration_sha_54=$digest_54" \ --set="migration_sha_55=$digest_55" --set="migration_sha_56=$digest_56" \ --set="migration_sha_57=$digest_57" --set="migration_sha_58=$digest_58" --set="migration_sha_59=$digest_59" \ - --set="migration_sha_60=$digest_60" \ + --set="migration_sha_60=$digest_60" --set="migration_sha_61=$digest_61" \ --set="runtime_role=$runtime_role" \ --file="$root/migrations/apply.sql"