Files
aevolution/apps/evo-dev-session/main.cpp
T
dingoandClaude Opus 5.5 8e319322f4 Implement M9.7 dev region sessions with durable no-effect intentions
Run a non-blocking TLS 1.3 session server inside evo-server's loop:
environment views come from the region's own field/terrain stores with an
explicitly empty organism presentation; admitted intentions ride the next
synthetic input (content unchanged) and return a durable no-effect outcome
from the host's final acknowledgement, or not_committed when dropped.
Sessions are bound to their connection, epochs close stale sessions, and
connections have bounded output, input rate and deadlines.

SessionClient and evo-client --connect consume one single-use grant per
Hello (refusals before admission keep it), reset to a fresh baseline on
every session, keep stale views visible and report in-flight intentions as
unknown after loss. evo-dev-session generates dev credentials, grant
bundles and runs a restart probe. The dev deployment gains a drill-time,
loopback-only listener with an optional Secret, enforced by the policy
check, and tools/ops/session-drill.sh. Protocol v1 gains IntentOutcome and
the capacity close reason before any deployment. ADR-0083 records the
maintainer-confirmed decisions; M8-dev/stage remains not passed and no
cluster change was made.

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

289 lines
13 KiB
C++

// M9.7 dev session operator tool (ADR-0083). Dev environment only.
//
// evo-dev-session credentials --environment dev --server-name NAME --out DIR [--days N]
// Writes dev-ca.pem, server.pem, server.key and grant.key into DIR (which must not
// already contain them). server.key and grant.key are secrets (owner-only on POSIX):
// they belong in the dev namespace Secret, never in images, logs or the repository.
// evo-dev-session grants --environment dev --key FILE --world N --frame N --region N
// --subject N --out FILE [--count 1..64] [--lifetime 60..3600]
// Writes COUNT single-use 108-byte grants for one test subject. Clients consume one
// per connection; the HMAC key itself never leaves the operator machine.
// evo-dev-session probe --connect HOST:PORT --server-name NAME --ca FILE --grants FILE
// [--expect-restart] [--timeout 10..600]
// Connects as a dev client, waits for a view, sends one intention and requires its
// durable no-effect acknowledgement. With --expect-restart it then waits (printing
// "probe awaiting-restart") for the connection to be lost and re-established at a
// newer epoch with a fresh baseline, and repeats the acknowledgement check.
// Prints "probe passed" on success. Used by tools/ops/session-drill.sh.
// Exit: 0 written/passed, 1 failure, 2 usage.
#include "evo/network/dev_credentials.hpp"
#include "evo/network/session_client.hpp"
#include <charconv>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
#ifndef _WIN32
#include <fcntl.h>
#include <unistd.h>
#endif
namespace {
using namespace evo::network;
std::optional<std::uint64_t> number(std::string_view text) {
std::uint64_t value{};
const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
if (error != std::errc{} || end != text.data() + text.size())
return std::nullopt;
return value;
}
// Exclusive create; secrets get owner-only permissions on POSIX.
bool write_new(const std::filesystem::path& path, std::span<const std::uint8_t> bytes,
bool secret) {
#ifdef _WIN32
(void)secret; // Windows ACLs are inherited from the chosen directory.
std::FILE* file = nullptr;
if (fopen_s(&file, path.string().c_str(), "wbx") != 0 || file == nullptr)
return false;
#else
const int fd =
::open(path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, secret ? 0600 : 0644);
if (fd < 0)
return false;
std::FILE* file = ::fdopen(fd, "wb");
if (file == nullptr) {
::close(fd);
return false;
}
#endif
const bool ok = std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size();
return std::fclose(file) == 0 && ok;
}
bool write_new(const std::filesystem::path& path, const std::string& text, bool secret) {
return write_new(path, {reinterpret_cast<const std::uint8_t*>(text.data()), text.size()},
secret);
}
struct Args {
std::vector<std::pair<std::string_view, std::string_view>> values;
[[nodiscard]] std::optional<std::string_view> get(std::string_view name) const {
for (const auto& [k, v] : values)
if (k == name)
return v;
return std::nullopt;
}
};
std::optional<Args> parse(int argc, char** argv) {
Args a;
for (int i = 2; i < argc; i += 2) {
if (i + 1 >= argc || std::string_view{argv[i]}.substr(0, 2) != "--")
return std::nullopt;
a.values.emplace_back(argv[i], argv[i + 1]);
}
return a;
}
int credentials(const Args& a) {
const auto out = a.get("--out");
const auto name = a.get("--server-name");
const auto days = number(a.get("--days").value_or("90"));
if (a.get("--environment") != "dev" || !out || !name || !days || *days > 825)
return 2;
const auto made = generate_dev_credentials(DeploymentEnvironment::dev, *name,
static_cast<std::uint32_t>(*days),
std::chrono::system_clock::now());
if (!made) {
std::fputs("credential generation failed\n", stderr);
return 1;
}
const std::filesystem::path dir{std::string{*out}};
std::error_code error;
std::filesystem::create_directories(dir, error);
if (!write_new(dir / "dev-ca.pem", made->authority_pem, false) ||
!write_new(dir / "server.pem", made->server_certificate_pem, false) ||
!write_new(dir / "server.key", made->server_key_pem, true) ||
!write_new(dir / "grant.key", format_grant_key(made->grant_key) + "\n", true)) {
std::fputs("refusing to overwrite or failed to write credential files\n", stderr);
return 1;
}
std::printf("wrote dev-ca.pem server.pem server.key grant.key for %.*s (dev only)\n",
static_cast<int>(name->size()), name->data());
return 0;
}
int grants(const Args& a) {
const auto key_path = a.get("--key");
const auto out = a.get("--out");
const auto world = number(a.get("--world").value_or(""));
const auto frame = number(a.get("--frame").value_or(""));
const auto region = number(a.get("--region").value_or(""));
const auto subject = number(a.get("--subject").value_or(""));
const auto count = number(a.get("--count").value_or("16"));
const auto lifetime = number(a.get("--lifetime").value_or("3600"));
if (a.get("--environment") != "dev" || !key_path || !out || !world || !frame || !region ||
!subject || !count || *count == 0 || *count > 64 || !lifetime || *lifetime < 60 ||
*lifetime > 3600)
return 2;
std::ifstream file{std::string{*key_path}};
const std::string text{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
const auto secret = parse_grant_key(text);
if (!secret) {
std::fputs("grant key must be 64 lowercase hex digits\n", stderr);
return 1;
}
const auto key = DevGrantKey::import(DeploymentEnvironment::dev, *secret);
if (!key)
return 1;
const auto now =
static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
std::vector<std::uint8_t> bundle;
for (std::uint64_t i = 0; i < *count; ++i) {
const auto id = random_grant_id();
if (!id)
return 1;
const auto grant =
key->issue({*id, *subject, {*world, *frame}, *region, now, now + *lifetime});
if (!grant) {
std::fputs("invalid grant claims\n", stderr);
return 1;
}
bundle.insert(bundle.end(), grant->begin(), grant->end());
}
if (!write_new(std::filesystem::path{std::string{*out}}, bundle, true)) {
std::fputs("refusing to overwrite or failed to write the grant bundle\n", stderr);
return 1;
}
std::printf("wrote %llu single-use dev grants for subject %llu, valid %llu s\n",
static_cast<unsigned long long>(*count), static_cast<unsigned long long>(*subject),
static_cast<unsigned long long>(*lifetime));
return 0;
}
std::vector<std::uint8_t> read_file(std::string_view path) {
std::ifstream file{std::string{path}, std::ios::binary};
return {std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
}
int probe(const Args& a, bool expect_restart) {
const auto connect = a.get("--connect");
const auto name = a.get("--server-name");
const auto ca = a.get("--ca");
const auto bundle_path = a.get("--grants");
const auto timeout = number(a.get("--timeout").value_or("240"));
if (!connect || !name || !ca || !bundle_path || !timeout || *timeout < 10 || *timeout > 600)
return 2;
const auto colon = connect->rfind(':');
if (colon == std::string_view::npos || colon == 0)
return 2;
const std::uint64_t port = number(connect->substr(colon + 1)).value_or(0);
const auto bundle = read_file(*bundle_path);
if (port == 0 || port > 65535 || bundle.empty() || bundle.size() % dev_grant_bytes != 0)
return 2;
SessionClientConfig config;
config.host = std::string{connect->substr(0, colon)};
config.port = static_cast<std::uint16_t>(port);
const auto pem = read_file(*ca);
config.trust = {{pem.begin(), pem.end()}, std::string{*name}};
for (std::size_t at = 0; at < bundle.size(); at += dev_grant_bytes) {
DevGrant grant{};
std::copy_n(bundle.begin() + static_cast<std::ptrdiff_t>(at), grant.size(), grant.begin());
config.grants.push_back(grant);
}
config.max_retry = std::chrono::milliseconds{2000};
auto made = SessionClient::create(std::move(config));
if (!made)
return 2;
auto& c = **made;
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{*timeout};
std::uint64_t sequence = 0, epoch = 0;
const auto failed = [](const char* why) {
std::printf("probe failed: %s\n", why);
return 1;
};
// One acknowledged round: a session newer than `after_epoch`, a view, one durable intent.
const auto round = [&](std::uint64_t after_epoch) -> const char* {
bool sent = false;
while (std::chrono::steady_clock::now() < deadline) {
c.poll(std::chrono::steady_clock::now());
for (const auto& e : c.take_events()) {
using Kind = ClientEvent::Kind;
if (e.kind == Kind::welcome)
std::printf("probe welcome session=%llu epoch=%llu tick=%llu commit=%llu\n",
static_cast<unsigned long long>(e.welcome.session),
static_cast<unsigned long long>(e.welcome.epoch),
static_cast<unsigned long long>(e.welcome.server_tick),
static_cast<unsigned long long>(e.welcome.commit_watermark));
else if (e.kind == Kind::closed)
std::printf("probe closed reason=%u\n", static_cast<unsigned>(e.reason));
else if (e.kind == Kind::lost)
std::puts("probe lost");
else if (e.kind == Kind::exhausted)
return "grants exhausted";
else if (e.kind == Kind::result && e.result.status != IntentStatus::admitted)
return "intention rejected";
else if (e.kind == Kind::outcome) {
if (e.outcome.finality != IntentFinality::committed_no_effect)
return "intention not committed";
std::printf("probe durable sequence=%llu tick=%llu commit=%llu\n",
static_cast<unsigned long long>(e.sequence),
static_cast<unsigned long long>(e.outcome.tick),
static_cast<unsigned long long>(e.outcome.commit_sequence));
epoch = c.welcome()->epoch;
return nullptr;
}
}
std::fflush(stdout);
const auto w = c.welcome();
if (!sent && w && w->epoch > after_epoch && c.latest_view() &&
c.environment().freshness() == evo::client::Freshness::current &&
c.send({++sequence, 0, 1000, 0}))
sent = true;
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
return "timeout";
};
if (const auto* why = round(0))
return failed(why);
if (expect_restart) {
std::puts("probe awaiting-restart");
std::fflush(stdout);
if (const auto* why = round(epoch))
return failed(why);
}
std::puts("probe passed");
return 0;
}
} // namespace
int main(int argc, char** argv) {
const auto args = parse(argc, argv);
const std::string_view command = argc > 1 ? argv[1] : "";
int code = 2;
if (args && command == "credentials")
code = credentials(*args);
else if (args && command == "grants")
code = grants(*args);
else if (command == "probe") {
// --expect-restart takes no value; strip it before pairing the rest.
std::vector<char*> rest{argv, argv + argc};
const bool restart = std::erase_if(rest, [](const char* x) {
return std::string_view{x} == "--expect-restart";
}) > 0;
const auto probe_args = parse(static_cast<int>(rest.size()), rest.data());
code = probe_args ? probe(*probe_args, restart) : 2;
}
if (code == 2)
std::fputs("usage: evo-dev-session credentials --environment dev --server-name NAME "
"--out DIR [--days N]\n"
" evo-dev-session grants --environment dev --key FILE --world N "
"--frame N --region N --subject N --out FILE [--count N] [--lifetime S]\n"
" evo-dev-session probe --connect HOST:PORT --server-name NAME --ca FILE "
"--grants FILE [--expect-restart] [--timeout S]\n",
stderr);
return code;
}