// 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" #include #include #include #include #include #include #include #include #include void run_grant_broker_tests(); namespace { using namespace evo; using namespace evo::server::broker; using namespace std::chrono_literals; void check(bool value, std::source_location at = std::source_location::current()) { if (!value) throw std::runtime_error("grant broker test line " + std::to_string(at.line())); } #define CHECK(...) check(static_cast(__VA_ARGS__)) template const T& must(const std::optional& value, std::source_location at = std::source_location::current()) { if (!value) throw std::runtime_error("grant broker test line " + std::to_string(at.line())); return *value; } std::string env(const char* name) { const auto* value = std::getenv(name); if (!value) throw std::runtime_error("missing PostgreSQL test environment"); return value; } std::unique_ptr connect_as(const std::string& user) { auto db = persistence::Postgres::connect( {env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), user, {}, {}}, 5s); CHECK(db); return std::move(*db); } std::string base64url(std::span bytes) { auto text = base64_encode(bytes); for (auto& ch : text) ch = ch == '+' ? '-' : ch == '/' ? '_' : ch; while (!text.empty() && text.back() == '=') text.pop_back(); return text; } std::string base64url(std::string_view text) { return base64url(std::span{reinterpret_cast(text.data()), text.size()}); } // A test realm: one RSA key, its JWKS, and RS256 token signing. class Realm { public: Realm() : key_{EVP_PKEY_Q_keygen(nullptr, nullptr, "RSA", std::size_t{2048}), EVP_PKEY_free} { CHECK(key_); } [[nodiscard]] std::string jwks(std::string_view kid) const { return R"({"keys":[{"kid":"enc","kty":"RSA","use":"enc","alg":"RSA-OAEP","n":")" + component(OSSL_PKEY_PARAM_RSA_N) + R"(","e":"AQAB"},{"kid":")" + std::string(kid) + R"(","kty":"RSA","use":"sig","alg":"RS256","n":")" + component(OSSL_PKEY_PARAM_RSA_N) + R"(","e":")" + component(OSSL_PKEY_PARAM_RSA_E) + R"("}]})"; } [[nodiscard]] std::string token(std::string_view header, std::string_view payload) const { const auto input = base64url(header) + "." + base64url(payload); std::unique_ptr context{EVP_MD_CTX_new(), EVP_MD_CTX_free}; std::size_t size = 0; CHECK(context && EVP_DigestSignInit(context.get(), nullptr, EVP_sha256(), nullptr, key_.get()) == 1 && EVP_DigestSign(context.get(), nullptr, &size, reinterpret_cast(input.data()), input.size()) == 1); std::vector signature(size); CHECK(EVP_DigestSign(context.get(), signature.data(), &size, reinterpret_cast(input.data()), input.size()) == 1); signature.resize(size); return input + "." + base64url(signature); } private: [[nodiscard]] std::string component(const char* name) const { BIGNUM* value = nullptr; CHECK(EVP_PKEY_get_bn_param(key_.get(), name, &value) == 1); std::vector bytes(static_cast(BN_num_bytes(value))); BN_bn2bin(value, bytes.data()); BN_free(value); return base64url(bytes); } std::unique_ptr key_; }; constexpr std::string_view issuer = "https://auth.example.test/realms/aeternalis"; constexpr std::uint64_t now = 1'800'000'000; const std::string header = R"({"alg":"RS256","typ":"JWT","kid":"sig-1"})"; std::string claims(std::string_view subject, std::string_view extra = {}, std::string_view aud = R"(["account","aevolution-grants"])", std::string_view azp = "aevolution-game", std::string_view typ = "Bearer", std::uint64_t exp = now + 300, std::string_view verified = "true") { return R"({"exp":)" + std::to_string(exp) + R"(,"iat":)" + std::to_string(now - 10) + R"(,"iss":")" + std::string(issuer) + R"(","aud":)" + std::string(aud) + R"(,"sub":")" + std::string(subject) + R"(","typ":")" + std::string(typ) + R"(","azp":")" + std::string(azp) + R"(","email_verified":)" + std::string(verified) + std::string(extra) + "}"; } AccessTokenRules rules() { return {std::string(issuer), "aevolution-grants", "aevolution-game", 30}; } void json_tests() { const auto parsed = JsonValue::parse("{\"a\":[1,true,null,\"x\\u00e9\\ud83d\\ude00\\n\"]," "\"b\":{\"c\":9223372036854775807},\"a\":2}"); const auto& doc = must(parsed); CHECK(doc.member("a")->array()->size() == 4); CHECK(doc.member("a")->array()->at(1).boolean() == true); CHECK(doc.member("a")->array()->at(3).string() == "x\xC3\xA9\xF0\x9F\x98\x80\n"); CHECK(doc.member("b")->member("c")->integer() == 9223372036854775807ULL); CHECK(doc.member("missing") == nullptr); for (const std::string_view bad : {"", "{", "[1,]", R"({"a":1,})", "01", "1.5e", R"("\ud83d")", "[1] x", "{'a':1}", "\"\x01\"", "nul", "-", R"({"a" 1})"}) CHECK(!JsonValue::parse(bad)); CHECK(!must(JsonValue::parse("9223372036854775808")).integer()); CHECK(!must(JsonValue::parse("1.5")).integer()); CHECK(!must(JsonValue::parse("-1")).integer()); CHECK(JsonValue::parse(std::string(16, '[') + std::string(16, ']'))); CHECK(!JsonValue::parse(std::string(17, '[') + std::string(17, ']'))); CHECK(!JsonValue::parse("\"" + std::string(max_json_bytes, 'a') + "\"")); } void token_tests(const Realm& realm) { CHECK(base64url_decode("AQAB") == std::vector{1, 0, 1}); CHECK(!base64url_decode("AQAB=")); CHECK(!base64url_decode("AQ+B")); CHECK(!base64url_decode("AR")); // Non-canonical trailing bits. CHECK(!TokenVerifier::from_jwks(R"({"keys":[]})", rules())); CHECK(!TokenVerifier::from_jwks("not json", rules())); const auto verifier = TokenVerifier::from_jwks(realm.jwks("sig-1"), rules()); CHECK(verifier && verifier->keys() == 1); // The enc key is ignored. const auto good = verifier->verify(realm.token(header, claims("user-a")), now); CHECK(good && good->subject == "user-a" && good->issuer == issuer && good->expires_at == now + 300); CHECK( verifier->verify(realm.token(header, claims("user-a", {}, R"("aevolution-grants")")), now)); const auto failure = [&](const std::string& token, TokenError expected, std::uint64_t at = now) { const auto result = verifier->verify(token, at); return !result && result.error() == expected; }; CHECK(failure(realm.token(header, claims("u", {}, R"(["account"])")), TokenError::wrong_audience)); CHECK(failure(realm.token(header, claims("u", {}, R"("aevolution-grants")", "other")), TokenError::wrong_party)); CHECK(failure( realm.token(header, claims("u", {}, R"("aevolution-grants")", "aevolution-game", "ID")), TokenError::wrong_type)); CHECK(failure(realm.token(header, claims("u")), TokenError::expired, now + 330)); CHECK(verifier->verify(realm.token(header, claims("u")), now + 329)); // Leeway. CHECK(failure(realm.token(header, claims("u", R"(,"nbf":1800000100)")), TokenError::not_yet_valid)); CHECK(failure(realm.token(header, claims("u", {}, R"("aevolution-grants")", "aevolution-game", "Bearer", now + 300, "false")), TokenError::unverified_email)); CHECK(failure(realm.token(header, claims("")), TokenError::missing_subject)); auto wrong_issuer = claims("u"); wrong_issuer.replace(wrong_issuer.find("aeternalis"), 10, "other-realm"); CHECK(failure(realm.token(header, wrong_issuer), TokenError::wrong_issuer)); CHECK(failure(realm.token(R"({"alg":"RS256","kid":"sig-2"})", claims("u")), TokenError::unknown_key)); CHECK(failure(realm.token(R"({"alg":"none","kid":"sig-1"})", claims("u")), TokenError::unsupported_algorithm)); CHECK(failure(realm.token(R"({"alg":"HS256","kid":"sig-1"})", claims("u")), TokenError::unsupported_algorithm)); // A signature over different claims, and a token signed by another realm's key. auto spliced = realm.token(header, claims("user-a")); const auto other = realm.token(header, claims("user-b")); spliced = spliced.substr(0, spliced.rfind('.')) + other.substr(other.rfind('.')); CHECK(failure(spliced, TokenError::bad_signature)); const Realm stranger; 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 { network::GrantClaims claims; std::string account; std::uint64_t region{}; }; Grant decode(const server::OpsResponse& response, const network::GrantVerifier& verifier) { CHECK(response.status == 200 && response.content_type == "application/json"); const auto parsed = JsonValue::parse(response.body); const auto& body = must(parsed); CHECK(body.member("grant") && body.member("account") && body.member("region")); CHECK(body.member("endpoint")->string() == "void.example.test:7400"); CHECK(body.member("server_name")->string() == "void.example.test"); const auto decoded = base64url_decode([&] { auto text = std::string(must(body.member("grant")->string())); for (auto& ch : text) ch = ch == '+' ? '-' : ch == '/' ? '_' : ch; while (!text.empty() && text.back() == '=') text.pop_back(); return text; }()); const auto verified = verifier.verify(must(decoded)); CHECK(verified); const auto& claims = verified->claims(); CHECK(body.member("expires_at")->integer() == claims.expires_at); return {claims, std::string(must(body.member("account")->string())), must(body.member("region")->integer())}; } void broker_tests(const Realm& realm) { auto admin = connect_as(env("PGUSER")); CHECK(admin->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode(repeat('d7',32),'hex')) ON CONFLICT DO NOTHING", {}, 5s)); CHECK(admin->query("INSERT INTO evolution.region_leases(world_id,region_id,frame_id) " "VALUES (9831,1,7)", {}, 5s)); const auto runtime = env("EVO_PG_RUNTIME_USER"); auto key = network::GrantSigningKey::generate(network::DeploymentEnvironment::dev, 1); CHECK(key); auto public_key = key->public_key(); auto grants = network::GrantVerifier::create(network::DeploymentEnvironment::dev); CHECK(public_key && grants && grants->add_key(1, *public_key)); std::uint64_t next_id = 41; BrokerConfig config{9831, 7, 1, {{1, "void.example.test:7400", "void.example.test"}}}; int connects = 0; GrantBroker broker{config, *TokenVerifier::from_jwks(realm.jwks("sig-1"), rules()), std::move(*key), [&]() -> std::unique_ptr { ++connects; return connect_as(runtime); }, [&](std::uint64_t& id) { id = next_id++; return true; }}; const auto alice = "Bearer " + realm.token(header, claims("alice-sub")); const auto bob = "bearer " + realm.token(header, claims("bob-sub")); const auto post = [&](std::string_view path, const std::string& authorization, std::uint64_t at) { return broker.handle({"POST", path, authorization}, at); }; CHECK(broker.handle({"GET", "/healthz", {}}, now).status == 200); CHECK(broker.handle({"GET", "/grant", alice}, now).status == 405); CHECK(broker.handle({"POST", "/other", alice}, now).status == 404); CHECK(post("/grant", "", now).status == 401); CHECK(post("/grant", "Basic abc", now).status == 401); const auto forged = post("/grant", "Bearer " + Realm{}.token(header, claims("alice-sub")), now); CHECK(forged.status == 401 && forged.body.find("invalid_token") != std::string::npos); CHECK(connects == 0); // Nothing reaches the database before a token verifies. const auto first = decode(post("/grant", alice, now), *grants); CHECK(first.claims.serial == 1 && first.claims.grant_id == 41 && first.region == 1); CHECK(first.claims.world.world == 9831 && first.claims.world.frame == 7); CHECK(first.claims.region == 1 && first.claims.issued_at == now && first.claims.expires_at == now + 600); CHECK(first.account.size() == 36 && first.account[8] == '-'); CHECK(post("/grant", alice, now + 1).status == 429); const auto second = decode(post("/grant", alice, now + 2), *grants); CHECK(second.claims.serial == 2 && second.account == first.account); CHECK(second.claims.account.bytes == first.claims.account.bytes); const auto other = decode(post("/grant", bob, now + 2), *grants); CHECK(other.account != first.account && other.claims.serial == 1); // The region accepts the newest grant; logout makes it, and every older one, stale. persistence::Sha256Digest build{}; build.fill(0xD7); auto region = connect_as(runtime); const persistence::RegionKey home{9831, 1}; const auto lease = persistence::acquire_region_lease(*region, home, build, 20000ms, 5s); CHECK(lease); const auto& account = second.claims.account.bytes; const auto claim = persistence::claim_account_control(*region, home, *lease, account, 2, 7, 20000ms, 5s); CHECK(claim); CHECK(persistence::renew_account_control(*region, home, *lease, account, claim->generation, 20000ms, 5s)); const auto logout = post("/logout", alice, now + 3); CHECK(logout.status == 200 && logout.body == "{\"revoked\":true}\n"); const auto renewed = persistence::renew_account_control(*region, home, *lease, account, claim->generation, 20000ms, 5s); CHECK(!renewed && renewed.error().kind == persistence::ControlStoreError::fenced); // The next login gets a serial above everything revoked and takes control again. const auto third = decode(post("/grant", alice, now + 3), *grants); CHECK(third.claims.serial == 3 && third.account == first.account); const auto stale = persistence::claim_account_control(*region, home, *lease, account, 2, 8, 20000ms, 5s); CHECK(!stale && stale.error().kind == persistence::ControlStoreError::stale_grant); CHECK(persistence::claim_account_control(*region, home, *lease, account, 3, 8, 20000ms, 5s)); // Bob never held control: logout still raises the accepted serial for him. CHECK(post("/logout", bob, now + 4).body == "{\"revoked\":true}\n"); CHECK(!persistence::claim_account_control(*region, home, *lease, other.claims.account.bytes, 1, 9, 20000ms, 5s)); const auto unknown = post("/logout", "Bearer " + realm.token(header, claims("nobody")), now); CHECK(unknown.status == 200 && unknown.body == "{\"revoked\":false}\n"); // Store-level argument checks, and a database that cannot be reached. CHECK(!persistence::issue_account_grant(*region, 0, issuer, "x", 5s)); CHECK(!persistence::issue_account_grant(*region, 9831, issuer, "", 5s)); CHECK(!persistence::issue_account_grant(*region, 9831, issuer, std::string(256, 's'), 5s)); GrantBroker offline{ config, *TokenVerifier::from_jwks(realm.jwks("sig-1"), rules()), std::move(*network::GrantSigningKey::generate(network::DeploymentEnvironment::dev, 1)), [] { return std::unique_ptr{}; }, [](std::uint64_t& id) { id = 1; return true; }}; CHECK(offline.handle({"POST", "/grant", alice}, now).status == 503); // 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_ADMIN_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); // Session windows (schema 62): none yet, so sessions are closed. const auto window_of = [&](std::string_view id) { return must(JsonValue::parse( get("/api/regions/" + std::string(id) + "/session-window", admin).body)); }; const auto post = [&](std::string_view target) { return api.handle({"POST", target, admin}, now, t0); }; CHECK(window_of("1").member("open")->boolean() == false && window_of("1").member("history")->array()->empty()); for (const std::string_view bad : {"/api/regions/1/session-window", "/api/regions/1/session-window?minutes=241", "/api/regions/1/session-window?minutes=x", "/api/regions/1/session-window?minutes=1000", "/api/regions/1/session-window?minutes=60&reason=%zz", "/api/regions/1/session-window?minutes=60&reason=a%0Ab"}) CHECK(post(bad).status == 400); CHECK( api.handle({"POST", "/api/regions/1/session-window?minutes=60", player}, now, t0).status == 403); CHECK(post("/api/accounts").status == 405 && post("/api/regions/1/view").status == 405); CHECK(post("/api/regions/2/session-window?minutes=60").status == 503); // No such region. // Open for an hour, with a reason; the region list and the history show it. const auto opened = post("/api/regions/1/session-window?minutes=60&reason=Playtest+A%21"); CHECK(opened.status == 200); const auto first = must(JsonValue::parse(opened.body)); const auto first_id = std::string(must(first.member("activation")->string())); CHECK(first_id.starts_with("adm-") && first.member("expires_at")->integer()); const auto open_now = window_of("1"); const auto& latest = open_now.member("history")->array()->at(0); CHECK(open_now.member("open")->boolean() == true && latest.member("activation")->string() == first_id && latest.member("author")->string() == "ops@example.test (ops)" && latest.member("reason")->string() == "Playtest A!" && latest.member("expires_at")->integer() == first.member("expires_at")->integer()); const auto listed_regions = must(JsonValue::parse(get("/api/regions", admin).body)); CHECK(listed_regions.member("regions")->array()->at(0).member("window_open")->boolean() == true); // Extending writes a new activation; closing writes a closing row. Rows never change. const auto extended = must(JsonValue::parse(post("/api/regions/1/session-window?minutes=240").body)); CHECK(extended.member("activation")->string() != first_id); CHECK(post("/api/regions/1/session-window?minutes=0&reason=done").status == 200); const auto closed_now = window_of("1"); CHECK(closed_now.member("open")->boolean() == false && closed_now.member("history")->array()->size() == 3 && closed_now.member("history")->array()->at(0).member("expires_at")->kind() == JsonValue::Kind::null); // The region reads only the newest row; the table refuses rewrites and long windows. auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto current = runtime->query( "SELECT activation_id, expires_at IS NULL FROM evolution.load_session_window_v1(9831, 1)", {}, 5s); CHECK(current && current->size() == 1 && (*current)[0][1] == "t"); CHECK(!runtime->query( "SELECT * FROM evolution.admin_set_session_window_v1(9831, 1, 60, 'x', '')", {}, 5s)); runtime = connect_as(env("EVO_PG_RUNTIME_USER")); CHECK(!runtime->query("SELECT * FROM evolution.admin_accounts_v1(9831)", {}, 5s)); auto owner = connect_as(env("PGUSER")); CHECK(!owner->query("UPDATE evolution.session_windows SET reason = 'x'", {}, 5s)); owner = connect_as(env("PGUSER")); CHECK(!owner->query("DELETE FROM evolution.session_windows", {}, 5s)); owner = connect_as(env("PGUSER")); CHECK(!owner->query("INSERT INTO evolution.session_windows(world_id, region_id, " "activation_id, expires_at, author_subject) VALUES (9831, 1, 'long', " "clock_timestamp() + interval '5 hours', 'x')", {}, 5s)); owner = connect_as(env("PGUSER")); CHECK(!owner->query( "SELECT * FROM evolution.admin_set_session_window_v1(9831, 1, 14401, 'x', '')", {}, 5s)); // Admin commands (schema 63): queued with the admin's identity, shape-checked, listed. for (const std::string_view bad : {"/api/regions/1/commands", "/api/regions/1/commands?kind=explode", "/api/regions/1/commands?kind=add_pool", "/api/regions/1/commands?kind=add_pool&energy=x", "/api/regions/1/commands?kind=remove_cell&target=7&energy=5", "/api/regions/1/commands?kind=spawn_wildlife&count=65"}) CHECK(post(bad).status == 400); const auto queued = must(JsonValue::parse(post("/api/regions/1/commands?kind=add_pool&energy=1000&carbon=7" "&reason=top+up") .body)); CHECK(queued.member("id") && queued.member("target")->string() == "0"); CHECK(post("/api/regions/1/commands?kind=remove_cell&target=424242").status == 200); CHECK(post("/api/regions/2/commands?kind=add_pool&energy=1").status == 400); const auto listed_commands = must(JsonValue::parse(get("/api/regions/1/commands", admin).body)); const auto& newest = listed_commands.member("commands")->array()->at(0); const auto& older = listed_commands.member("commands")->array()->at(1); CHECK(newest.member("kind")->string() == "remove_cell" && newest.member("target")->string() == "424242" && newest.member("applied_tick")->kind() == JsonValue::Kind::null && older.member("kind")->string() == "add_pool" && older.member("amount")->array()->at(0).string() == "1000" && older.member("amount")->array()->at(1).string() == "7" && older.member("reason")->string() == "top up" && older.member("author")->string() == "ops@example.test (ops)"); { auto reader = connect_as(env("EVO_PG_RUNTIME_USER")); const auto pending = reader->query( "SELECT count(*) FROM evolution.load_pending_admin_commands_v1(9831, 1)", {}, 5s); CHECK(pending && (*pending)[0][0] == "2"); CHECK(!reader->query("SELECT * FROM evolution.admin_enqueue_command_v1(9831, 1, 4, 0, 0, " "1, 0, 0, 0, 0, 'x', '')", {}, 5s)); reader = connect_as(env("PGUSER")); 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)); CHECK(!runtime->query("SELECT count(*) FROM evolution.session_windows", {}, 5s)); CHECK(server::admin::query_value("a=1&reason=x%20y+z&b=2", "reason") == "x y z" && !server::admin::query_value("a=1", "reason") && !server::admin::query_value("reason=abc", "reason", 2)); CHECK(server::admin::json_string("a\"b\\c\n\x01") == "\"a\\\"b\\\\c\\u000a\\u0001\""); } } // namespace void run_grant_broker_tests() { json_tests(); const Realm realm; token_tests(realm); broker_tests(realm); admin_api_tests(realm); }