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
|
||||
Reference in New Issue
Block a user