ADR-0131: Keycloak grant broker and schema v39 account identities
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
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
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>
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
#include "evo/server/broker/access_token.hpp"
|
||||
|
||||
#include "evo/server/broker/json.hpp"
|
||||
|
||||
#include <openssl/bn.h>
|
||||
#include <openssl/core_names.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/param_build.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
|
||||
namespace evo::server::broker {
|
||||
namespace {
|
||||
constexpr std::string_view alphabet =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
std::shared_ptr<void> rsa_public_key(std::span<const std::uint8_t> n,
|
||||
std::span<const std::uint8_t> e) {
|
||||
std::unique_ptr<BIGNUM, decltype(&BN_free)> modulus{
|
||||
BN_bin2bn(n.data(), static_cast<int>(n.size()), nullptr), BN_free};
|
||||
std::unique_ptr<BIGNUM, decltype(&BN_free)> exponent{
|
||||
BN_bin2bn(e.data(), static_cast<int>(e.size()), nullptr), BN_free};
|
||||
std::unique_ptr<OSSL_PARAM_BLD, decltype(&OSSL_PARAM_BLD_free)> build{OSSL_PARAM_BLD_new(),
|
||||
OSSL_PARAM_BLD_free};
|
||||
if (!modulus || !exponent || !build ||
|
||||
OSSL_PARAM_BLD_push_BN(build.get(), OSSL_PKEY_PARAM_RSA_N, modulus.get()) != 1 ||
|
||||
OSSL_PARAM_BLD_push_BN(build.get(), OSSL_PKEY_PARAM_RSA_E, exponent.get()) != 1)
|
||||
return nullptr;
|
||||
std::unique_ptr<OSSL_PARAM, decltype(&OSSL_PARAM_free)> params{
|
||||
OSSL_PARAM_BLD_to_param(build.get()), OSSL_PARAM_free};
|
||||
std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> context{
|
||||
EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr), EVP_PKEY_CTX_free};
|
||||
EVP_PKEY* key = nullptr;
|
||||
if (!params || !context || EVP_PKEY_fromdata_init(context.get()) != 1 ||
|
||||
EVP_PKEY_fromdata(context.get(), &key, EVP_PKEY_PUBLIC_KEY, params.get()) != 1 ||
|
||||
key == nullptr)
|
||||
return nullptr;
|
||||
std::shared_ptr<void> owned{key, [](void* p) { EVP_PKEY_free(static_cast<EVP_PKEY*>(p)); }};
|
||||
if (EVP_PKEY_get_bits(key) < 2048)
|
||||
return nullptr;
|
||||
return owned;
|
||||
}
|
||||
|
||||
bool verify_rs256(void* key, std::string_view signed_part, std::span<const std::uint8_t> sig) {
|
||||
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> context{EVP_MD_CTX_new(),
|
||||
EVP_MD_CTX_free};
|
||||
return context &&
|
||||
EVP_DigestVerifyInit(context.get(), nullptr, EVP_sha256(), nullptr,
|
||||
static_cast<EVP_PKEY*>(key)) == 1 &&
|
||||
EVP_DigestVerify(context.get(), sig.data(), sig.size(),
|
||||
reinterpret_cast<const unsigned char*>(signed_part.data()),
|
||||
signed_part.size()) == 1;
|
||||
}
|
||||
|
||||
std::optional<JsonValue> json_segment(std::string_view segment) {
|
||||
const auto bytes = base64url_decode(segment);
|
||||
if (!bytes)
|
||||
return std::nullopt;
|
||||
return JsonValue::parse(
|
||||
std::string_view{reinterpret_cast<const char*>(bytes->data()), bytes->size()});
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::optional<std::vector<std::uint8_t>> base64url_decode(std::string_view text) {
|
||||
if (text.size() % 4 == 1)
|
||||
return std::nullopt;
|
||||
std::vector<std::uint8_t> out;
|
||||
out.reserve(text.size() * 3 / 4);
|
||||
std::uint32_t buffer = 0;
|
||||
int bits = 0;
|
||||
for (const char ch : text) {
|
||||
std::uint32_t value{};
|
||||
if (ch >= 'A' && ch <= 'Z')
|
||||
value = static_cast<std::uint32_t>(ch - 'A');
|
||||
else if (ch >= 'a' && ch <= 'z')
|
||||
value = static_cast<std::uint32_t>(ch - 'a' + 26);
|
||||
else if (ch >= '0' && ch <= '9')
|
||||
value = static_cast<std::uint32_t>(ch - '0' + 52);
|
||||
else if (ch == '-')
|
||||
value = 62;
|
||||
else if (ch == '_')
|
||||
value = 63;
|
||||
else
|
||||
return std::nullopt; // No padding or other characters in JWT segments.
|
||||
buffer = (buffer << 6U) | value;
|
||||
bits += 6;
|
||||
if (bits >= 8) {
|
||||
bits -= 8;
|
||||
out.push_back(
|
||||
static_cast<std::uint8_t>((buffer >> static_cast<unsigned>(bits)) & 0xFFU));
|
||||
}
|
||||
}
|
||||
// Leftover bits must be zero (canonical encoding).
|
||||
if (bits > 0 && (buffer & ((1U << static_cast<unsigned>(bits)) - 1U)) != 0)
|
||||
return std::nullopt;
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string base64_encode(std::span<const std::uint8_t> bytes) {
|
||||
std::string out;
|
||||
out.reserve((bytes.size() + 2) / 3 * 4);
|
||||
for (std::size_t i = 0; i < bytes.size(); i += 3) {
|
||||
const std::uint32_t chunk =
|
||||
(std::uint32_t{bytes[i]} << 16U) |
|
||||
(i + 1 < bytes.size() ? std::uint32_t{bytes[i + 1]} << 8U : 0U) |
|
||||
(i + 2 < bytes.size() ? std::uint32_t{bytes[i + 2]} : 0U);
|
||||
out.push_back(alphabet[(chunk >> 18U) & 63U]);
|
||||
out.push_back(alphabet[(chunk >> 12U) & 63U]);
|
||||
out.push_back(i + 1 < bytes.size() ? alphabet[(chunk >> 6U) & 63U] : '=');
|
||||
out.push_back(i + 2 < bytes.size() ? alphabet[chunk & 63U] : '=');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::expected<TokenVerifier, TokenError> TokenVerifier::from_jwks(std::string_view jwks,
|
||||
AccessTokenRules rules) {
|
||||
const auto document = JsonValue::parse(jwks);
|
||||
const auto* keys = document ? document->member("keys") : nullptr;
|
||||
if (!keys || !keys->array() || rules.issuer.empty() || rules.audience.empty() ||
|
||||
rules.authorized_party.empty())
|
||||
return std::unexpected{TokenError::malformed};
|
||||
std::vector<Key> usable;
|
||||
for (const auto& entry : *keys->array()) {
|
||||
const auto field = [&](std::string_view name) -> std::optional<std::string_view> {
|
||||
const auto* value = entry.member(name);
|
||||
return value ? value->string() : std::nullopt;
|
||||
};
|
||||
const auto kty = field("kty");
|
||||
const auto use = field("use");
|
||||
const auto alg = field("alg");
|
||||
const auto kid = field("kid");
|
||||
const auto n = field("n");
|
||||
const auto e = field("e");
|
||||
if (kty != "RSA" || !kid || kid->empty() || !n || !e || (use && *use != "sig") ||
|
||||
(alg && *alg != "RS256"))
|
||||
continue;
|
||||
const auto modulus = base64url_decode(*n);
|
||||
const auto exponent = base64url_decode(*e);
|
||||
if (!modulus || !exponent)
|
||||
continue;
|
||||
if (auto key = rsa_public_key(*modulus, *exponent))
|
||||
usable.push_back({std::string(*kid), std::move(key)});
|
||||
}
|
||||
if (usable.empty())
|
||||
return std::unexpected{TokenError::unknown_key};
|
||||
return TokenVerifier{std::move(usable), std::move(rules)};
|
||||
}
|
||||
|
||||
std::expected<AccessTokenClaims, TokenError>
|
||||
TokenVerifier::verify(std::string_view token, std::uint64_t now_seconds) const {
|
||||
if (token.empty() || token.size() > max_access_token_bytes)
|
||||
return std::unexpected{TokenError::malformed};
|
||||
const auto first = token.find('.');
|
||||
const auto second = first == std::string_view::npos ? first : token.find('.', first + 1);
|
||||
if (second == std::string_view::npos || token.find('.', second + 1) != std::string_view::npos)
|
||||
return std::unexpected{TokenError::malformed};
|
||||
const auto header = json_segment(token.substr(0, first));
|
||||
const auto payload = json_segment(token.substr(first + 1, second - first - 1));
|
||||
const auto signature = base64url_decode(token.substr(second + 1));
|
||||
if (!header || !payload || !signature || header->kind() != JsonValue::Kind::object ||
|
||||
payload->kind() != JsonValue::Kind::object)
|
||||
return std::unexpected{TokenError::malformed};
|
||||
|
||||
const auto* alg = header->member("alg");
|
||||
const auto* kid = header->member("kid");
|
||||
if (!alg || alg->string() != "RS256" || header->member("crit") != nullptr)
|
||||
return std::unexpected{TokenError::unsupported_algorithm};
|
||||
const auto key_id = kid ? kid->string() : std::nullopt;
|
||||
const auto key = std::ranges::find_if(
|
||||
keys_, [&](const Key& candidate) { return key_id && candidate.kid == *key_id; });
|
||||
if (key == keys_.end())
|
||||
return std::unexpected{TokenError::unknown_key};
|
||||
if (!verify_rs256(key->public_key.get(), token.substr(0, second), *signature))
|
||||
return std::unexpected{TokenError::bad_signature};
|
||||
|
||||
// Only claims under a verified signature are read from here on.
|
||||
const auto text = [&](std::string_view name) -> std::optional<std::string_view> {
|
||||
const auto* value = payload->member(name);
|
||||
return value ? value->string() : std::nullopt;
|
||||
};
|
||||
const auto number = [&](std::string_view name) -> std::optional<std::uint64_t> {
|
||||
const auto* value = payload->member(name);
|
||||
return value ? value->integer() : std::nullopt;
|
||||
};
|
||||
if (text("iss") != rules_.issuer)
|
||||
return std::unexpected{TokenError::wrong_issuer};
|
||||
const auto* aud = payload->member("aud");
|
||||
bool audience = aud && aud->string() == rules_.audience;
|
||||
if (aud && aud->array())
|
||||
audience = std::ranges::any_of(*aud->array(), [&](const JsonValue& entry) {
|
||||
return entry.string() == rules_.audience;
|
||||
});
|
||||
if (!audience)
|
||||
return std::unexpected{TokenError::wrong_audience};
|
||||
if (text("azp") != rules_.authorized_party)
|
||||
return std::unexpected{TokenError::wrong_party};
|
||||
if (text("typ") != "Bearer") // Keycloak access tokens; ID tokens say "ID".
|
||||
return std::unexpected{TokenError::wrong_type};
|
||||
const auto expires = number("exp");
|
||||
if (!expires || now_seconds >= *expires + rules_.leeway_seconds)
|
||||
return std::unexpected{TokenError::expired};
|
||||
if (const auto* nbf = payload->member("nbf")) {
|
||||
const auto not_before = nbf->integer();
|
||||
if (!not_before || *not_before > now_seconds + rules_.leeway_seconds)
|
||||
return std::unexpected{TokenError::not_yet_valid};
|
||||
}
|
||||
const auto* verified = payload->member("email_verified");
|
||||
if (!verified || verified->boolean() != true)
|
||||
return std::unexpected{TokenError::unverified_email};
|
||||
const auto subject = text("sub");
|
||||
if (!subject || subject->empty() || subject->size() > 255)
|
||||
return std::unexpected{TokenError::missing_subject};
|
||||
return AccessTokenClaims{rules_.issuer, std::string(*subject), *expires};
|
||||
}
|
||||
} // namespace evo::server::broker
|
||||
@@ -0,0 +1,150 @@
|
||||
#include "evo/server/broker/grant_broker.hpp"
|
||||
|
||||
#include "evo/persistence/account_identity_store.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <string_view>
|
||||
|
||||
namespace evo::server::broker {
|
||||
namespace {
|
||||
constexpr std::size_t max_tracked_subjects = 4096;
|
||||
|
||||
OpsResponse json(int status, std::string body) {
|
||||
return {status, std::move(body), "application/json"};
|
||||
}
|
||||
OpsResponse error(int status, std::string_view code) {
|
||||
return json(status, "{\"error\":\"" + std::string(code) + "\"}\n");
|
||||
}
|
||||
const char* token_error(TokenError e) {
|
||||
switch (e) {
|
||||
case TokenError::expired:
|
||||
return "token_expired";
|
||||
case TokenError::unverified_email:
|
||||
return "email_not_verified";
|
||||
case TokenError::wrong_audience:
|
||||
case TokenError::wrong_party:
|
||||
case TokenError::wrong_issuer:
|
||||
case TokenError::wrong_type:
|
||||
return "token_not_for_this_service";
|
||||
default:
|
||||
return "invalid_token";
|
||||
}
|
||||
}
|
||||
std::string uuid_text(const persistence::Uuid& id) {
|
||||
constexpr std::string_view digits = "0123456789abcdef";
|
||||
std::string out;
|
||||
for (std::size_t i = 0; i < id.size(); ++i) {
|
||||
if (i == 4 || i == 6 || i == 8 || i == 10)
|
||||
out.push_back('-');
|
||||
out.push_back(digits[id[i] >> 4U]);
|
||||
out.push_back(digits[id[i] & 0x0FU]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// JSON string content for operator-configured names (endpoint, server name).
|
||||
std::string escaped(std::string_view text) {
|
||||
std::string out;
|
||||
for (const char ch : text) {
|
||||
if (ch == '"' || ch == '\\')
|
||||
out.push_back('\\');
|
||||
if (static_cast<unsigned char>(ch) >= 0x20)
|
||||
out.push_back(ch);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
GrantBroker::GrantBroker(BrokerConfig config, TokenVerifier verifier, network::GrantSigningKey key,
|
||||
BrokerConnect connect, GrantIdSource ids)
|
||||
: config_{std::move(config)}, verifier_{std::move(verifier)}, key_{std::move(key)},
|
||||
connect_{std::move(connect)}, ids_{std::move(ids)} {}
|
||||
|
||||
persistence::Postgres* GrantBroker::database() {
|
||||
if (!db_ && connect_)
|
||||
db_ = connect_();
|
||||
return db_.get();
|
||||
}
|
||||
|
||||
OpsResponse GrantBroker::handle(const ApiRequest& request, std::uint64_t now_seconds) {
|
||||
if (request.path == "/healthz")
|
||||
return request.method == "GET" ? OpsResponse{200, "ok\n"}
|
||||
: OpsResponse{405, "method not allowed\n"};
|
||||
if (request.path != "/grant" && request.path != "/logout")
|
||||
return {404, "not found\n"};
|
||||
if (request.method != "POST")
|
||||
return {405, "method not allowed\n"};
|
||||
auto authorization = request.authorization;
|
||||
constexpr std::string_view scheme = "bearer ";
|
||||
if (authorization.size() <= scheme.size() ||
|
||||
!std::ranges::equal(authorization.substr(0, scheme.size()), scheme,
|
||||
[](char a, char b) { return (a | 0x20) == b; }))
|
||||
return error(401, "missing_token");
|
||||
authorization.remove_prefix(scheme.size());
|
||||
const auto claims = verifier_.verify(authorization, now_seconds);
|
||||
if (!claims)
|
||||
return error(401, token_error(claims.error()));
|
||||
return request.path == "/grant" ? issue(*claims, now_seconds) : logout(*claims);
|
||||
}
|
||||
|
||||
OpsResponse GrantBroker::issue(const AccessTokenClaims& claims, std::uint64_t now_seconds) {
|
||||
const auto previous = last_grant_.find(claims.subject);
|
||||
if (previous != last_grant_.end() &&
|
||||
now_seconds < previous->second + static_cast<std::uint64_t>(config_.min_interval.count()))
|
||||
return error(429, "too_many_requests");
|
||||
auto* db = database();
|
||||
if (db == nullptr)
|
||||
return error(503, "unavailable");
|
||||
const auto issued = persistence::issue_account_grant(*db, config_.world, claims.issuer,
|
||||
claims.subject, config_.db_timeout);
|
||||
if (!issued) {
|
||||
if (issued.error() != persistence::AccountIdentityError::invalid)
|
||||
db_.reset();
|
||||
return error(503, "unavailable");
|
||||
}
|
||||
const auto region = issued->home_region.value_or(config_.default_region);
|
||||
const auto route = std::ranges::find(config_.routes, region, &BrokerRoute::region);
|
||||
if (route == config_.routes.end())
|
||||
return error(503, "region_unavailable");
|
||||
|
||||
network::GrantClaims grant;
|
||||
if (!ids_ || !ids_(grant.grant_id) || grant.grant_id == 0)
|
||||
return error(503, "unavailable");
|
||||
grant.account.bytes = issued->account;
|
||||
grant.serial = issued->serial;
|
||||
grant.world = {config_.world, config_.frame};
|
||||
grant.region = region;
|
||||
grant.issued_at = now_seconds;
|
||||
grant.expires_at = now_seconds + config_.grant_lifetime_seconds;
|
||||
const auto signed_grant = key_.sign(grant);
|
||||
if (!signed_grant)
|
||||
return error(503, "unavailable");
|
||||
|
||||
if (last_grant_.size() >= max_tracked_subjects && previous == last_grant_.end())
|
||||
std::erase_if(last_grant_, [&](const auto& entry) {
|
||||
return entry.second + static_cast<std::uint64_t>(config_.min_interval.count()) <=
|
||||
now_seconds;
|
||||
});
|
||||
if (last_grant_.size() < max_tracked_subjects)
|
||||
last_grant_[claims.subject] = now_seconds;
|
||||
return json(200, "{\"grant\":\"" + base64_encode(*signed_grant) + "\",\"account\":\"" +
|
||||
uuid_text(issued->account) + "\",\"region\":" + std::to_string(region) +
|
||||
",\"endpoint\":\"" + escaped(route->endpoint) + "\",\"server_name\":\"" +
|
||||
escaped(route->server_name) +
|
||||
"\",\"expires_at\":" + std::to_string(grant.expires_at) + "}\n");
|
||||
}
|
||||
|
||||
OpsResponse GrantBroker::logout(const AccessTokenClaims& claims) {
|
||||
auto* db = database();
|
||||
if (db == nullptr)
|
||||
return error(503, "unavailable");
|
||||
const auto revoked = persistence::revoke_account_grants(*db, config_.world, claims.issuer,
|
||||
claims.subject, config_.db_timeout);
|
||||
if (!revoked) {
|
||||
if (revoked.error() != persistence::AccountIdentityError::invalid)
|
||||
db_.reset();
|
||||
return error(503, "unavailable");
|
||||
}
|
||||
last_grant_.erase(claims.subject);
|
||||
return json(200, std::string("{\"revoked\":") + (*revoked ? "true" : "false") + "}\n");
|
||||
}
|
||||
} // namespace evo::server::broker
|
||||
@@ -0,0 +1,301 @@
|
||||
#include "evo/server/broker/json.hpp"
|
||||
|
||||
#include <charconv>
|
||||
#include <limits>
|
||||
|
||||
namespace evo::server::broker {
|
||||
namespace {
|
||||
void append_utf8(std::string& out, std::uint32_t code) {
|
||||
if (code < 0x80) {
|
||||
out.push_back(static_cast<char>(code));
|
||||
} else if (code < 0x800) {
|
||||
out.push_back(static_cast<char>(0xC0 | (code >> 6U)));
|
||||
out.push_back(static_cast<char>(0x80 | (code & 0x3FU)));
|
||||
} else if (code < 0x10000) {
|
||||
out.push_back(static_cast<char>(0xE0 | (code >> 12U)));
|
||||
out.push_back(static_cast<char>(0x80 | ((code >> 6U) & 0x3FU)));
|
||||
out.push_back(static_cast<char>(0x80 | (code & 0x3FU)));
|
||||
} else {
|
||||
out.push_back(static_cast<char>(0xF0 | (code >> 18U)));
|
||||
out.push_back(static_cast<char>(0x80 | ((code >> 12U) & 0x3FU)));
|
||||
out.push_back(static_cast<char>(0x80 | ((code >> 6U) & 0x3FU)));
|
||||
out.push_back(static_cast<char>(0x80 | (code & 0x3FU)));
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class JsonParser {
|
||||
public:
|
||||
explicit JsonParser(std::string_view text) : text_{text} {}
|
||||
std::optional<JsonValue> document() {
|
||||
auto value = parse_value(0);
|
||||
skip_space();
|
||||
if (!value || at_ != text_.size())
|
||||
return std::nullopt;
|
||||
return value;
|
||||
}
|
||||
|
||||
private:
|
||||
void skip_space() {
|
||||
while (at_ < text_.size() && (text_[at_] == ' ' || text_[at_] == '\t' ||
|
||||
text_[at_] == '\n' || text_[at_] == '\r'))
|
||||
++at_;
|
||||
}
|
||||
bool literal(std::string_view word) {
|
||||
if (text_.substr(at_, word.size()) != word)
|
||||
return false;
|
||||
at_ += word.size();
|
||||
return true;
|
||||
}
|
||||
std::optional<std::uint32_t> hex4() {
|
||||
if (at_ + 4 > text_.size())
|
||||
return std::nullopt;
|
||||
std::uint32_t value{};
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const char ch = text_[at_++];
|
||||
value <<= 4U;
|
||||
if (ch >= '0' && ch <= '9')
|
||||
value |= static_cast<std::uint32_t>(ch - '0');
|
||||
else if (ch >= 'a' && ch <= 'f')
|
||||
value |= static_cast<std::uint32_t>(ch - 'a' + 10);
|
||||
else if (ch >= 'A' && ch <= 'F')
|
||||
value |= static_cast<std::uint32_t>(ch - 'A' + 10);
|
||||
else
|
||||
return std::nullopt;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
std::optional<std::string> parse_string() {
|
||||
if (at_ >= text_.size() || text_[at_] != '"')
|
||||
return std::nullopt;
|
||||
++at_;
|
||||
std::string out;
|
||||
while (at_ < text_.size()) {
|
||||
const auto ch = static_cast<unsigned char>(text_[at_++]);
|
||||
if (ch == '"')
|
||||
return out;
|
||||
if (ch < 0x20)
|
||||
return std::nullopt;
|
||||
if (ch != '\\') {
|
||||
out.push_back(static_cast<char>(ch));
|
||||
continue;
|
||||
}
|
||||
if (at_ >= text_.size())
|
||||
return std::nullopt;
|
||||
switch (text_[at_++]) {
|
||||
case '"':
|
||||
out.push_back('"');
|
||||
break;
|
||||
case '\\':
|
||||
out.push_back('\\');
|
||||
break;
|
||||
case '/':
|
||||
out.push_back('/');
|
||||
break;
|
||||
case 'b':
|
||||
out.push_back('\b');
|
||||
break;
|
||||
case 'f':
|
||||
out.push_back('\f');
|
||||
break;
|
||||
case 'n':
|
||||
out.push_back('\n');
|
||||
break;
|
||||
case 'r':
|
||||
out.push_back('\r');
|
||||
break;
|
||||
case 't':
|
||||
out.push_back('\t');
|
||||
break;
|
||||
case 'u': {
|
||||
auto code = hex4();
|
||||
if (!code || (*code >= 0xDC00 && *code <= 0xDFFF))
|
||||
return std::nullopt;
|
||||
if (*code >= 0xD800 && *code <= 0xDBFF) {
|
||||
if (!literal("\\u"))
|
||||
return std::nullopt;
|
||||
const auto low = hex4();
|
||||
if (!low || *low < 0xDC00 || *low > 0xDFFF)
|
||||
return std::nullopt;
|
||||
code = 0x10000 + ((*code - 0xD800) << 10U) + (*low - 0xDC00);
|
||||
}
|
||||
append_utf8(out, *code);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
std::optional<JsonValue> parse_number() {
|
||||
const auto start = at_;
|
||||
if (at_ < text_.size() && text_[at_] == '-')
|
||||
++at_;
|
||||
if (at_ >= text_.size())
|
||||
return std::nullopt;
|
||||
if (text_[at_] == '0') {
|
||||
++at_;
|
||||
} else if (text_[at_] >= '1' && text_[at_] <= '9') {
|
||||
while (at_ < text_.size() && text_[at_] >= '0' && text_[at_] <= '9')
|
||||
++at_;
|
||||
} else {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (at_ < text_.size() && text_[at_] == '.') {
|
||||
++at_;
|
||||
const auto digits = at_;
|
||||
while (at_ < text_.size() && text_[at_] >= '0' && text_[at_] <= '9')
|
||||
++at_;
|
||||
if (at_ == digits)
|
||||
return std::nullopt;
|
||||
}
|
||||
if (at_ < text_.size() && (text_[at_] == 'e' || text_[at_] == 'E')) {
|
||||
++at_;
|
||||
if (at_ < text_.size() && (text_[at_] == '+' || text_[at_] == '-'))
|
||||
++at_;
|
||||
const auto digits = at_;
|
||||
while (at_ < text_.size() && text_[at_] >= '0' && text_[at_] <= '9')
|
||||
++at_;
|
||||
if (at_ == digits)
|
||||
return std::nullopt;
|
||||
}
|
||||
JsonValue value;
|
||||
value.kind_ = JsonValue::Kind::number;
|
||||
value.text_ = std::string(text_.substr(start, at_ - start));
|
||||
return value;
|
||||
}
|
||||
// `depth` counts the containers enclosing this value.
|
||||
std::optional<JsonValue> parse_value(std::size_t depth) {
|
||||
skip_space();
|
||||
if (at_ >= text_.size())
|
||||
return std::nullopt;
|
||||
if ((text_[at_] == '{' || text_[at_] == '[') && depth >= max_json_depth)
|
||||
return std::nullopt;
|
||||
JsonValue value;
|
||||
const char ch = text_[at_];
|
||||
if (ch == '{') {
|
||||
++at_;
|
||||
value.kind_ = JsonValue::Kind::object;
|
||||
skip_space();
|
||||
if (at_ < text_.size() && text_[at_] == '}') {
|
||||
++at_;
|
||||
return value;
|
||||
}
|
||||
for (;;) {
|
||||
skip_space();
|
||||
auto name = parse_string();
|
||||
skip_space();
|
||||
if (!name || at_ >= text_.size() || text_[at_] != ':')
|
||||
return std::nullopt;
|
||||
++at_;
|
||||
auto member = parse_value(depth + 1);
|
||||
if (!member)
|
||||
return std::nullopt;
|
||||
value.members_.emplace_back(std::move(*name), std::move(*member));
|
||||
skip_space();
|
||||
if (at_ >= text_.size())
|
||||
return std::nullopt;
|
||||
if (text_[at_] == ',') {
|
||||
++at_;
|
||||
continue;
|
||||
}
|
||||
if (text_[at_++] != '}')
|
||||
return std::nullopt;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
if (ch == '[') {
|
||||
++at_;
|
||||
value.kind_ = JsonValue::Kind::array;
|
||||
skip_space();
|
||||
if (at_ < text_.size() && text_[at_] == ']') {
|
||||
++at_;
|
||||
return value;
|
||||
}
|
||||
for (;;) {
|
||||
auto item = parse_value(depth + 1);
|
||||
if (!item)
|
||||
return std::nullopt;
|
||||
value.items_.push_back(std::move(*item));
|
||||
skip_space();
|
||||
if (at_ >= text_.size())
|
||||
return std::nullopt;
|
||||
if (text_[at_] == ',') {
|
||||
++at_;
|
||||
continue;
|
||||
}
|
||||
if (text_[at_++] != ']')
|
||||
return std::nullopt;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
if (ch == '"') {
|
||||
auto text = parse_string();
|
||||
if (!text)
|
||||
return std::nullopt;
|
||||
value.kind_ = JsonValue::Kind::string;
|
||||
value.text_ = std::move(*text);
|
||||
return value;
|
||||
}
|
||||
if (literal("true")) {
|
||||
value.kind_ = JsonValue::Kind::boolean;
|
||||
value.boolean_ = true;
|
||||
return value;
|
||||
}
|
||||
if (literal("false")) {
|
||||
value.kind_ = JsonValue::Kind::boolean;
|
||||
return value;
|
||||
}
|
||||
if (literal("null"))
|
||||
return value;
|
||||
return parse_number();
|
||||
}
|
||||
|
||||
std::string_view text_;
|
||||
std::size_t at_{};
|
||||
};
|
||||
|
||||
std::optional<JsonValue> JsonValue::parse(std::string_view text) {
|
||||
if (text.size() > max_json_bytes)
|
||||
return std::nullopt;
|
||||
return JsonParser{text}.document();
|
||||
}
|
||||
|
||||
std::optional<bool> JsonValue::boolean() const {
|
||||
if (kind_ != Kind::boolean)
|
||||
return std::nullopt;
|
||||
return boolean_;
|
||||
}
|
||||
|
||||
std::optional<std::string_view> JsonValue::string() const {
|
||||
if (kind_ != Kind::string)
|
||||
return std::nullopt;
|
||||
return std::string_view{text_};
|
||||
}
|
||||
|
||||
std::optional<std::uint64_t> JsonValue::integer() const {
|
||||
if (kind_ != Kind::number || text_.empty() || text_.front() == '-' ||
|
||||
text_.find_first_of(".eE") != std::string::npos)
|
||||
return std::nullopt;
|
||||
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() ||
|
||||
value > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))
|
||||
return std::nullopt;
|
||||
return value;
|
||||
}
|
||||
|
||||
const JsonValue* JsonValue::member(std::string_view name) const {
|
||||
if (kind_ != Kind::object)
|
||||
return nullptr;
|
||||
for (const auto& [key, value] : members_)
|
||||
if (key == name)
|
||||
return &value;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const std::vector<JsonValue>* JsonValue::array() const {
|
||||
return kind_ == Kind::array ? &items_ : nullptr;
|
||||
}
|
||||
} // namespace evo::server::broker
|
||||
Reference in New Issue
Block a user