Files
aevolution/src/server/ops_http.cpp
T
dingoandClaude Opus 5.5 68880ba3b4
Foundation / checks (checks) (push) Successful in 42m13s
Foundation / checks (deploy) (push) Successful in 4m5s
Foundation / checks (ecs) (push) Successful in 2m25s
Foundation / checks (network) (push) Successful in 19m18s
Foundation / checks (postgres) (push) Successful in 44m19s
Foundation / checks (tsan) (push) Successful in 9m48s
Foundation / checks (client) (push) Failing after 12m6s
Foundation / postgres-tools (push) Skipped
Foundation / server-image (push) Skipped
Foundation / image (push) Skipped
ADR-0131: Keycloak grant broker and schema v39 account identities
evo-grant-broker verifies realm aeternalis access tokens offline (RS256 against
the pinned JWKS; audience aevolution-grants, client aevolution-game, verified
email) and issues 10-minute session grants:
- POST /grant routes to the region holding the account's life, or the default.
- POST /logout makes every issued grant stale and expires current control.
- GET /healthz.

Schema v39 maps (issuer, subject) to stable accounts with strictly increasing
serials. The binary ships in the server image. The DEV manifests are in
deploy/kubernetes/grant-broker-dev and are not yet enabled in region/dev; that
waits for the image promotion and the out-of-band Secrets and Ingress.

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

241 lines
9.6 KiB
C++

