// ADR-0131 grant broker: bounded JSON, offline RS256 access-token checks, and real // PostgreSQL schema v39 identities, serials and logout revocation. Isolated world 9831. #include "evo/persistence/account_control_store.hpp" #include "evo/persistence/account_identity_store.hpp" #include "evo/persistence/region_lease_store.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)); } 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)); } } // namespace void run_grant_broker_tests() { json_tests(); const Realm realm; token_tests(realm); broker_tests(realm); }