Files
aevolution/tests/quic_sessions.cpp
T
dingoandClaude Opus 5.5 7956143cd8
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 3m13s
Foundation / checks (client) (push) Successful in 12m12s
Foundation / checks (network) (push) Successful in 8m56s
Foundation / checks (tsan) (push) Successful in 7m42s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (postgres) (push) Canceled after 19m14s
Foundation / checks (checks) (push) Canceled after 31m28s
Add M10.3b session login over QUIC
Session protocol v1 session messages (Hello with grant, Welcome, Refresh,
RefreshResult, Close with reasons) on the QUIC reliable stream. RegionSessions
verifies grants with the issuer public keys and admits them through SessionControl:
a newer grant closes the account's old connection as superseded, expiry and epoch
advances close sessions, every close is announced and flushed. RegionSessionClient
logs in, refreshes in place and reports why a session ended. ADR-0091.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 21:12:00 -04:00

352 lines
15 KiB
C++

// M10.3b session login over QUIC (ADR-0091): grants verified by the region, newest grant
// wins, replay and stale grants, scope, expiry, refresh, epochs, rate and capacity
// limits, malformed and silent peers, client close and shutdown. The wall clock used for
// grants is injected; deadlines use the real monotonic clock.
#include "evo/client/region_session.hpp"
#include "evo/network/dev_credentials.hpp"
#include "evo/network/session_grant.hpp"
#include "evo/server/region_sessions.hpp"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <functional>
#include <optional>
#include <source_location>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace {
using namespace evo;
using namespace evo::network;
using client::RegionSessionClient;
using client::RegionSessionState;
using server::RegionSessionEvent;
using server::RegionSessions;
using Clock = std::chrono::steady_clock;
using Reason = SessionCloseReason;
void check(bool ok, std::source_location at = std::source_location::current()) {
if (!ok)
throw std::runtime_error("quic sessions line " + std::to_string(at.line()));
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
template <typename T>
const T& must(const std::optional<T>& o,
std::source_location at = std::source_location::current()) {
if (!o)
throw std::runtime_error("quic sessions missing value line " + std::to_string(at.line()));
return *o;
}
constexpr std::string_view name = "dev-region.evolution.test";
constexpr world::WorldIdentity world_id{7, 3};
constexpr std::uint64_t region = 11;
constexpr std::uint64_t start = 1'800'000'000;
struct Files {
std::filesystem::path dir;
std::string ca_pem;
std::filesystem::path ca, certificate, key;
};
Files credentials() {
const auto made = generate_dev_credentials(DeploymentEnvironment::dev, name, 1,
std::chrono::system_clock::now());
CHECK(made.has_value());
Files f;
f.dir = std::filesystem::temp_directory_path() / "evo-quic-sessions";
std::filesystem::remove_all(f.dir);
std::filesystem::create_directories(f.dir);
f.ca_pem = made->authority_pem;
f.ca = f.dir / "ca.pem";
f.certificate = f.dir / "server.pem";
f.key = f.dir / "server.key";
for (const auto& [path, text] : {std::pair{f.ca, made->authority_pem},
std::pair{f.certificate, made->server_certificate_pem},
std::pair{f.key, made->server_key_pem}}) {
std::ofstream out{path, std::ios::binary | std::ios::trunc};
out << text;
CHECK(out.good());
}
return f;
}
AccountId account(std::uint8_t tag) {
AccountId a;
a.bytes.fill(tag);
return a;
}
// The issuer's dev key from a fixed scalar, so the same key can also sign as "stage".
std::array<std::uint8_t, grant_private_key_bytes> scalar() {
std::array<std::uint8_t, grant_private_key_bytes> s{};
s.back() = 0x2A;
return s;
}
struct Issuer {
GrantSigningKey key = *GrantSigningKey::import(DeploymentEnvironment::dev, 1, scalar());
WireGrant grant(const AccountId& who, std::uint64_t serial, std::uint64_t issued = start,
std::uint64_t lifetime = 60, std::uint64_t in_region = region) const {
GrantClaims c;
c.grant_id = 500 + serial;
c.account = who;
c.serial = serial;
c.world = world_id;
c.region = in_region;
c.issued_at = issued;
c.expires_at = issued + lifetime;
const auto g = key.sign(c);
CHECK(g.has_value());
return *g;
}
};
struct Harness {
explicit Harness(const Files& f, std::size_t max_sessions = 4,
std::uint32_t region_attempts = 64)
: files{f} {
server::RegionSessionsConfig c;
c.transport.certificate_pem_file = f.certificate.string();
c.transport.key_pem_file = f.key.string();
c.control.environment = DeploymentEnvironment::dev;
c.control.world = world_id;
c.control.region = region;
c.control.epoch = 5;
c.control.max_sessions = max_sessions;
c.control.max_account_attempts = 16;
c.control.max_region_attempts = region_attempts;
c.issuer_keys.push_back({1, *issuer.key.public_key()});
c.hello_deadline = std::chrono::milliseconds{500};
c.close_flush = std::chrono::milliseconds{300};
auto made = RegionSessions::create(std::move(c));
CHECK(made.has_value());
server = std::move(*made);
}
std::unique_ptr<RegionSessionClient> connect(const WireGrant& grant) {
client::RegionSessionClientConfig c;
c.transport.port = server->port();
c.transport.server_name = std::string{name};
c.transport.authority_pem = files.ca_pem;
c.transport.authority_pem_file = files.ca.string();
c.grant = grant;
auto made = RegionSessionClient::connect(std::move(c), Clock::now());
CHECK(made.has_value());
clients.push_back(made->get());
return std::move(*made);
}
std::unique_ptr<quic::Endpoint> raw() {
quic::ClientConfig c;
c.port = server->port();
c.server_name = std::string{name};
c.authority_pem = files.ca_pem;
c.authority_pem_file = files.ca.string();
auto made = quic::Endpoint::connect(c);
CHECK(made.has_value());
return std::move(*made);
}
void pump() {
server->poll(epoch, now_seconds, Clock::now());
for (auto& e : server->take_events())
events.push_back(std::move(e));
for (auto* c : clients)
c->poll(Clock::now());
}
bool until(const std::function<bool()>& done,
std::chrono::milliseconds limit = std::chrono::milliseconds{10000}) {
const auto end = Clock::now() + limit;
while (Clock::now() < end) {
pump();
if (done())
return true;
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
pump();
return done();
}
bool settled(RegionSessionClient& c) {
return until([&] {
return c.state() == RegionSessionState::established ||
c.state() == RegionSessionState::closed;
});
}
bool has_event(RegionSessionEvent::Kind kind, Reason reason, std::uint64_t session = 0) const {
return std::ranges::any_of(events, [&](const RegionSessionEvent& e) {
return e.kind == kind &&
(kind == RegionSessionEvent::Kind::opened || e.reason == reason) &&
(session == 0 || e.session == session);
});
}
void forget(const RegionSessionClient* c) {
std::erase(clients, c);
}
const Files& files;
Issuer issuer;
std::unique_ptr<RegionSessions> server;
std::vector<RegionSessionClient*> clients;
std::vector<RegionSessionEvent> events;
std::uint64_t epoch{5}, now_seconds{start};
};
bool refused_with(Harness& h, const WireGrant& grant, Reason reason) {
auto c = h.connect(grant);
const bool ok = h.settled(*c) && c->state() == RegionSessionState::closed &&
c->close_reason() == reason && !c->welcome();
h.forget(c.get());
return ok;
}
// A raw QUIC peer: sends `bytes` (or nothing) and returns the server's Close reason.
std::optional<Reason> raw_peer(Harness& h, const std::optional<std::vector<std::uint8_t>>& bytes) {
auto peer = h.raw();
std::optional<Reason> reason;
quic::ConnectionId id = 0;
const bool done = h.until([&] {
for (auto& e : peer->poll()) {
if (e.kind == quic::EventKind::connected) {
id = e.connection;
if (bytes)
CHECK(peer->send_message(id, *bytes).has_value());
} else if (e.kind == quic::EventKind::message) {
const auto m = decode_session(e.bytes);
if (m && std::holds_alternative<SessionClose>(*m))
reason = std::get<SessionClose>(*m).reason;
}
}
return reason.has_value();
});
CHECK(done);
return reason;
}
void login_rules(const Files& f) {
Harness h{f};
const auto alice = account(1), bob = account(2), carol = account(3);
// Login and Welcome.
auto a1 = h.connect(h.issuer.grant(alice, 1));
CHECK(h.settled(*a1) && a1->state() == RegionSessionState::established);
const auto& w = must(a1->welcome());
CHECK(w.epoch == 5 && w.world == world_id.world && w.frame == world_id.frame &&
w.region == region && w.expires_at == start + 60 && w.server_seconds == start);
CHECK(h.server->holder(alice) == w.session && h.server->sessions() == 1);
CHECK(h.has_event(RegionSessionEvent::Kind::opened, {}, w.session));
CHECK(std::ranges::all_of(h.events, [&](const RegionSessionEvent& e) {
return e.account.empty() || e.account == log_label(alice) || e.account == log_label(bob) ||
e.account == log_label(carol);
}));
// Replay of the same grant.
CHECK(refused_with(h, h.issuer.grant(alice, 1), Reason::stale_grant));
CHECK(h.server->holder(alice) == w.session);
// Duplicate login: the newer grant takes over; the old connection is told why.
auto a2 = h.connect(h.issuer.grant(alice, 3));
CHECK(h.settled(*a2) && a2->state() == RegionSessionState::established);
CHECK(h.until([&] { return a1->state() == RegionSessionState::closed; }));
CHECK(a1->close_reason() == Reason::superseded);
CHECK(h.has_event(RegionSessionEvent::Kind::closed, Reason::superseded, w.session));
CHECK(h.server->holder(alice) == must(a2->welcome()).session && h.server->sessions() == 1);
// A stolen older grant (serial 2, still unexpired) cannot take control back.
CHECK(refused_with(h, h.issuer.grant(alice, 2), Reason::stale_grant));
CHECK(a2->state() == RegionSessionState::established);
// Refresh in place: accepted, then stale, then another account's grant.
CHECK(a2->refresh(h.issuer.grant(alice, 4, start + 30)));
std::optional<SessionRefreshResult> r;
CHECK(h.until([&] { return (r = a2->take_refresh_result()).has_value(); }));
CHECK(must(r).status == 0 && must(r).expires_at == start + 90 &&
must(a2->welcome()).expires_at == start + 90);
CHECK(a2->refresh(h.issuer.grant(alice, 4, start + 30)));
CHECK(h.until([&] { return (r = a2->take_refresh_result()).has_value(); }));
CHECK(must(r).status == static_cast<std::uint8_t>(Reason::stale_grant));
CHECK(a2->refresh(h.issuer.grant(bob, 9)));
CHECK(h.until([&] { return (r = a2->take_refresh_result()).has_value(); }));
CHECK(must(r).status == static_cast<std::uint8_t>(Reason::unauthenticated));
CHECK(a2->state() == RegionSessionState::established &&
must(a2->welcome()).expires_at == start + 90);
// Scope and authenticity.
CHECK(refused_with(h, h.issuer.grant(bob, 1, start, 60, region + 1), Reason::wrong_scope));
const auto stage = *GrantSigningKey::import(DeploymentEnvironment::stage, 1, scalar());
GrantClaims staged;
staged.grant_id = 1;
staged.account = bob;
staged.serial = 1;
staged.world = world_id;
staged.region = region;
staged.issued_at = start;
staged.expires_at = start + 60;
CHECK(refused_with(h, *stage.sign(staged), Reason::wrong_scope)); // Stage grant, dev region.
const auto stranger = *GrantSigningKey::generate(DeploymentEnvironment::dev, 1);
CHECK(refused_with(h, *stranger.sign(staged), Reason::unauthenticated)); // Not our issuer.
auto forged = h.issuer.grant(bob, 1);
forged.at(40) ^= 1;
CHECK(refused_with(h, forged, Reason::unauthenticated));
// Expiry at login and during a session (injected wall clock).
CHECK(refused_with(h, h.issuer.grant(bob, 1, start - 120), Reason::expired));
auto b = h.connect(h.issuer.grant(bob, 2));
CHECK(h.settled(*b) && b->state() == RegionSessionState::established);
h.now_seconds = start + 60; // Bob's grant ends; Alice refreshed until start + 90.
CHECK(h.until([&] { return b->state() == RegionSessionState::closed; }));
CHECK(b->close_reason() == Reason::expired && a2->state() == RegionSessionState::established);
// Client close releases control.
auto c = h.connect(h.issuer.grant(carol, 1, start + 60));
CHECK(h.settled(*c) && c->state() == RegionSessionState::established);
const auto carol_session = must(c->welcome()).session;
c->close();
CHECK(h.until([&] { return !h.server->holder(carol); }));
CHECK(h.has_event(RegionSessionEvent::Kind::closed, Reason::client_closed, carol_session));
// Malformed and silent peers.
CHECK(raw_peer(h, std::nullopt) == Reason::timeout);
CHECK(raw_peer(h, std::vector<std::uint8_t>{1, 2, 3}) == Reason::protocol);
auto future = encode_session(SessionHello{0, h.issuer.grant(carol, 2, start + 60)});
future.at(4) = 2;
CHECK(raw_peer(h, future) == Reason::unsupported_version);
CHECK(raw_peer(h, encode_session(SessionClose{Reason::client_closed})) == Reason::protocol);
CHECK(raw_peer(h, encode_session(SessionHello{1, h.issuer.grant(carol, 3, start + 60)})) ==
Reason::protocol); // Unknown required feature.
// A new ownership epoch ends every session.
h.epoch = 6;
CHECK(h.until([&] { return a2->state() == RegionSessionState::closed; }));
CHECK(a2->close_reason() == Reason::stale_epoch && h.server->sessions() == 0);
auto a3 = h.connect(h.issuer.grant(alice, 5, start + 60));
CHECK(h.settled(*a3) && must(a3->welcome()).epoch == 6);
// Shutdown tells every client.
h.server->shutdown(Clock::now());
CHECK(h.until([&] { return a3->state() == RegionSessionState::closed; }));
CHECK(a3->close_reason() == Reason::shutdown);
CHECK(h.until([&] { return h.server->connections() == 0; }));
}
void limits(const Files& f) {
{
Harness h{f, 1};
auto a = h.connect(h.issuer.grant(account(1), 1));
CHECK(h.settled(*a) && a->state() == RegionSessionState::established);
CHECK(refused_with(h, h.issuer.grant(account(2), 1), Reason::capacity));
a->close();
CHECK(h.until([&] { return h.server->sessions() == 0; }));
// The refused grant was not consumed.
auto b = h.connect(h.issuer.grant(account(2), 1));
CHECK(h.settled(*b) && b->state() == RegionSessionState::established);
}
{
Harness h{f, 4, 3};
for (std::uint64_t serial = 1; serial <= 3; ++serial) {
auto c = h.connect(h.issuer.grant(account(1), serial));
CHECK(h.settled(*c) && c->state() == RegionSessionState::established);
h.forget(c.get());
}
CHECK(refused_with(h, h.issuer.grant(account(1), 4), Reason::rate_limited));
}
}
} // namespace
int main() try {
const auto files = credentials();
login_rules(files);
limits(files);
std::filesystem::remove_all(files.dir);
std::puts("quic session tests passed");
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
return 1;
}