#include "evo/server/ops_http.hpp"
#include <arpa/inet.h>
#include <cerrno>
#include <charconv>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
namespace evo::server {
namespace {
using Clock = std::chrono::steady_clock;
const char* reason(int status) {
switch (status) {
case 200:
return "OK";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 404:
return "Not Found";
case 429:
return "Too Many Requests";
case 405:
return "Method Not Allowed";
case 431:
return "Request Header Fields Too Large";
case 503:
return "Service Unavailable";
default:
return "Internal Server Error";
}
}
std::string encode(const OpsResponse& r) {
std::string out = "HTTP/1.1 " + std::to_string(r.status) + " " + reason(r.status) +
"\r\nContent-Type: " + r.content_type +
"\r\nContent-Length: " + std::to_string(r.body.size()) +
"\r\nCache-Control: no-store\r\nConnection: close\r\n";
if (r.status == 405)
out += "Allow: GET, POST\r\n";
if (r.status == 401)
out += "WWW-Authenticate: Bearer\r\n";
return out + "\r\n" + r.body;
}
bool printable(std::string_view s) {
for (const char ch : s)
if (ch <= ' ' || ch > '~')
return false;
return true;
}
} // namespace
std::expected<std::unique_ptr<OpsServer>, OpsError> OpsServer::listen(std::string_view address) {
const auto colon = address.rfind(':');
if (colon == std::string_view::npos || colon + 1 >= address.size())
return std::unexpected{OpsError::address};
unsigned port{};
const auto digits = address.substr(colon + 1);
const auto [end, error] = std::from_chars(digits.data(), digits.data() + digits.size(), port);
if (error != std::errc{} || end != digits.data() + digits.size() || port > 65535)
return std::unexpected{OpsError::address};
auto host = std::string(address.substr(0, colon));
sockaddr_storage storage{};
socklen_t length{};
int family{};
if (host.size() >= 2 && host.front() == '[' && host.back() == ']') {
host = host.substr(1, host.size() - 2);
auto* v6 = reinterpret_cast<sockaddr_in6*>(&storage);
if (inet_pton(AF_INET6, host.c_str(), &v6->sin6_addr) != 1)
return std::unexpected{OpsError::address};
v6->sin6_family = AF_INET6;
v6->sin6_port = htons(static_cast<std::uint16_t>(port));
family = AF_INET6;
length = sizeof(sockaddr_in6);
} else {
auto* v4 = reinterpret_cast<sockaddr_in*>(&storage);
if (inet_pton(AF_INET, host.c_str(), &v4->sin_addr) != 1)
return std::unexpected{OpsError::address};
v4->sin_family = AF_INET;
v4->sin_port = htons(static_cast<std::uint16_t>(port));
family = AF_INET;
length = sizeof(sockaddr_in);
}
const int fd = ::socket(family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0)
return std::unexpected{OpsError::socket};
const int on = 1;
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);
if (::bind(fd, reinterpret_cast<sockaddr*>(&storage), length) != 0 || ::listen(fd, 16) != 0) {
::close(fd);
return std::unexpected{OpsError::socket};
}
sockaddr_storage bound{};
socklen_t bound_length = sizeof bound;
::getsockname(fd, reinterpret_cast<sockaddr*>(&bound), &bound_length);
const auto actual = family == AF_INET6
? ntohs(reinterpret_cast<sockaddr_in6*>(&bound)->sin6_port)
: ntohs(reinterpret_cast<sockaddr_in*>(&bound)->sin_port);
return std::unique_ptr<OpsServer>(new OpsServer(fd, actual));
}
OpsServer::~OpsServer() {
for (auto& c : connections_)
::close(c.fd);
::close(fd_);
}
void OpsServer::respond(Connection& c, const OpsHandler& handler) {
OpsResponse response;
const auto line_end = c.in.find("\r\n");
const std::string_view line = std::string_view(c.in).substr(0, line_end);
const auto first = line.find(' ');
const auto second = first == std::string_view::npos ? first : line.find(' ', first + 1);
if (second == std::string_view::npos || line.substr(second + 1).rfind("HTTP/1.", 0) != 0) {
response = {400, "bad request\n"};
} else {
const auto method = line.substr(0, first);
const auto path = line.substr(first + 1, second - first - 1);
if (method != "GET")
response = {405, "method not allowed\n"};
else if (path.empty() || path.front() != '/' || path.size() > 256 || !printable(path))
response = {400, "bad request\n"};
else
response = handler(path);
}
if (response.body.size() > max_response_bytes)
response = {500, "response too large\n"};
c.out = encode(response);
}
void OpsServer::respond_api(Connection& c, const ApiHandler& handler) {
OpsResponse response;
const std::string_view request = c.in;
const auto line_end = request.find("\r\n");
const auto line = request.substr(0, line_end);
const auto first = line.find(' ');
const auto second = first == std::string_view::npos ? first : line.find(' ', first + 1);
if (second == std::string_view::npos || line.substr(second + 1).rfind("HTTP/1.", 0) != 0) {
c.out = encode({400, "bad request\n"});
return;
}
const auto method = line.substr(0, first);
const auto path = line.substr(first + 1, second - first - 1);
std::string_view authorization;
bool has_body = false;
// Header lines up to the blank line; names are case-insensitive.
auto at = line_end + 2;
while (at < request.size()) {
const auto end = request.find("\r\n", at);
if (end == std::string_view::npos || end == at)
break;
const auto header = request.substr(at, end - at);
const auto colon = header.find(':');
if (colon != std::string_view::npos) {
std::string name(header.substr(0, colon));
for (auto& ch : name)
ch = static_cast<char>(ch >= 'A' && ch <= 'Z' ? ch - 'A' + 'a' : ch);
auto value = header.substr(colon + 1);
while (!value.empty() && value.front() == ' ')
value.remove_prefix(1);
if (name == "authorization")
authorization = value;
else if ((name == "content-length" && value != "0") || name == "transfer-encoding")
has_body = true;
}
at = end + 2;
}
if (method != "GET" && method != "POST")
response = {405, "method not allowed\n"};
else if (path.empty() || path.front() != '/' || path.size() > 256 || !printable(path) ||
has_body)
response = {400, "bad request\n"};
else
response = handler({method, path, authorization});
if (response.body.size() > max_response_bytes)
response = {500, "response too large\n"};
c.out = encode(response);
}
void OpsServer::serve(const OpsHandler& handler) {
serve_with(max_request_bytes, [&](Connection& c) { respond(c, handler); });
}
void OpsServer::serve_api(const ApiHandler& handler) {
serve_with(max_api_request_bytes, [&](Connection& c) { respond_api(c, handler); });
}
template <typename Answer>
void OpsServer::serve_with(std::size_t request_limit, const Answer& answer) {
const auto accepted_at = Clock::now();
for (std::size_t attempt = 0; attempt < max_accepts_per_serve; ++attempt) {
const int fd = ::accept4(fd_, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (fd < 0)
break; // EAGAIN: nothing pending (other errors: retried next call).
if (connections_.size() >= max_connections) {
::close(fd); // Bounded: excess connections are refused, never queued.
++refused_;
continue;
}
connections_.push_back({fd, {}, {}, 0, accepted_at + connection_deadline});
}
const auto now = Clock::now(); // Deadlines are judged after the bounded accept work.
for (auto it = connections_.begin(); it != connections_.end();) {
auto& c = *it;
bool done = false;
// Read before expiring: a complete request that waited behind a bounded host
// step is still answered; only incomplete or unsent work expires.
if (c.out.empty()) {
char chunk[1024];
const auto n = ::recv(c.fd, chunk, sizeof chunk, 0);
if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) {
done = true;
} else if (n > 0) {
c.in.append(chunk, static_cast<std::size_t>(n));
if (c.in.size() > request_limit)
c.out = encode({431, "request too large\n"});
else if (c.in.find("\r\n\r\n") != std::string::npos)
answer(c);
}
}
if (!done && !c.out.empty()) {
const auto n = ::send(c.fd, c.out.data() + c.sent, c.out.size() - c.sent, MSG_NOSIGNAL);
if (n > 0)
c.sent += static_cast<std::size_t>(n);
done = c.sent == c.out.size() ||
(n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR);
}
// Slow client: an incomplete request expires at the deadline; a response the
// client will not take gets one more deadline, then is dropped.
if (!done && now > c.deadline && (c.out.empty() || now > c.deadline + connection_deadline))
done = true;
if (done) {
::close(c.fd);
it = connections_.erase(it);
} else {
++it;
}
}
}
} // namespace evo::server