From 070c458dc5249e4534b24ff9214281af1a55f872 Mon Sep 17 00:00:00 2001 From: dingo Date: Tue, 27 Oct 2026 17:50:34 -0400 Subject: [PATCH] feat(admin): bans, admin logout and time played (schema 64) ADR-0182 section 11. - Append-only account bans; a ban also revokes the account's grants (its live session closes at the next control renewal) and issue_account_grant refuses a banned account (EVL20 -> broker 403 account_banned). Lifting is another row. - admin_logout_account_v1 revokes by account id. - Session intervals recorded by claim/renew/release (signatures unchanged): time played, sessions and last seen per account. - The region view carries each cell's lineage root; the portal counts living wildlife descended from an account's lives. - Portal: Ban/Unban and Log out with reason and history; time played column. Co-Authored-By: Claude Opus 5.5 --- apps/evo-admin-api/portal/app.js | 62 ++++- docs/STATUS.md | 7 + .../adr/0182-admin-portal-and-world-tuning.md | 16 +- docs/engineering/VALIDATION.md | 18 ++ .../persistence/account_identity_store.hpp | 1 + include/evo/server/admin/admin_api.hpp | 7 +- .../server/lifecycle/cellular_admin_view.hpp | 11 +- migrations/0064_account_admin.sql | 223 ++++++++++++++++++ migrations/apply.sql | 26 +- src/persistence/region_lease_store.cpp | 2 + src/server/admin/admin_api.cpp | 88 ++++++- src/server/broker/grant_broker.cpp | 2 + src/server/lifecycle/cellular_admin_view.cpp | 4 +- tests/grant_broker_tests.cpp | 22 ++ tests/region_migration_tests.cpp | 3 +- tools/ci/history-domain-check.sh | 19 ++ tools/ci/postgres-check.sh | 10 +- tools/migrate-postgres.sh | 5 +- 18 files changed, 490 insertions(+), 36 deletions(-) create mode 100644 migrations/0064_account_admin.sql diff --git a/apps/evo-admin-api/portal/app.js b/apps/evo-admin-api/portal/app.js index 170b72a..f7d7305 100644 --- a/apps/evo-admin-api/portal/app.js +++ b/apps/evo-admin-api/portal/app.js @@ -57,6 +57,14 @@ function fmtAgo(seconds) { return `${Math.round(hr / 24)}d ago`; } const short = (id) => (id ? `${id.slice(0, 8)}…` : '—'); +function fmtDuration(seconds) { + const s = Math.max(0, Math.round(seconds || 0)); + if (s < 60) return `${s}s`; + const m = Math.floor(s / 60); + if (m < 60) return `${m}m ${s % 60}s`; + const hr = Math.floor(m / 60); + return hr < 48 ? `${hr}h ${m % 60}m` : `${Math.floor(hr / 24)}d ${hr % 24}h`; +} // ---------- Sign-in ---------- function b64url(bytes) { @@ -184,8 +192,9 @@ function table(columns, rows, { onRow, sortKey, sortUp = false } = {}) { } function statusBadge(a) { - return h('span', { class: `badge ${a.status === 'alive' ? 'alive' : a.status === 'dead' ? 'dead' : ''}` }, + const life = h('span', { class: `badge ${a.status === 'alive' ? 'alive' : a.status === 'dead' ? 'dead' : ''}` }, a.status === 'no_life' ? 'no life' : a.status); + return a.banned ? h('span', {}, life, ' ', h('span', { class: 'badge dead' }, 'banned')) : life; } function sessionBadge(a) { return a.logged_in ? h('span', { class: 'badge online' }, `online · region ${a.control_region}`) @@ -209,6 +218,7 @@ async function accountsPage() { { key: 'deaths', label: 'Deaths', num: true }, { key: 'resets', label: 'Resets', num: true }, { key: 'mutation_choices', label: 'Mutation choices', num: true }, + { key: 'played_seconds', label: 'Time played', num: true, render: (a) => fmtDuration(a.played_seconds) }, { key: 'created_at', label: 'Created', render: (a) => (a.created_at ? fmtAgo(a.created_at) : '—'), sort: (a) => a.created_at ?? 0 }, ]; const draw = () => { @@ -238,9 +248,49 @@ function stat(label, value, sub) { // persistence::LifeRefusal. const rejections = ['accepted', 'refused: not enough funding', 'refused: no placement', 'cancelled', 'refused: already alive']; +async function livingOffspring(identities) { + // Living wildlife whose lineage root is one of the account's lives, in every viewable region. + const roots = new Set(identities); + let count = 0; + try { + const regions = await api('/api/regions'); + for (const r of regions.regions.filter((x) => x.viewable)) { + try { + const view = await api(`/api/regions/${r.region}/view`); + count += view.cells.filter((c) => (c[6] & 1) && roots.has(c[14])).length; + } catch { /* region not ready */ } + } + } catch { return null; } + return count; +} + async function accountPage(id) { const data = await api(`/api/accounts/${id}`); const a = data.account; + const offspring = h('span', { class: 'muted' }, '…'); + livingOffspring(data.lives.filter((l) => l.born !== null).map((l) => l.identity)) + .then((n) => { offspring.textContent = n === null ? '—' : fmtInt(n); }); + const note = h('span', { class: 'muted small' }); + const reason = h('input', { type: 'text', maxlength: 200, placeholder: 'Reason (optional)' }); + const act = async (path, label, ask) => { + if (ask && !confirm(ask)) return; + try { + const q = new URLSearchParams(path.includes('?') ? path.split('?')[1] : ''); + if (reason.value.trim()) q.set('reason', reason.value.trim()); + await api(`/api/accounts/${a.account}/${path.split('?')[0]}?${q}`, true, 'POST'); + route(); + } catch (e) { note.textContent = `Could not ${label}: ${e.code || e.message}`; } + }; + const actions = h('div', { class: 'card' }, h('h2', {}, 'Account actions'), + h('div', { class: 'window-controls' }, + h('button', { onclick: () => act('logout', 'log out', `Log out ${short(a.account)} now? Its session closes within seconds.`) }, 'Log out'), + a.banned + ? h('button', { onclick: () => act('ban?banned=0', 'lift the ban') }, 'Lift ban') + : h('button', { class: 'danger', onclick: () => act('ban?banned=1', 'ban', `Ban ${short(a.account)}? It is logged out and cannot sign in to play.`) }, 'Ban')), + reason, note, + data.bans.length ? h('table', { class: 'compact' }, h('tbody', {}, data.bans.slice(0, 8).map((b) => + h('tr', {}, h('td', {}, fmtTime(b.at)), h('td', {}, b.banned ? h('span', { class: 'badge dead' }, 'banned') : 'lifted'), + h('td', { class: 'muted' }, (b.author || '').split(' (')[0]), h('td', { class: 'muted' }, b.reason || ''))))) : null); 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 || '—'), @@ -250,7 +300,9 @@ async function accountPage(id) { 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))); + h('dt', {}, 'Created'), h('dd', {}, fmtTime(a.created_at)), + h('dt', {}, 'Last seen'), h('dd', {}, a.last_seen ? `${fmtTime(a.last_seen)} (${fmtAgo(a.last_seen)})` : '—'), + h('dt', {}, 'Living offspring'), h('dd', {}, offspring, h('span', { class: 'muted' }, ' wildlife descended from its lives'))); const lives = table([ { key: 'request', label: 'Request', sort: (l) => Number(l.request) }, { key: 'identity', label: 'Life', render: (l) => h('span', { class: 'mono' }, l.identity) }, @@ -265,10 +317,12 @@ async function accountPage(id) { 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))), + stat('Mutation choices', fmtInt(a.mutation_choices)), + stat('Time played', fmtDuration(a.played_seconds), `${fmtInt(a.sessions)} sessions`)), h('div', { class: 'card' }, facts), + actions, h('h2', {}, 'Lives'), lives, - h('p', { class: 'muted' }, 'Time played, bans, current mutations and living offspring arrive with the next admin phase (ADR-0182).')); + h('p', { class: 'muted' }, 'Time played counts sessions from schema 64 on; earlier play is not recorded.')); } async function regionsPage() { diff --git a/docs/STATUS.md b/docs/STATUS.md index 3c3499b..37bd807 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,12 @@ # Project status and next steps +## Account administration: bans, logout, time played - 2026-10-27 + +The admin portal can ban (and unban) an account, which also logs it out and stops new +grants; log an account out; and shows time played, sessions, last seen and living +offspring (wildlife descended from its lives). Schema 64; see +[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 11. + ## Admin commands: spawn wildlife, resources, remove and grant - 2026-10-27 The admin portal can now spawn wildlife, add bubbles, add to or release the spent pool, diff --git a/docs/adr/0182-admin-portal-and-world-tuning.md b/docs/adr/0182-admin-portal-and-world-tuning.md index 45b6c42..e2a6515 100644 --- a/docs/adr/0182-admin-portal-and-world-tuning.md +++ b/docs/adr/0182-admin-portal-and-world-tuning.md @@ -204,8 +204,22 @@ The commands of section 3 are delivered without a new owner format or region ope per-cell Remove and Grant reserve, and the command history with the tick each applied at. Amounts are entered in µJ and ng. +### 11. Account administration (delivered, schema 64) + +- **Bans.** Append-only `account_bans` rows; the newest per account decides. A banned + account's grant request fails with SQLSTATE EVL20 (the broker answers 403 + `account_banned`), and banning also revokes its grants, so a live session closes at its + next control renewal. Lifting a ban is another row. +- **Logout.** `admin_logout_account_v1` revokes by account id, as the player's own logout + does by Keycloak identity. +- **Time played.** The session-control functions keep their signatures and also record + `session_intervals`: a claim opens one, a renewal moves its last-seen time, a release ends + it; an unreleased session ends at its last renewal. History starts with schema 64. +- **Living offspring.** The region view adds each cell's lineage root; the portal counts + living wildlife whose root is one of the account's lives. + Still pending from this ADR: drip/source settings (section 4), tuning amendments -(sections 1-2), data-defined mutations (section 5), bans and time played (section 6). +(sections 1-2), data-defined mutations (section 5) and the account's current mutations. ## Delivery order diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index f35183c..2b88986 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -10541,3 +10541,21 @@ Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, build/m97-postgres): Limits: no live region has applied a command yet; the portal's command forms were not driven in a browser. + +## 2026-10-27 - Account administration (schema 64) + +Scope: ADR-0182 section 11. Bans (append-only, a ban also revokes grants), an admin logout, +time played from session intervals recorded by the unchanged-signature control functions, +the broker's 403 `account_banned`, and each cell's lineage root in the region view for the +portal's living-offspring count. No simulation, trace, checkpoint or wire change. + +Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, build/m97-postgres): full build; CTest +119/119; `tools/ci/postgres-check.sh --full` passed (637 s, every phase, including the +schema-50 rewind restoring the four wrapped control and grant functions, the permission +audit and checksum drift with the probe at 65). New PostgreSQL cases: sessions recorded from +the broker test's control claims, ban with reason (listed in the account and its history), +`issue_account_grant` refused with the banned error while banned and allowed after lifting, +admin logout, refused shapes (bad flag, unknown action, POST on the account itself). + +Limits: no live ban or logout was exercised against a connected client; time played starts +at this schema. diff --git a/include/evo/persistence/account_identity_store.hpp b/include/evo/persistence/account_identity_store.hpp index 972aae1..920eb57 100644 --- a/include/evo/persistence/account_identity_store.hpp +++ b/include/evo/persistence/account_identity_store.hpp @@ -12,6 +12,7 @@ namespace evo::persistence { enum class AccountIdentityError : std::uint8_t { invalid, // Arguments refused. + banned, // ADR-0182: the account is banned (schema 64); nothing changed. store, // Other failure; nothing changed. unknown // May have executed: reconnect before relying on the serial. }; diff --git a/include/evo/server/admin/admin_api.hpp b/include/evo/server/admin/admin_api.hpp index 7e89765..93ade68 100644 --- a/include/evo/server/admin/admin_api.hpp +++ b/include/evo/server/admin/admin_api.hpp @@ -23,7 +23,9 @@ // 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/accounts/ one account, its life requests and ban history +// POST /api/accounts//ban?banned=1|0[&reason=R] bans (and logs out) or lifts a ban +// POST /api/accounts//logout ends the account's sessions now // GET /api/regions the world's regions, leases and heads // GET /api/regions//view the region's live view (render_cellular_admin_view) // GET /api/regions//session-window the current session window and its last changes @@ -66,6 +68,9 @@ class AdminApi { std::string_view query, const broker::AccessTokenClaims& admin, std::chrono::steady_clock::time_point now); [[nodiscard]] OpsResponse accounts(std::optional account); + [[nodiscard]] OpsResponse account_action(std::string_view account, std::string_view action, + std::string_view query, + const broker::AccessTokenClaims& admin); [[nodiscard]] OpsResponse regions(); [[nodiscard]] OpsResponse view(std::uint64_t region, std::chrono::steady_clock::time_point now); [[nodiscard]] OpsResponse window(std::uint64_t region); diff --git a/include/evo/server/lifecycle/cellular_admin_view.hpp b/include/evo/server/lifecycle/cellular_admin_view.hpp index cdb6334..e2b02c9 100644 --- a/include/evo/server/lifecycle/cellular_admin_view.hpp +++ b/include/evo/server/lifecycle/cellular_admin_view.hpp @@ -13,15 +13,16 @@ // {"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],...], +// reserve_e,reserve_c,reserve_n,reserve_p,reserve_o,body_mass,"root"],...], // "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. +// is the lowercase UUID, empty for wildlife; `root` the lineage root (the founder whose life +// request a lineage descends from, cellular_lineage_root). 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}; diff --git a/migrations/0064_account_admin.sql b/migrations/0064_account_admin.sql new file mode 100644 index 0000000..3adde0b --- /dev/null +++ b/migrations/0064_account_admin.sql @@ -0,0 +1,223 @@ +-- Account administration (ADR-0182 section 6, 2026-10-27): bans, an admin logout and time +-- played. A ban is an append-only row; the newest row per account decides. A banned account +-- gets no grant (SQLSTATE EVL20, which the broker reports as account_banned), and banning +-- also revokes its grants, so a live session closes at its next control renewal. Session +-- intervals are recorded by the session-control functions the regions already call: a claim +-- opens one, a renewal moves its last-seen time, a release closes it. A session that is +-- never released ends at its last renewal. + +CREATE TABLE evolution.account_bans ( + sequence bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + account_id uuid NOT NULL, + banned boolean NOT NULL, + author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255), + reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX account_bans_by_account ON evolution.account_bans(account_id, sequence); +CREATE TRIGGER account_bans_immutable BEFORE UPDATE OR DELETE ON evolution.account_bans + FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite(); + +CREATE TABLE evolution.session_intervals ( + world_id evolution.u64 NOT NULL, + account_id uuid NOT NULL, + generation evolution.u64 NOT NULL, + region_id evolution.u64 NOT NULL, + started_at timestamptz NOT NULL, + last_seen timestamptz NOT NULL, + ended_at timestamptz, + PRIMARY KEY (world_id, account_id, generation) +); + +CREATE FUNCTION evolution.account_banned(p_account uuid) +RETURNS boolean LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$ + SELECT coalesce((SELECT b.banned FROM evolution.account_bans b + WHERE b.account_id = p_account ORDER BY b.sequence DESC LIMIT 1), false) +$$; +REVOKE ALL ON FUNCTION evolution.account_banned(uuid) FROM PUBLIC; + +-- Raises the account's accepted serial past every grant issued and expires its control, as +-- revoke_account_grants does for a Keycloak identity. +CREATE FUNCTION evolution.revoke_account_by_id(p_world evolution.u64, p_account uuid) +RETURNS boolean LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$ +DECLARE r evolution.account_identities%ROWTYPE; +BEGIN + SELECT * INTO r FROM evolution.account_identities x WHERE x.account_id = p_account FOR UPDATE; + IF NOT FOUND THEN + UPDATE evolution.account_controls a + SET expires_at = CASE WHEN a.region_id IS NULL THEN NULL + ELSE least(a.expires_at, clock_timestamp()) END + WHERE a.world_id = p_world AND a.account_id = p_account; + RETURN FOUND; + END IF; + INSERT INTO evolution.account_controls AS a (world_id, account_id, serial, generation) + VALUES (p_world, r.account_id, greatest(r.last_serial, 1), 1) + ON CONFLICT (world_id, account_id) DO UPDATE + SET serial = greatest(a.serial, EXCLUDED.serial), + expires_at = CASE WHEN a.region_id IS NULL THEN NULL + ELSE least(a.expires_at, clock_timestamp()) END; + RETURN true; +END $$; +REVOKE ALL ON FUNCTION evolution.revoke_account_by_id(evolution.u64, uuid) FROM PUBLIC; + +-- Admin: ban or lift a ban (recorded with who and why); a ban also logs the account out. +CREATE FUNCTION evolution.admin_set_account_ban_v1(p_world evolution.u64, p_account uuid, + p_banned boolean, p_subject text, p_reason text) +RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +BEGIN + IF p_world IS NULL OR p_world = 0 OR p_account IS NULL OR p_banned IS NULL THEN + RAISE EXCEPTION 'invalid ban' USING ERRCODE = '22023'; + END IF; + INSERT INTO evolution.account_bans(account_id, banned, author_subject, reason) + VALUES (p_account, p_banned, p_subject, coalesce(p_reason, '')); + IF p_banned THEN + PERFORM evolution.revoke_account_by_id(p_world, p_account); + END IF; + RETURN p_banned; +END $$; +REVOKE ALL ON FUNCTION evolution.admin_set_account_ban_v1(evolution.u64, uuid, boolean, text, text) + FROM PUBLIC; + +-- Admin: end the account's sessions now (its next login needs a new grant). +CREATE FUNCTION evolution.admin_logout_account_v1(p_world evolution.u64, p_account uuid) +RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +BEGIN + IF p_world IS NULL OR p_world = 0 OR p_account IS NULL THEN + RAISE EXCEPTION 'invalid account' USING ERRCODE = '22023'; + END IF; + RETURN evolution.revoke_account_by_id(p_world, p_account); +END $$; +REVOKE ALL ON FUNCTION evolution.admin_logout_account_v1(evolution.u64, uuid) FROM PUBLIC; + +-- Admin: each account's ban state, time played and last session activity in the world. +CREATE FUNCTION evolution.admin_account_status_v1(p_world evolution.u64) +RETURNS TABLE (account_id uuid, banned boolean, played_seconds bigint, last_seen timestamptz, + sessions 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 s.account_id FROM evolution.session_intervals s WHERE s.world_id = p_world + UNION SELECT b.account_id FROM evolution.account_bans b + ) + SELECT a.account_id, evolution.account_banned(a.account_id), + coalesce((SELECT floor(sum(extract(epoch FROM coalesce(s.ended_at, s.last_seen) + - s.started_at)))::bigint + FROM evolution.session_intervals s + WHERE s.world_id = p_world AND s.account_id = a.account_id), 0), + (SELECT max(coalesce(s.ended_at, s.last_seen)) FROM evolution.session_intervals s + WHERE s.world_id = p_world AND s.account_id = a.account_id), + (SELECT count(*) FROM evolution.session_intervals s + WHERE s.world_id = p_world AND s.account_id = a.account_id) + FROM accounts a + LIMIT 10000 +$$; +REVOKE ALL ON FUNCTION evolution.admin_account_status_v1(evolution.u64) FROM PUBLIC; + +-- Admin: one account's ban history, newest first. +CREATE FUNCTION evolution.admin_account_bans_v1(p_account uuid) +RETURNS TABLE (banned boolean, author_subject text, reason text, created_at timestamptz) +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ + SELECT b.banned, b.author_subject, b.reason, b.created_at FROM evolution.account_bans b + WHERE b.account_id = p_account ORDER BY b.sequence DESC LIMIT 50 +$$; +REVOKE ALL ON FUNCTION evolution.admin_account_bans_v1(uuid) FROM PUBLIC; + +-- A banned account gets no grant. +ALTER FUNCTION evolution.issue_account_grant(evolution.u64, text, text) + RENAME TO issue_account_grant_v63; +REVOKE ALL ON FUNCTION evolution.issue_account_grant_v63(evolution.u64, text, text) + FROM PUBLIC, :"runtime_role"; +CREATE FUNCTION evolution.issue_account_grant(p_world evolution.u64, p_issuer text, + p_subject text) +RETURNS TABLE(grant_account uuid, grant_serial evolution.u64, home_region evolution.u64) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE known uuid; +BEGIN + SELECT x.account_id INTO known FROM evolution.account_identities x + WHERE x.issuer = p_issuer AND x.subject = p_subject; + IF known IS NOT NULL AND evolution.account_banned(known) THEN + RAISE EXCEPTION 'account banned' USING ERRCODE = 'EVL20'; + END IF; + RETURN QUERY SELECT * FROM evolution.issue_account_grant_v63(p_world, p_issuer, p_subject); +END $$; +REVOKE ALL ON FUNCTION evolution.issue_account_grant(evolution.u64, text, text) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION evolution.issue_account_grant(evolution.u64, text, text) + TO :"runtime_role"; + +-- Session intervals from the control functions (signatures unchanged). +ALTER FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid, evolution.u64, + uuid, evolution.u64, evolution.u64, integer) RENAME TO claim_account_control_v63; +REVOKE ALL ON FUNCTION evolution.claim_account_control_v63(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64, evolution.u64, integer) FROM PUBLIC, :"runtime_role"; +CREATE FUNCTION evolution.claim_account_control(p_world evolution.u64, p_region evolution.u64, + p_holder uuid, p_epoch evolution.u64, p_account uuid, p_serial evolution.u64, + p_session evolution.u64, p_duration_ms integer) +RETURNS TABLE (control_generation evolution.u64, wait_ms integer, granted_ms integer) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE r record; +BEGIN + FOR r IN SELECT * FROM evolution.claim_account_control_v63(p_world, p_region, p_holder, + p_epoch, p_account, p_serial, p_session, p_duration_ms) LOOP + IF r.granted_ms > 0 THEN + INSERT INTO evolution.session_intervals(world_id, account_id, generation, region_id, + started_at, last_seen) + VALUES (p_world, p_account, r.control_generation, p_region, clock_timestamp(), + clock_timestamp()) + ON CONFLICT (world_id, account_id, generation) DO NOTHING; + END IF; + control_generation := r.control_generation; + wait_ms := r.wait_ms; + granted_ms := r.granted_ms; + RETURN NEXT; + END LOOP; +END $$; +REVOKE ALL ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64, evolution.u64, integer) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64, evolution.u64, integer) TO :"runtime_role"; + +ALTER FUNCTION evolution.renew_account_control(evolution.u64, evolution.u64, uuid, evolution.u64, + uuid, evolution.u64, integer) RENAME TO renew_account_control_v63; +REVOKE ALL ON FUNCTION evolution.renew_account_control_v63(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64, integer) FROM PUBLIC, :"runtime_role"; +CREATE FUNCTION evolution.renew_account_control(p_world evolution.u64, p_region evolution.u64, + p_holder uuid, p_epoch evolution.u64, p_account uuid, p_generation evolution.u64, + p_duration_ms integer) +RETURNS integer LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE granted integer; +BEGIN + granted := evolution.renew_account_control_v63(p_world, p_region, p_holder, p_epoch, p_account, + p_generation, p_duration_ms); + UPDATE evolution.session_intervals s SET last_seen = clock_timestamp() + WHERE s.world_id = p_world AND s.account_id = p_account AND s.generation = p_generation + AND s.ended_at IS NULL; + RETURN granted; +END $$; +REVOKE ALL ON FUNCTION evolution.renew_account_control(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64, integer) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION evolution.renew_account_control(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64, integer) TO :"runtime_role"; + +ALTER FUNCTION evolution.release_account_control(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64) RENAME TO release_account_control_v63; +REVOKE ALL ON FUNCTION evolution.release_account_control_v63(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64) FROM PUBLIC, :"runtime_role"; +CREATE FUNCTION evolution.release_account_control(p_world evolution.u64, p_region evolution.u64, + p_holder uuid, p_epoch evolution.u64, p_account uuid, p_generation evolution.u64) +RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE released boolean; +BEGIN + released := evolution.release_account_control_v63(p_world, p_region, p_holder, p_epoch, + p_account, p_generation); + UPDATE evolution.session_intervals s SET last_seen = clock_timestamp(), + ended_at = clock_timestamp() + WHERE s.world_id = p_world AND s.account_id = p_account AND s.generation = p_generation + AND s.ended_at IS NULL; + RETURN released; +END $$; +REVOKE ALL ON FUNCTION evolution.release_account_control(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION evolution.release_account_control(evolution.u64, evolution.u64, uuid, + evolution.u64, uuid, evolution.u64) TO :"runtime_role"; + +INSERT INTO evolution.schema_migrations(version,sha256) VALUES(64,:'migration_sha_64'); diff --git a/migrations/apply.sql b/migrations/apply.sql index f73c309..849ee55 100644 --- a/migrations/apply.sql +++ b/migrations/apply.sql @@ -139,6 +139,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') SELECT :'history_v60' || ',61:' || :'migration_sha_61' AS history_v61 \gset SELECT :'history_v61' || ',62:' || :'migration_sha_62' AS history_v62 \gset SELECT :'history_v62' || ',63:' || :'migration_sha_63' AS history_v63 \gset + SELECT :'history_v63' || ',64:' || :'migration_sha_64' AS history_v64 \gset SELECT :'history' = :'history_v22' AS at_v22, :'history' = :'history_v23' AS at_v23, :'history' = :'history_v24' AS at_v24, @@ -180,8 +181,10 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') :'history' = :'history_v60' AS at_v60, :'history' = :'history_v61' AS at_v61, :'history' = :'history_v62' AS at_v62, - :'history' = :'history_v63' AS at_v63 \gset - \if :at_v63 + :'history' = :'history_v63' AS at_v63, + :'history' = :'history_v64' AS at_v64 \gset + \if :at_v64 + \elif :at_v63 \elif :at_v62 \elif :at_v61 \elif :at_v60 @@ -601,7 +604,8 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, coalesce(max(version), 0) = 60 AS at_v60, coalesce(max(version), 0) = 61 AS at_v61, coalesce(max(version), 0) = 62 AS at_v62, - coalesce(max(version), 0) = 63 AS at_v63 + coalesce(max(version), 0) = 63 AS at_v63, + coalesce(max(version), 0) = 64 AS at_v64 FROM evolution.schema_migrations \gset \if :at_v24 \ir 0025_cellular_v2_bundle.sql @@ -833,6 +837,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \elif :at_v61 \elif :at_v62 \elif :at_v63 +\elif :at_v64 \else \echo 'Unknown or changed migration history after v43' DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$; @@ -917,6 +922,10 @@ SELECT coalesce(max(version), 0) = 62 AS needs_v63 FROM evolution.schema_migrati \if :needs_v63 \ir 0063_admin_commands.sql \endif +SELECT coalesce(max(version), 0) = 63 AS needs_v64 FROM evolution.schema_migrations \gset +\if :needs_v64 + \ir 0064_account_admin.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 @@ -1065,6 +1074,11 @@ GRANT EXECUTE ON FUNCTION evolution.admin_enqueue_command_v1(evolution.u64, evol evolution.u64, text, text) TO :"admin_role"; GRANT EXECUTE ON FUNCTION evolution.admin_commands_v1(evolution.u64, evolution.u64) TO :"admin_role"; +GRANT EXECUTE ON FUNCTION evolution.admin_set_account_ban_v1(evolution.u64, uuid, boolean, text, + text) TO :"admin_role"; +GRANT EXECUTE ON FUNCTION evolution.admin_logout_account_v1(evolution.u64, uuid) TO :"admin_role"; +GRANT EXECUTE ON FUNCTION evolution.admin_account_status_v1(evolution.u64) TO :"admin_role"; +GRANT EXECUTE ON FUNCTION evolution.admin_account_bans_v1(uuid) TO :"admin_role"; SELECT pg_catalog.set_config('evolution.admin_role', :'admin_role', true); DO $$ DECLARE @@ -1089,7 +1103,11 @@ BEGIN ('evolution.admin_session_windows_v1(evolution.u64,evolution.u64)'::regprocedure::oid), ('evolution.admin_set_session_window_v1(evolution.u64,evolution.u64,integer,text,text)'::regprocedure::oid), ('evolution.admin_enqueue_command_v1(evolution.u64,evolution.u64,integer,integer,evolution.u64,evolution.u64,evolution.u64,evolution.u64,evolution.u64,evolution.u64,text,text)'::regprocedure::oid), - ('evolution.admin_commands_v1(evolution.u64,evolution.u64)'::regprocedure::oid) + ('evolution.admin_commands_v1(evolution.u64,evolution.u64)'::regprocedure::oid), + ('evolution.admin_set_account_ban_v1(evolution.u64,uuid,boolean,text,text)'::regprocedure::oid), + ('evolution.admin_logout_account_v1(evolution.u64,uuid)'::regprocedure::oid), + ('evolution.admin_account_status_v1(evolution.u64)'::regprocedure::oid), + ('evolution.admin_account_bans_v1(uuid)'::regprocedure::oid) ), violations(reason) AS ( SELECT 'admin role is the runtime role' WHERE admin = runtime UNION ALL diff --git a/src/persistence/region_lease_store.cpp b/src/persistence/region_lease_store.cpp index bfea415..10da99e 100644 --- a/src/persistence/region_lease_store.cpp +++ b/src/persistence/region_lease_store.cpp @@ -1449,6 +1449,8 @@ AccountIdentityError identity_failure(const PgFailure& f) { return AccountIdentityError::unknown; if (f.kind == PgError::config || f.kind == PgError::bounds || state == "22023") return AccountIdentityError::invalid; + if (state == "EVL20") + return AccountIdentityError::banned; return AccountIdentityError::store; } } // namespace diff --git a/src/server/admin/admin_api.cpp b/src/server/admin/admin_api.cpp index f5afe41..ba88ef0 100644 --- a/src/server/admin/admin_api.cpp +++ b/src/server/admin/admin_api.cpp @@ -76,7 +76,8 @@ const std::optional& at(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. + // 6 logged in, 7 lives, 8 deaths, 9 active life, 10 active region, 11 mutation choices, + // 12 banned, 13 seconds played, 14 last seen, 15 sessions. 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"; @@ -90,14 +91,21 @@ std::string account_json(const std::vector>& row) { ",\"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)) + "}"; + ",\"mutation_choices\":" + count_value(at(row, 11)) + + ",\"banned\":" + (at(row, 12) == "t" ? "true" : "false") + + ",\"played_seconds\":" + (at(row, 13) ? count_value(at(row, 13)) : "0") + + ",\"last_seen\":" + seconds_value(at(row, 14)) + + ",\"sessions\":" + (at(row, 15) ? count_value(at(row, 15)) : "0") + "}"; } 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)"; + "SELECT a.account_id::text, floor(extract(epoch FROM a.created_at))::bigint, a.issuer, " + "a.subject, a.control_region, floor(extract(epoch FROM a.control_expires))::bigint, " + "a.control_expires > clock_timestamp(), a.lives, a.deaths, a.active_life, a.active_region, " + "a.mutation_choices, s.banned, s.played_seconds, floor(extract(epoch FROM " + "s.last_seen))::bigint, " + "s.sessions FROM evolution.admin_accounts_v1($1) a " + "LEFT JOIN evolution.admin_account_status_v1($1) s ON s.account_id = a.account_id"; struct Socket { int fd{-1}; @@ -264,10 +272,13 @@ OpsResponse AdminApi::handle(const ApiRequest& request, std::uint64_t now_second auto path = request.path.substr(0, mark); const auto query = mark == std::string_view::npos ? std::string_view{} : request.path.substr(mark + 1); - // Only session windows and commands accept POST; everything else is read-only. + // Only session windows, commands and account actions accept POST. if (request.method != "GET" && - !(request.method == "POST" && path.starts_with("/api/regions/") && - (path.ends_with("/session-window") || path.ends_with("/commands")))) + !(request.method == "POST" && + ((path.starts_with("/api/regions/") && + (path.ends_with("/session-window") || path.ends_with("/commands"))) || + (path.starts_with("/api/accounts/") && + (path.ends_with("/ban") || path.ends_with("/logout")))))) return {405, "method not allowed\n"}; if (path == "/healthz") return {200, "ok\n"}; @@ -310,8 +321,15 @@ OpsResponse AdminApi::api(std::string_view method, std::string_view path, std::s 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"); + const auto rest = path.substr(account_prefix.size()); + const auto slash = rest.find('/'); + const auto id = rest.substr(0, slash); + if (!is_uuid(id)) + return error(404, "not_found"); + if (slash == std::string_view::npos) + return method == "GET" ? accounts(id) : error(405, "method_not_allowed"); + return method == "POST" ? account_action(id, rest.substr(slash + 1), query, admin) + : error(405, "method_not_allowed"); } if (path == "/api/regions") return regions(); @@ -369,7 +387,7 @@ OpsResponse AdminApi::accounts(std::optional account) { return json(200, out + "]}\n"); } const auto rows = - query(accounts_sql + " WHERE account_id = $2::uuid", {world, std::string(*account)}); + query(accounts_sql + " WHERE a.account_id = $2::uuid", {world, std::string(*account)}); if (!rows) return error(503, "unavailable"); if (rows->empty()) @@ -380,8 +398,21 @@ OpsResponse AdminApi::accounts(std::optional account) { {world, std::string(*account)}); if (!lives) return error(503, "unavailable"); + const auto bans = query("SELECT banned, author_subject, reason, " + "floor(extract(epoch FROM created_at))::bigint " + "FROM evolution.admin_account_bans_v1($1::uuid)", + {std::string(*account)}); + if (!bans) + return error(503, "unavailable"); std::string out = - "{\"world\":" + world + ",\"account\":" + account_json(rows->front()) + ",\"lives\":["; + "{\"world\":" + world + ",\"account\":" + account_json(rows->front()) + ",\"bans\":["; + for (std::size_t i = 0; i < bans->size(); ++i) { + const auto& row = (*bans)[i]; + out += std::string(i == 0 ? "" : ",") + "{\"banned\":" + bool_value(at(row, 0)) + + ",\"author\":" + text_value(at(row, 1)) + ",\"reason\":" + text_value(at(row, 2)) + + ",\"at\":" + seconds_value(at(row, 3)) + "}"; + } + out += "],\"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)) + @@ -393,6 +424,37 @@ OpsResponse AdminApi::accounts(std::optional account) { return json(200, out + "]}\n"); } +OpsResponse AdminApi::account_action(std::string_view account, std::string_view action, + std::string_view query_text, + const broker::AccessTokenClaims& admin) { + const auto world = std::to_string(config_.world); + if (action == "logout") { + const auto rows = query("SELECT evolution.admin_logout_account_v1($1, $2::uuid)", + {world, std::string(account)}); + if (!rows || rows->empty()) + return error(503, "unavailable"); + return json(200, "{\"logged_out\":" + bool_value(at(rows->front(), 0)) + "}\n"); + } + if (action != "ban") + return error(404, "not_found"); + const auto banned = query_value(query_text, "banned", 1); + if (!banned || (*banned != "0" && *banned != "1")) + return error(400, "bad_banned"); + const auto reason = query_value(query_text, "reason"); + if (!reason && query_text.find("reason=") != std::string_view::npos) + return error(400, "bad_reason"); + auto author = admin.email.empty() ? admin.subject : admin.email + " (" + admin.subject + ")"; + if (author.size() > 255) + author = admin.subject; + const auto rows = query("SELECT evolution.admin_set_account_ban_v1($1, $2::uuid, $3::boolean, " + "$4, $5)", + {world, std::string(account), *banned == "1" ? "true" : "false", author, + reason.value_or("")}); + if (!rows || rows->empty()) + return error(503, "unavailable"); + return json(200, "{\"banned\":" + bool_value(at(rows->front(), 0)) + "}\n"); +} + OpsResponse AdminApi::regions() { const auto world = std::to_string(config_.world); const auto rows = diff --git a/src/server/broker/grant_broker.cpp b/src/server/broker/grant_broker.cpp index 1055561..c8f73cc 100644 --- a/src/server/broker/grant_broker.cpp +++ b/src/server/broker/grant_broker.cpp @@ -97,6 +97,8 @@ OpsResponse GrantBroker::issue(const AccessTokenClaims& claims, std::uint64_t no const auto issued = persistence::issue_account_grant(*db, config_.world, claims.issuer, claims.subject, config_.db_timeout); if (!issued) { + if (issued.error() == persistence::AccountIdentityError::banned) + return error(403, "account_banned"); if (issued.error() != persistence::AccountIdentityError::invalid) db_.reset(); return error(503, "unavailable"); diff --git a/src/server/lifecycle/cellular_admin_view.cpp b/src/server/lifecycle/cellular_admin_view.cpp index 0d3a958..43f99d8 100644 --- a/src/server/lifecycle/cellular_admin_view.cpp +++ b/src/server/lifecycle/cellular_admin_view.cpp @@ -98,7 +98,9 @@ std::string render_cellular_admin_view(const CellularLives& state, append_inventory(out, life.reserve); out.push_back(','); append(out, body_mass); - out.push_back(']'); + out += ",\""; + append(out, cellular_lineage_root(state, life.identity.life)); + out += "\"]"; } // Patches are kept by address; the view lists them by ascending id. diff --git a/tests/grant_broker_tests.cpp b/tests/grant_broker_tests.cpp index a887101..2a008e4 100644 --- a/tests/grant_broker_tests.cpp +++ b/tests/grant_broker_tests.cpp @@ -587,6 +587,28 @@ void admin_api_tests(const Realm& realm) { CHECK(!reader->query("DELETE FROM evolution.admin_commands", {}, 5s)); } + // Accounts (schema 64): control claims recorded alice's sessions; a ban refuses grants + // and is listed with its reason; lifting it restores them; an admin logout succeeds. + CHECK(alice->member("sessions")->integer().value_or(0) >= 1 && + alice->member("banned")->boolean() == false); + const auto alice_path = "/api/accounts/" + alice_id; + CHECK(post(alice_path + "/ban?banned=2").status == 400); + CHECK(post(alice_path + "/other").status == 405); // Not an account action. + CHECK(api.handle({"POST", alice_path, admin}, now, t0).status == 405); + CHECK(post(alice_path + "/ban?banned=1&reason=cheating").body == "{\"banned\":true}\n"); + const auto banned_view = must(JsonValue::parse(get(alice_path, admin).body)); + CHECK(banned_view.member("account")->member("banned")->boolean() == true && + banned_view.member("bans")->array()->at(0).member("reason")->string() == "cheating"); + { + auto broker_db = connect_as(env("EVO_PG_RUNTIME_USER")); + const auto refused = + persistence::issue_account_grant(*broker_db, 9831, issuer, "alice-sub", 5s); + CHECK(!refused && refused.error() == persistence::AccountIdentityError::banned); + CHECK(post(alice_path + "/ban?banned=0").body == "{\"banned\":false}\n"); + CHECK(persistence::issue_account_grant(*broker_db, 9831, issuer, "alice-sub", 5s)); + } + CHECK(post(alice_path + "/logout").body == "{\"logged_out\":true}\n"); + // The read views are the only way in: the runtime role still cannot read the tables. runtime = connect_as(env("EVO_PG_RUNTIME_USER")); CHECK(!runtime->query("SELECT count(*) FROM evolution.life_reservations", {}, 5s)); diff --git a/tests/region_migration_tests.cpp b/tests/region_migration_tests.cpp index 6e8a54e..3035bfa 100644 --- a/tests/region_migration_tests.cpp +++ b/tests/region_migration_tests.cpp @@ -229,6 +229,7 @@ void upgrade_across_migration_and_barrier() { " -v migration_sha_61=$(s 0061_admin_read_views.sql)" " -v migration_sha_62=$(s 0062_session_windows.sql)" " -v migration_sha_63=$(s 0063_admin_commands.sql)" + " -v migration_sha_64=$(s 0064_account_admin.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"); @@ -246,7 +247,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,61,62,63"); + "47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64"); 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 9a697c8..ae50691 100644 --- a/tools/ci/history-domain-check.sh +++ b/tools/ci/history-domain-check.sh @@ -75,6 +75,25 @@ 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.release_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64); +ALTER FUNCTION evolution.release_account_control_v63(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64) RENAME TO release_account_control; +GRANT EXECUTE ON FUNCTION evolution.release_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64) TO :"runtime_role"; +DROP FUNCTION evolution.renew_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,integer); +ALTER FUNCTION evolution.renew_account_control_v63(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,integer) RENAME TO renew_account_control; +GRANT EXECUTE ON FUNCTION evolution.renew_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,integer) TO :"runtime_role"; +DROP FUNCTION evolution.claim_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64,integer); +ALTER FUNCTION evolution.claim_account_control_v63(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64,integer) RENAME TO claim_account_control; +GRANT EXECUTE ON FUNCTION evolution.claim_account_control(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64,integer) TO :"runtime_role"; +DROP FUNCTION evolution.issue_account_grant(evolution.u64,text,text); +ALTER FUNCTION evolution.issue_account_grant_v63(evolution.u64,text,text) RENAME TO issue_account_grant; +GRANT EXECUTE ON FUNCTION evolution.issue_account_grant(evolution.u64,text,text) TO :"runtime_role"; +DROP FUNCTION evolution.admin_account_bans_v1(uuid); +DROP FUNCTION evolution.admin_account_status_v1(evolution.u64); +DROP FUNCTION evolution.admin_logout_account_v1(evolution.u64,uuid); +DROP FUNCTION evolution.admin_set_account_ban_v1(evolution.u64,uuid,boolean,text,text); +DROP FUNCTION evolution.revoke_account_by_id(evolution.u64,uuid); +DROP FUNCTION evolution.account_banned(uuid); +DROP TABLE evolution.session_intervals, evolution.account_bans; DROP FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,bytea,bytea); ALTER FUNCTION evolution.publish_cellular_mutation_checkpoint_v62(bytea,bytea,bytea,bytea,bytea,bytea) RENAME TO publish_cellular_mutation_checkpoint; GRANT EXECUTE ON FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,bytea,bytea) TO :"runtime_role"; diff --git a/tools/ci/postgres-check.sh b/tools/ci/postgres-check.sh index fba6032..e5673f8 100644 --- a/tools/ci/postgres-check.sh +++ b/tools/ci/postgres-check.sh @@ -172,7 +172,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,61,62,63 +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,62,63,64 # 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%% *}" @@ -193,7 +193,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")" = 63: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,62,63 +test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 64: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,62,63,64 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. @@ -247,7 +247,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,61,62,63 +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,62,63,64 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 @@ -305,9 +305,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=64 WHERE version=63' +psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=65 WHERE version=64' 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=63 WHERE version=64" +psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=64 WHERE version=65" 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/migrate-postgres.sh b/tools/migrate-postgres.sh index 498590a..6c41ebb 100644 --- a/tools/migrate-postgres.sh +++ b/tools/migrate-postgres.sh @@ -142,6 +142,8 @@ digest_62="$(sha256sum "$root/migrations/0062_session_windows.sql")" digest_62="${digest_62%% *}" digest_63="$(sha256sum "$root/migrations/0063_admin_commands.sql")" digest_63="${digest_63%% *}" +digest_64="$(sha256sum "$root/migrations/0064_account_admin.sql")" +digest_64="${digest_64%% *}" 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" \ @@ -191,6 +193,7 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --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_61=$digest_61" \ - --set="migration_sha_62=$digest_62" --set="migration_sha_63=$digest_63" "${admin[@]}" \ + --set="migration_sha_62=$digest_62" --set="migration_sha_63=$digest_63" \ + --set="migration_sha_64=$digest_64" "${admin[@]}" \ --set="runtime_role=$runtime_role" \ --file="$root/migrations/apply.sql"