Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / postgres-tools (push) Successful in 31s
Foundation / server-image (push) Successful in 4m29s
Foundation / image (push) Successful in 5m43s
ADR-0182 section 17. The plan's 2,000-organism cap became the rules-12 key region.organism_cap, which was parsed but never enforced; the real bound was max_cellular_tick_lives = 256 (ADR-0106), which rules 13's organism cap could not exceed. The bound is now 4,096, for testing limits only; the DEV tuning file keeps 256. - max_cellular_tick_lives (4,096) bounds the raw region path: step, owner state, batch trace (cellular_batch_bytes_for) and current checkpoint traces. max_cellular_frozen_lives (256) keeps cohort populations, population batches, migration traces and pre-v3 cellular traces, whose database checks are fixed. - Tuning: reproduction.organism_cap and wildlife_cap accept up to 4,096. - Schema 68: the trace checker under the current publishers (cellular_births_v45) accepts 4,096 intents, births and mutations per tick; spawn_wildlife takes up to 256 cells a command. - Region view and portal: the lineage archive's fill (births of 65,536, genomes of 4,096), at which a region stops ticking. - PostgreSQL suite: 256 wildlife spawned in one command, then a 289-life tick published and recovered exactly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1069 lines
60 KiB
C++
1069 lines
60 KiB
C++
// 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/admin/region_switch.hpp"
|
|
#include "evo/server/broker/grant_broker.hpp"
|
|
#include "evo/server/broker/json.hpp"
|
|
|
|
#include <openssl/core_names.h>
|
|
#include <openssl/evp.h>
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cstdlib>
|
|
#include <fstream>
|
|
#include <iterator>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <source_location>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
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<bool>(__VA_ARGS__))
|
|
template <typename T>
|
|
const T& must(const std::optional<T>& 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<persistence::Postgres> 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<const std::uint8_t> 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<const std::uint8_t*>(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<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> 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<const unsigned char*>(input.data()),
|
|
input.size()) == 1);
|
|
std::vector<std::uint8_t> signature(size);
|
|
CHECK(EVP_DigestSign(context.get(), signature.data(), &size,
|
|
reinterpret_cast<const unsigned char*>(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<std::uint8_t> bytes(static_cast<std::size_t>(BN_num_bytes(value)));
|
|
BN_bn2bin(value, bytes.data());
|
|
BN_free(value);
|
|
return base64url(bytes);
|
|
}
|
|
std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> 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<std::uint8_t>{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<persistence::Postgres> {
|
|
++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<persistence::Postgres>{}; },
|
|
[](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<persistence::Postgres> {
|
|
++connects;
|
|
return online ? connect_as(env("EVO_PG_ADMIN_USER")) : nullptr;
|
|
},
|
|
[&](std::uint64_t region) -> std::optional<std::string> {
|
|
++fetches;
|
|
return region == 1 ? std::optional<std::string>{"{\"region\":1}\n"}
|
|
: std::nullopt;
|
|
},
|
|
{{"/index.html", "text/html; charset=utf-8", "<!doctype html>"},
|
|
{"/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 == "<!doctype html>" &&
|
|
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=257",
|
|
"/api/regions/1/commands?kind=take_reserve&target=7",
|
|
"/api/regions/1/commands?kind=remove_wildlife&target=7",
|
|
"/api/regions/1/commands?kind=remove_wildlife&energy=1"})
|
|
CHECK(post(bad).status == 400);
|
|
// Schema 67: take_reserve and remove_wildlife.
|
|
CHECK(post("/api/regions/1/commands?kind=take_reserve&target=424242&energy=5").status == 200);
|
|
CHECK(post("/api/regions/1/commands?kind=remove_wildlife").status == 200);
|
|
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] == "4");
|
|
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));
|
|
}
|
|
|
|
// Resource schedules (schema 65): a due schedule queues one command, never a second
|
|
// while that one waits; the list shows the run; stopping writes a new version.
|
|
for (const std::string_view bad :
|
|
{"/api/regions/1/schedules?kind=add_pool&count=1&interval=5&energy=1",
|
|
"/api/regions/1/schedules?kind=add_bubbles&count=4&interval=0&energy=1",
|
|
"/api/regions/1/schedules?kind=add_bubbles&count=4&interval=90000&energy=1",
|
|
"/api/regions/1/schedules?kind=add_bubbles&count=4&interval=5"})
|
|
CHECK(post(bad).status == 400);
|
|
const auto made = must(JsonValue::parse(
|
|
post("/api/regions/1/schedules?kind=add_bubbles&count=4&interval=60&energy=100&"
|
|
"reason=feed")
|
|
.body));
|
|
const auto schedule_id = std::string(must(made.member("id")->string()));
|
|
const auto pending_now = [&] {
|
|
auto reader = connect_as(env("EVO_PG_RUNTIME_USER"));
|
|
const auto rows = reader->query(
|
|
"SELECT count(*) FROM evolution.load_pending_admin_commands_v1(9831, 1)", {}, 5s);
|
|
CHECK(rows && rows->size() == 1);
|
|
return std::string(*(*rows)[0][0]);
|
|
};
|
|
CHECK(pending_now() == "5" && pending_now() == "5");
|
|
const auto listed_schedules =
|
|
must(JsonValue::parse(get("/api/regions/1/schedules", admin).body));
|
|
const auto& schedule = listed_schedules.member("schedules")->array()->at(0);
|
|
CHECK(schedule.member("id")->string() == schedule_id &&
|
|
schedule.member("kind")->string() == "add_bubbles" &&
|
|
schedule.member("runs")->integer() == 1 &&
|
|
schedule.member("enabled")->boolean() == true &&
|
|
schedule.member("interval")->integer() == 60);
|
|
const auto queued_by_schedule =
|
|
must(JsonValue::parse(get("/api/regions/1/commands", admin).body));
|
|
CHECK(queued_by_schedule.member("commands")->array()->at(0).member("author")->string() ==
|
|
"schedule " + schedule_id);
|
|
CHECK(post("/api/regions/1/schedules?kind=add_bubbles&count=4&interval=60&energy=100&"
|
|
"enabled=0&id=" +
|
|
schedule_id)
|
|
.status == 200);
|
|
const auto stopped = must(JsonValue::parse(get("/api/regions/1/schedules", admin).body));
|
|
CHECK(stopped.member("schedules")->array()->size() == 1 &&
|
|
stopped.member("schedules")->array()->at(0).member("enabled")->boolean() == false);
|
|
CHECK(post("/api/regions/1/schedules?kind=add_bubbles&count=4&interval=60&energy=1&id=999999")
|
|
.status == 400);
|
|
|
|
// Tuning revisions (schema 66): a request body in the Git revamp file format, checked,
|
|
// stored with the admin's identity and queued as an adopt_tuning command per region.
|
|
{
|
|
const auto file = [](std::string_view name) {
|
|
std::ifstream in{env("EVO_SOURCE_ROOT") + "/deploy/kubernetes/region/dev/tuning/" +
|
|
std::string(name),
|
|
std::ios::binary};
|
|
return std::string{std::istreambuf_iterator<char>{in}, {}};
|
|
};
|
|
const auto baseline = file("cellular-revamp.tuning");
|
|
CHECK(!baseline.empty());
|
|
server::admin::AdminConfig config;
|
|
config.world = 9831;
|
|
config.view_regions = {1};
|
|
config.baseline_tuning = baseline;
|
|
config.region_tuning = file("cellular.tuning");
|
|
AdminApi tuned{config,
|
|
*TokenVerifier::from_jwks(realm.jwks("sig-1"), admin_rules),
|
|
[] { return connect_as(env("EVO_PG_ADMIN_USER")); },
|
|
[](std::uint64_t) { return std::optional<std::string>{}; },
|
|
{}};
|
|
const auto send = [&](std::string_view target, std::string_view body) {
|
|
return tuned.handle({"POST", target, admin, body}, now, t0);
|
|
};
|
|
const auto read = [&](std::string_view target) {
|
|
return tuned.handle({"GET", target, admin}, now, t0);
|
|
};
|
|
const auto none = must(JsonValue::parse(read("/api/tuning").body));
|
|
const auto digest =
|
|
std::string(must(none.member("baseline")->member("rules_sha256")->string()));
|
|
CHECK(none.member("newest")->kind() == JsonValue::Kind::null &&
|
|
none.member("revisions")->array()->empty() &&
|
|
none.member("baseline")->member("text")->string() == baseline &&
|
|
digest.size() == 64 && none.member("regions")->array()->at(0).string() == "1" &&
|
|
none.member("region_file")->string() == config.region_tuning);
|
|
|
|
// Bodies go to /api/tuning only; check=1 stores nothing.
|
|
CHECK(tuned
|
|
.handle({"POST", "/api/regions/1/commands?kind=add_pool&energy=1", admin, "x"},
|
|
now, t0)
|
|
.status == 400);
|
|
const auto checked = must(JsonValue::parse(send("/api/tuning?check=1", baseline).body));
|
|
CHECK(checked.member("valid")->boolean() == true &&
|
|
checked.member("rules_sha256")->string() == digest &&
|
|
checked.member("safety_version")->integer() == 0);
|
|
// Problems name the kind, line and key; the safety revision cannot change live.
|
|
const auto lines = std::ranges::count(baseline, '\n');
|
|
const auto unknown = must(
|
|
JsonValue::parse(send("/api/tuning?check=1", baseline + "no.such_key = 1\n").body));
|
|
CHECK(unknown.member("error")->string() == "invalid_tuning" &&
|
|
unknown.member("kind")->string() == "unknown_key" &&
|
|
unknown.member("key")->string() == "no.such_key" &&
|
|
unknown.member("line")->integer() == lines + 1);
|
|
CHECK(send("/api/tuning", "").status == 400 &&
|
|
send("/api/tuning", "a = \x01").status == 400);
|
|
const auto unsafe = must(JsonValue::parse(
|
|
send("/api/tuning?check=1", file("cellular-reproduction-safety.tuning")).body));
|
|
CHECK(unsafe.member("error")->string() == "safety_version_changed" &&
|
|
unsafe.member("expected")->integer() == 0);
|
|
CHECK(
|
|
must(JsonValue::parse(read("/api/tuning").body)).member("revisions")->array()->empty());
|
|
|
|
// A slower drip: stored, listed, and queued for region 1 with its digest.
|
|
auto changed = baseline;
|
|
const auto at = changed.find("spent.drip_interval_ticks = 20");
|
|
CHECK(at != std::string::npos);
|
|
changed.replace(at, 30, "spent.drip_interval_ticks = 40");
|
|
const auto stored =
|
|
must(JsonValue::parse(send("/api/tuning?reason=slower+drip", changed).body));
|
|
const auto revision = std::string(must(stored.member("revision")->string()));
|
|
const auto changed_digest = std::string(must(stored.member("rules_sha256")->string()));
|
|
CHECK(changed_digest != digest && stored.member("regions")->integer() == 1);
|
|
const auto listed_tuning = must(JsonValue::parse(read("/api/tuning").body));
|
|
const auto& entry = listed_tuning.member("revisions")->array()->at(0);
|
|
CHECK(listed_tuning.member("newest")->member("revision")->string() == revision &&
|
|
listed_tuning.member("newest")->member("text")->string() == changed &&
|
|
entry.member("rules_sha256")->string() == changed_digest &&
|
|
entry.member("reason")->string() == "slower drip" &&
|
|
entry.member("author")->string() == "ops@example.test (ops)" &&
|
|
entry.member("regions")->integer() == 1 && entry.member("adopted")->integer() == 0);
|
|
CHECK(
|
|
must(JsonValue::parse(read("/api/tuning/" + revision).body)).member("text")->string() ==
|
|
changed);
|
|
CHECK(read("/api/tuning/999999").status == 404 && read("/api/tuning/0").status == 404 &&
|
|
read("/api/tuning/x").status == 404);
|
|
std::uint64_t first_word = 0;
|
|
for (std::size_t b = 0; b < 8; ++b)
|
|
first_word |= std::stoull(changed_digest.substr(b * 2, 2), nullptr, 16) << (8 * b);
|
|
auto reader = connect_as(env("EVO_PG_RUNTIME_USER"));
|
|
const auto adoption =
|
|
reader->query("SELECT cell_count, target, energy, other FROM "
|
|
"evolution.load_pending_admin_commands_v1(9831, 1) WHERE kind = 7",
|
|
{}, 5s);
|
|
CHECK(adoption && adoption->size() == 1 && (*adoption)[0][0] == "0" &&
|
|
(*adoption)[0][1] == revision && (*adoption)[0][2] == std::to_string(first_word) &&
|
|
(*adoption)[0][3] == "0");
|
|
const auto text = reader->query(
|
|
"SELECT text, encode(rules_sha256, 'hex') FROM evolution.load_tuning_revision_v1(9831, "
|
|
"$1::bigint)",
|
|
std::array{revision}, 5s);
|
|
CHECK(text && text->size() == 1 && (*text)[0][0] == changed &&
|
|
(*text)[0][1] == changed_digest);
|
|
// Only the admin stores revisions, rows never change, and kind 7 is never queued by hand.
|
|
CHECK(!reader->query("SELECT evolution.admin_set_tuning_v1(9831, 'x', "
|
|
"decode(repeat('ab', 32), 'hex'), '{1}', 'x', '')",
|
|
{}, 5s));
|
|
reader = connect_as(env("PGUSER"));
|
|
CHECK(!reader->query("UPDATE evolution.tuning_revisions SET reason = 'x'", {}, 5s));
|
|
CHECK(post("/api/regions/1/commands?kind=adopt_tuning&target=1").status == 400);
|
|
CHECK(post("/api/regions/1/schedules?kind=adopt_tuning&count=1&interval=60").status == 400);
|
|
// An unknown region (3 has no lease) refuses the whole revision.
|
|
CHECK(api.handle({"POST", "/api/tuning", admin, changed}, now, t0).status == 400);
|
|
CHECK(
|
|
must(JsonValue::parse(read("/api/tuning").body)).member("revisions")->array()->size() ==
|
|
1);
|
|
|
|
// The guided editor sends only changes against a base: the newest revision or the
|
|
// baseline file. Values are replaced in place (comments kept), absent keys appended,
|
|
// and a base that is no longer the newest is refused.
|
|
const auto back = must(JsonValue::parse(
|
|
send("/api/tuning?check=1&base=" + revision, "spent.drip_interval_ticks = 20\n").body));
|
|
CHECK(back.member("rules_sha256")->string() == digest);
|
|
CHECK(send("/api/tuning?check=1&base=baseline", "").status == 200);
|
|
CHECK(send("/api/tuning?check=1&base=999999", "").status == 409);
|
|
CHECK(send("/api/tuning?check=1&base=x", "").status == 400);
|
|
CHECK(send("/api/tuning?check=1&base=baseline", "spent.drip_interval_ticks = 1 # x\n")
|
|
.status == 400);
|
|
CHECK(send("/api/tuning?check=1&base=baseline",
|
|
"spent.drip_absorb = 1\nspent.drip_absorb = 0\n")
|
|
.status == 400);
|
|
const auto appended = must(
|
|
JsonValue::parse(send("/api/tuning?check=1&base=baseline", "no.such_key = 1\n").body));
|
|
CHECK(appended.member("kind")->string() == "unknown_key");
|
|
const auto guided = must(JsonValue::parse(
|
|
send("/api/tuning?reason=guided&base=" + revision, "spent.drip_interval_ticks = 30\n")
|
|
.body));
|
|
const auto guided_revision = std::string(must(guided.member("revision")->string()));
|
|
auto expected = changed;
|
|
expected.replace(expected.find("spent.drip_interval_ticks = 40"), 30,
|
|
"spent.drip_interval_ticks = 30");
|
|
CHECK(must(JsonValue::parse(read("/api/tuning/" + guided_revision).body))
|
|
.member("text")
|
|
->string() == expected);
|
|
CHECK(send("/api/tuning?check=1&base=" + revision, "").status == 409);
|
|
}
|
|
|
|
// ADR-0182 section 15: opening a region. The HTTPS reader and the four-file switch first,
|
|
// over the repository's own files, then the endpoints against fake Gitea and Argo CD.
|
|
{
|
|
using server::admin::HttpsRequest;
|
|
using server::admin::HttpsResponse;
|
|
using server::admin::parse_http_response;
|
|
using server::admin::region_switch_paths;
|
|
const auto sized = parse_http_response(
|
|
"HTTP/1.1 201 Created\r\nContent-Length: 5\r\nX: y\r\n\r\nhello", 100);
|
|
CHECK(sized && sized->status == 201 && sized->body == "hello");
|
|
const auto chunked =
|
|
parse_http_response("HTTP/1.1 200 OK\r\nTransfer-Encoding: "
|
|
"chunked\r\n\r\n4\r\nwiki\r\n5;x=1\r\npedia\r\n0\r\n\r\n",
|
|
100);
|
|
CHECK(chunked && chunked->status == 200 && chunked->body == "wikipedia");
|
|
CHECK(!parse_http_response("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nwi",
|
|
100));
|
|
CHECK(!parse_http_response("HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nshort", 100));
|
|
CHECK(!parse_http_response("HTTP/1.1 200 OK\r\n\r\nlong enough", 4));
|
|
CHECK(!parse_http_response("SSH-2.0 hello\r\n\r\n", 100));
|
|
const auto with_prefix = server::admin::parse_https_base("https://git.example:8443/gitea/");
|
|
CHECK(with_prefix && with_prefix->host == "git.example" && with_prefix->port == 8443 &&
|
|
with_prefix->prefix == "/gitea");
|
|
const auto bare =
|
|
server::admin::parse_https_base("argocd-server.argocd.svc.cluster.local:443");
|
|
CHECK(bare && bare->host == "argocd-server.argocd.svc.cluster.local" && bare->port == 443 &&
|
|
bare->prefix.empty());
|
|
CHECK(!server::admin::parse_https_base("http://plain.example"));
|
|
|
|
server::admin::RegionSwitchFiles files;
|
|
for (std::size_t i = 0; i < files.size(); ++i) {
|
|
std::ifstream in{env("EVO_SOURCE_ROOT") + "/" + std::string(region_switch_paths.at(i)),
|
|
std::ios::binary};
|
|
files.at(i) = std::string{std::istreambuf_iterator<char>{in}, {}};
|
|
}
|
|
const auto layout = server::admin::read_region_layout(files);
|
|
CHECK(layout && layout->region != 0 && layout->wildlife_first != 0);
|
|
auto to = *layout;
|
|
to.region += 1;
|
|
to.wildlife_first += 100;
|
|
to.commit = std::string(32, 'e');
|
|
const auto switched =
|
|
server::admin::switch_region(files, to, "region opened_region by a test");
|
|
CHECK(switched && server::admin::read_region_layout(*switched) == to);
|
|
// Only the named lines change (and the note above the opening is added).
|
|
const auto lines = [](const std::string& text) {
|
|
std::vector<std::string> out;
|
|
for (std::size_t at = 0; at < text.size();) {
|
|
const auto end = std::min(text.find('\n', at), text.size());
|
|
const auto line = text.substr(at, end - at);
|
|
if (line.find("# Admin portal (ADR-0182 section 15)") == std::string::npos)
|
|
out.push_back(line);
|
|
at = end + 1;
|
|
}
|
|
return out;
|
|
};
|
|
for (std::size_t i = 0; switched && i < files.size(); ++i) {
|
|
const auto before = lines(files.at(i));
|
|
const auto after = lines(switched->at(i));
|
|
CHECK(before.size() == after.size());
|
|
for (std::size_t l = 0; l < std::min(before.size(), after.size()); ++l)
|
|
if (before[l] != after[l])
|
|
CHECK(std::ranges::any_of(
|
|
std::array<std::string_view, 8>{"REGION_ID", "REGION_LIFE_ROUTES",
|
|
"--commit", "--playtest-wildlife-first-id",
|
|
"Region host", "BROKER_DEFAULT_REGION",
|
|
"BROKER_ROUTES", "ADMIN_REGIONS"},
|
|
[&](std::string_view key) {
|
|
return after[l].find(key) != std::string::npos;
|
|
}));
|
|
}
|
|
CHECK(switched &&
|
|
switched->at(0).find("# Admin portal (ADR-0182 section 15): region opened_region "
|
|
"by a test\n - {name: REGION_OPENING") !=
|
|
std::string::npos);
|
|
CHECK(server::admin::switch_region(*switched, to, "again").error() == "target");
|
|
CHECK(server::admin::switch_region(files, to, "two\nlines").error() == "note");
|
|
auto broken = files;
|
|
broken.at(0).replace(broken.at(0).find("{name: REGION_ID"), 4, "{nom");
|
|
CHECK(server::admin::read_region_layout(broken).error() == "REGION_ID");
|
|
|
|
// The endpoints against fake services serving the repository files for world 9831.
|
|
for (auto& text : files)
|
|
for (const auto& from : {std::string{"REGION_WORLD, value: \"100\""},
|
|
std::string{"evolution-dev: world 100,"}})
|
|
for (auto at = text.find(from); at != std::string::npos; at = text.find(from, at))
|
|
text.replace(at, from.size(),
|
|
from == "evolution-dev: world 100,"
|
|
? std::string{"evolution-dev: world 9831,"}
|
|
: std::string{"REGION_WORLD, value: \"9831\""});
|
|
const auto head = std::string(40, 'a');
|
|
const auto made_commit = std::string(40, 'c');
|
|
std::vector<HttpsRequest> seen;
|
|
std::string argo_phase = "Succeeded";
|
|
int commit_status = 201;
|
|
const server::admin::HttpsTransport fake =
|
|
[&](const HttpsRequest& request) -> std::optional<HttpsResponse> {
|
|
seen.push_back(request);
|
|
const auto& t = request.target;
|
|
if (request.host == "argo.test") {
|
|
if (request.method == "POST")
|
|
return HttpsResponse{200, "{}"};
|
|
return HttpsResponse{200,
|
|
"{\"items\":[{\"metadata\":{\"name\":\"aevolution-dev\"},"
|
|
"\"status\":{\"sync\":{\"status\":\"Synced\",\"revision\":\"" +
|
|
head +
|
|
"\"},\"health\":{\"status\":\"Healthy\"},"
|
|
"\"operationState\":{\"phase\":\"" +
|
|
argo_phase + "\",\"message\":\"done\"}}}]}"};
|
|
}
|
|
if (t == "/api/v1/repos/dingo/AEvolution/branches/main")
|
|
return HttpsResponse{200,
|
|
"{\"name\":\"main\",\"commit\":{\"id\":\"" + head + "\"}}"};
|
|
if (request.method == "POST" && t == "/api/v1/repos/dingo/AEvolution/contents")
|
|
return HttpsResponse{commit_status,
|
|
"{\"commit\":{\"sha\":\"" + made_commit + "\"}}"};
|
|
for (std::size_t i = 0; i < region_switch_paths.size(); ++i) {
|
|
const std::string path(region_switch_paths.at(i));
|
|
std::string raw = "/api/v1/repos/dingo/AEvolution/raw/";
|
|
raw.append(path).append("?ref=").append(head);
|
|
if (t == raw)
|
|
return HttpsResponse{200, files.at(i)};
|
|
}
|
|
constexpr std::string_view listing = "/api/v1/repos/dingo/AEvolution/contents/";
|
|
if (t.starts_with(listing)) {
|
|
const auto dir = t.substr(listing.size(), t.find('?') - listing.size());
|
|
std::string out = "[";
|
|
for (std::size_t i = 0; i < region_switch_paths.size(); ++i) {
|
|
const std::string path(region_switch_paths.at(i));
|
|
if (path.substr(0, path.rfind('/')) == dir)
|
|
out += std::string(out.size() == 1 ? "" : ",") + "{\"name\":\"" +
|
|
path.substr(path.rfind('/') + 1) + "\",\"sha\":\"" +
|
|
std::string(40, static_cast<char>('1' + i)) + "\"}";
|
|
}
|
|
return HttpsResponse{200, out + "]"};
|
|
}
|
|
return HttpsResponse{404, "{}"};
|
|
};
|
|
server::admin::AdminConfig config;
|
|
config.world = 9831;
|
|
config.view_regions = {1};
|
|
std::ifstream revamp{env("EVO_SOURCE_ROOT") +
|
|
"/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning",
|
|
std::ios::binary};
|
|
config.baseline_tuning = std::string{std::istreambuf_iterator<char>{revamp}, {}};
|
|
AdminApi deploying{config,
|
|
*TokenVerifier::from_jwks(realm.jwks("sig-1"), admin_rules),
|
|
[] { return connect_as(env("EVO_PG_ADMIN_USER")); },
|
|
[](std::uint64_t) { return std::optional<std::string>{}; },
|
|
{}};
|
|
const auto ask = [&](std::string_view method, std::string_view target) {
|
|
return deploying.handle({method, target, admin}, now, t0);
|
|
};
|
|
CHECK(ask("GET", "/api/deploy").body == "{\"configured\":false}\n");
|
|
CHECK(ask("POST", "/api/deploy/region?region=17").status == 503);
|
|
deploying.enable_deploy({.gitea_base = "https://git.test",
|
|
.gitea_repository = "dingo/AEvolution",
|
|
.gitea_token = "gitea-secret",
|
|
.branch = "main",
|
|
.argo_server = "argo.test:443",
|
|
.argo_application = "aevolution-dev",
|
|
.argo_token = "argo-secret",
|
|
.argo_verify = false},
|
|
fake);
|
|
const auto status = must(JsonValue::parse(ask("GET", "/api/deploy").body));
|
|
const auto served = std::to_string(layout->region);
|
|
const auto next = std::string(must(status.member("next")->member("region")->string()));
|
|
CHECK(status.member("configured")->boolean() == true &&
|
|
status.member("current")->member("region")->string() == served &&
|
|
status.member("current")->member("world")->string() == "9831" &&
|
|
status.member("next")->member("wildlife_first")->string() ==
|
|
std::to_string(layout->wildlife_first + 100) &&
|
|
status.member("argo")->member("phase")->string() == "Succeeded" &&
|
|
status.member("git")->member("head")->string() == head &&
|
|
std::stoull(next) > layout->region);
|
|
CHECK(must(JsonValue::parse(ask("GET", "/api/deploy?argo=1").body)).member("current") ==
|
|
nullptr);
|
|
// Credentials only in headers; Argo's in-cluster hop may skip verification, Gitea's not.
|
|
for (const auto& request : seen)
|
|
CHECK(request.target.find("secret") == std::string::npos &&
|
|
std::ranges::count(request.headers,
|
|
std::pair<std::string, std::string>{
|
|
"Authorization", request.host == "argo.test"
|
|
? "Bearer argo-secret"
|
|
: "token gitea-secret"}) == 1 &&
|
|
request.verify == (request.host != "argo.test"));
|
|
// Refusals: a stale region number, a sync already running, a refused commit.
|
|
CHECK(ask("POST", "/api/deploy/region?region=" + std::to_string(std::stoull(next) + 1))
|
|
.status == 409);
|
|
argo_phase = "Running";
|
|
CHECK(ask("POST", "/api/deploy/region?region=" + next).status == 409);
|
|
argo_phase = "Succeeded";
|
|
commit_status = 409;
|
|
CHECK(ask("POST", "/api/deploy/region?region=" + next).status == 409);
|
|
commit_status = 201;
|
|
seen.clear();
|
|
const auto opened_region =
|
|
ask("POST", "/api/deploy/region?region=" + next + "&reason=fresh+start");
|
|
const auto result = must(JsonValue::parse(opened_region.body));
|
|
CHECK(opened_region.status == 200 && result.member("region")->string() == next &&
|
|
result.member("from")->string() == served &&
|
|
result.member("commit")->string() == made_commit &&
|
|
result.member("sync_started")->boolean() == true);
|
|
const auto commit = std::ranges::find_if(
|
|
seen, [](const HttpsRequest& r) { return r.method == "POST" && r.host == "git.test"; });
|
|
const auto sync = std::ranges::find_if(seen, [](const HttpsRequest& r) {
|
|
return r.method == "POST" && r.host == "argo.test";
|
|
});
|
|
CHECK(commit != seen.end() && sync != seen.end() &&
|
|
sync->target == "/api/v1/applications/aevolution-dev/sync" &&
|
|
sync->body == "{\"revision\":\"" + made_commit + "\",\"prune\":true}");
|
|
if (commit != seen.end()) {
|
|
const auto body = must(JsonValue::parse(commit->body, 1U << 20U));
|
|
CHECK(body.member("branch")->string() == "main" &&
|
|
std::string(must(body.member("message")->string())).find("open region " + next) !=
|
|
std::string::npos &&
|
|
std::string(must(body.member("message")->string())).find("ops@example.test") !=
|
|
std::string::npos &&
|
|
body.member("files")->array()->size() == 4);
|
|
const auto& first_file = body.member("files")->array()->at(0);
|
|
CHECK(first_file.member("path")->string() == region_switch_paths.at(0) &&
|
|
first_file.member("sha")->string() == std::string(40, '1') &&
|
|
first_file.member("operation")->string() == "update");
|
|
const auto encoded = std::string(must(first_file.member("content")->string()));
|
|
std::string decoded(encoded.size(), '\0');
|
|
const auto length =
|
|
EVP_DecodeBlock(reinterpret_cast<unsigned char*>(decoded.data()),
|
|
reinterpret_cast<const unsigned char*>(encoded.data()),
|
|
static_cast<int>(encoded.size()));
|
|
CHECK(length > 0);
|
|
decoded.resize(static_cast<std::size_t>(length) -
|
|
static_cast<std::size_t>(std::ranges::count(encoded, '=')));
|
|
CHECK(decoded.find("{name: REGION_ID, value: \"" + next + "\"}") != std::string::npos &&
|
|
decoded.find("--playtest-wildlife-first-id " +
|
|
std::to_string(layout->wildlife_first + 100)) != std::string::npos &&
|
|
decoded.find("in place of " + served + "; seeded wildlife") != std::string::npos);
|
|
}
|
|
}
|
|
|
|
// 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);
|
|
}
|