1094 lines
39 KiB
C++
1094 lines
39 KiB
C++
#include <Void/Update/Feed.hpp>
|
|
|
|
#include <Void/Data/Json.hpp>
|
|
#include <Void/Data/StrictJson.hpp>
|
|
#include <Void/Text/Base64.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <cmath>
|
|
#include <concepts>
|
|
#include <format>
|
|
#include <limits>
|
|
#include <set>
|
|
#include <tuple>
|
|
|
|
namespace Void::Update
|
|
{
|
|
namespace
|
|
{
|
|
using JsonResult = Void::Result::Result<const Json::Value*>;
|
|
|
|
[[nodiscard]] JsonResult member(const Json::Value& object,
|
|
std::string_view name,
|
|
bool (*predicate)(const Json::Value&),
|
|
std::string_view expected)
|
|
{
|
|
const auto* value = object.find(name);
|
|
if (value == nullptr || !predicate(*value)) {
|
|
return Void::Result::fail(std::format(
|
|
"Update feed: '{}' must be {}", name, expected));
|
|
}
|
|
return value;
|
|
}
|
|
|
|
[[nodiscard]] bool is_array(const Json::Value& value) noexcept
|
|
{
|
|
return value.is_array();
|
|
}
|
|
[[nodiscard]] bool is_object(const Json::Value& value) noexcept
|
|
{
|
|
return value.is_object();
|
|
}
|
|
[[nodiscard]] bool is_string(const Json::Value& value) noexcept
|
|
{
|
|
return value.is_string();
|
|
}
|
|
[[nodiscard]] bool is_number(const Json::Value& value) noexcept
|
|
{
|
|
return value.is_number();
|
|
}
|
|
|
|
template <std::unsigned_integral T>
|
|
[[nodiscard]] Void::Result::Result<T>
|
|
unsigned_number(const Json::Value& object, std::string_view name)
|
|
{
|
|
auto value = member(object, name, is_number, "an unsigned integer");
|
|
if (!value) {
|
|
return std::unexpected{value.error()};
|
|
}
|
|
const double number = (*value)->as_number();
|
|
constexpr double maxSafeInteger = 9'007'199'254'740'991.0;
|
|
if (!std::isfinite(number) || number < 0 ||
|
|
std::floor(number) != number || number > maxSafeInteger ||
|
|
number > static_cast<double>(std::numeric_limits<T>::max())) {
|
|
return Void::Result::fail(std::format(
|
|
"Update feed: '{}' is outside its integer range", name));
|
|
}
|
|
return static_cast<T>(number);
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<std::string>
|
|
string_member(const Json::Value& object, std::string_view name)
|
|
{
|
|
auto value = member(object, name, is_string, "a string");
|
|
if (!value) {
|
|
return std::unexpected{value.error()};
|
|
}
|
|
return (*value)->as_string();
|
|
}
|
|
|
|
[[nodiscard]] bool valid_token(std::string_view value,
|
|
std::size_t maximum = 128) noexcept
|
|
{
|
|
if (value.empty() || value.size() > maximum) {
|
|
return false;
|
|
}
|
|
for (const char character : value) {
|
|
if (!((character >= 'a' && character <= 'z') ||
|
|
(character >= 'A' && character <= 'Z') ||
|
|
(character >= '0' && character <= '9') ||
|
|
character == '.' || character == '_' ||
|
|
character == '-')) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
[[nodiscard]] bool valid_sha256(std::string_view value) noexcept
|
|
{
|
|
if (value.size() != 64) {
|
|
return false;
|
|
}
|
|
return std::ranges::all_of(value, [](const char character) {
|
|
return (character >= '0' && character <= '9') ||
|
|
(character >= 'a' && character <= 'f');
|
|
});
|
|
}
|
|
|
|
[[nodiscard]] bool
|
|
valid_prefixed_hash(std::string_view value, std::string_view prefix,
|
|
std::size_t hexadecimalSize) noexcept
|
|
{
|
|
if (!value.starts_with(prefix)) {
|
|
return false;
|
|
}
|
|
const auto hexadecimal = value.substr(prefix.size());
|
|
return hexadecimal.size() == hexadecimalSize &&
|
|
std::ranges::all_of(hexadecimal, [](const char character) {
|
|
return (character >= '0' && character <= '9') ||
|
|
(character >= 'a' && character <= 'f');
|
|
});
|
|
}
|
|
|
|
[[nodiscard]] bool valid_hex(std::string_view value,
|
|
std::size_t size) noexcept
|
|
{
|
|
return value.size() == size &&
|
|
std::ranges::all_of(value, [](const char character) {
|
|
return (character >= 48 && character <= 57) ||
|
|
(character >= 97 && character <= 102);
|
|
});
|
|
}
|
|
|
|
[[nodiscard]] bool valid_package_type(std::string_view value) noexcept
|
|
{
|
|
return !value.empty() && value.size() <= 128 &&
|
|
std::ranges::all_of(value, [](const char character) {
|
|
return (character >= 'a' && character <= 'z') ||
|
|
(character >= '0' && character <= '9') ||
|
|
character == '.' || character == '-' ||
|
|
character == '_';
|
|
});
|
|
}
|
|
|
|
[[nodiscard]] std::optional<int>
|
|
decimal(std::string_view value) noexcept
|
|
{
|
|
int result = 0;
|
|
for (const char character : value) {
|
|
if (character < '0' || character > '9') {
|
|
return std::nullopt;
|
|
}
|
|
result = result * 10 + (character - '0');
|
|
}
|
|
return result;
|
|
}
|
|
|
|
[[nodiscard]] std::optional<std::chrono::system_clock::time_point>
|
|
parse_timestamp(std::string_view value) noexcept
|
|
{
|
|
if (value.size() < 20 || value[4] != '-' || value[7] != '-' ||
|
|
value[10] != 'T' || value[13] != ':' || value[16] != ':' ||
|
|
value.back() != 'Z') {
|
|
return std::nullopt;
|
|
}
|
|
const auto year = decimal(value.substr(0, 4));
|
|
const auto month = decimal(value.substr(5, 2));
|
|
const auto day = decimal(value.substr(8, 2));
|
|
const auto hour = decimal(value.substr(11, 2));
|
|
const auto minute = decimal(value.substr(14, 2));
|
|
const auto second = decimal(value.substr(17, 2));
|
|
if (!year || !month || !day || !hour || !minute || !second ||
|
|
*hour > 23 || *minute > 59 || *second > 59) {
|
|
return std::nullopt;
|
|
}
|
|
if (value.size() > 20) {
|
|
if (value.size() == 21 || value[19] != '.') {
|
|
return std::nullopt;
|
|
}
|
|
for (std::size_t index = 20; index + 1 < value.size();
|
|
++index) {
|
|
if (value[index] < '0' || value[index] > '9') {
|
|
return std::nullopt;
|
|
}
|
|
}
|
|
}
|
|
const std::chrono::year_month_day date{
|
|
std::chrono::year{*year},
|
|
std::chrono::month{static_cast<unsigned>(*month)},
|
|
std::chrono::day{static_cast<unsigned>(*day)}};
|
|
if (!date.ok()) {
|
|
return std::nullopt;
|
|
}
|
|
return std::chrono::sys_days{date} + std::chrono::hours{*hour} +
|
|
std::chrono::minutes{*minute} +
|
|
std::chrono::seconds{*second};
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<Compatibility>
|
|
parse_compatibility(const Json::Value& value)
|
|
{
|
|
if (!value.is_object()) {
|
|
return Void::Result::fail(
|
|
"Update feed: compatibility must be an object");
|
|
}
|
|
Compatibility result;
|
|
if (const auto* contracts = value.find("versionContracts")) {
|
|
if (!contracts->is_object()) {
|
|
return Void::Result::fail(
|
|
"Update feed: compatibility.versionContracts must be "
|
|
"an object");
|
|
}
|
|
for (const auto& [name, rangeValue] : contracts->as_object()) {
|
|
if (!valid_token(name, 256) || !rangeValue.is_string()) {
|
|
return Void::Result::fail(
|
|
"Update feed: invalid version contract");
|
|
}
|
|
auto range = Semver::parse_range(rangeValue.as_string());
|
|
if (!range) {
|
|
return Void::Result::fail(
|
|
std::format("Update feed: version contract '{}' "
|
|
"has an invalid range",
|
|
name));
|
|
}
|
|
result.versionContracts.emplace(name, std::move(*range));
|
|
}
|
|
}
|
|
if (const auto* contracts = value.find("exactContracts")) {
|
|
if (!contracts->is_object()) {
|
|
return Void::Result::fail(
|
|
"Update feed: compatibility.exactContracts must be an "
|
|
"object");
|
|
}
|
|
for (const auto& [name, contractValue] :
|
|
contracts->as_object()) {
|
|
if (!valid_token(name, 256) || !contractValue.is_string() ||
|
|
contractValue.as_string().empty() ||
|
|
contractValue.as_string().size() > 512) {
|
|
return Void::Result::fail(
|
|
"Update feed: invalid exact contract");
|
|
}
|
|
result.exactContracts.emplace(name,
|
|
contractValue.as_string());
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<Release>
|
|
parse_release(const Json::Value& value)
|
|
{
|
|
if (!value.is_object()) {
|
|
return Void::Result::fail(
|
|
"Update feed: release must be an object");
|
|
}
|
|
Release release;
|
|
auto component = string_member(value, "component");
|
|
if (!component || !valid_token(*component, 256)) {
|
|
return Void::Result::fail("Update feed: component is invalid");
|
|
}
|
|
release.component = std::move(*component);
|
|
release.artifactId = value.get_str("artifactId");
|
|
if (!release.artifactId.empty() &&
|
|
!valid_token(release.artifactId, 256)) {
|
|
return Void::Result::fail("Update feed: artifactId is invalid");
|
|
}
|
|
|
|
auto channel = string_member(value, "channel");
|
|
auto versionText = string_member(value, "version");
|
|
auto platform = string_member(value, "platform");
|
|
auto architecture = string_member(value, "arch");
|
|
auto url = string_member(value, "url");
|
|
auto size = unsigned_number<std::uint64_t>(value, "size");
|
|
auto sha256 = string_member(value, "sha256");
|
|
auto packageType = string_member(value, "packageType");
|
|
if (!channel || !versionText || !platform || !architecture ||
|
|
!url || !size || !sha256 || !packageType) {
|
|
return Void::Result::fail(
|
|
"Update feed: release has invalid required fields");
|
|
}
|
|
const auto cohort = value.get_str("cohort");
|
|
const auto manifestHash = value.get_str("releaseManifestSha256");
|
|
const bool urlIsBounded =
|
|
!url->empty() && url->size() <= 8192 &&
|
|
std::ranges::none_of(*url, [](const unsigned char character) {
|
|
return character < 0x20 || character == 0x7f;
|
|
});
|
|
if (!valid_token(*channel) ||
|
|
(!cohort.empty() && !valid_token(cohort, 256)) ||
|
|
!valid_token(*platform) || !valid_token(*architecture) ||
|
|
!urlIsBounded || *size == 0 || !valid_sha256(*sha256) ||
|
|
!valid_package_type(*packageType) ||
|
|
(!manifestHash.empty() && !valid_sha256(manifestHash))) {
|
|
return Void::Result::fail("Update feed: release contains an "
|
|
"unsafe or unsupported field");
|
|
}
|
|
auto version = Semver::parse_strict(*versionText);
|
|
if (!version) {
|
|
return Void::Result::fail(
|
|
"Update feed: release version is invalid SemVer");
|
|
}
|
|
release.channel = std::move(*channel);
|
|
release.version = std::move(*version);
|
|
release.cohort = cohort;
|
|
release.platform = std::move(*platform);
|
|
release.architecture = std::move(*architecture);
|
|
release.url = std::move(*url);
|
|
release.size = *size;
|
|
release.sha256 = std::move(*sha256);
|
|
release.packageType = std::move(*packageType);
|
|
release.releaseManifestSha256 = manifestHash;
|
|
const auto* compatibility = value.find("compatibility");
|
|
if (compatibility) {
|
|
auto parsedCompatibility = parse_compatibility(*compatibility);
|
|
if (!parsedCompatibility) {
|
|
return std::unexpected{parsedCompatibility.error()};
|
|
}
|
|
release.compatibility = std::move(*parsedCompatibility);
|
|
}
|
|
return release;
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<Feed>
|
|
parse_feed(std::string_view payload,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
auto document = Json::parse(payload);
|
|
if (!document || !document->is_object()) {
|
|
return Void::Result::fail(
|
|
"Update feed: signed payload is not a JSON object");
|
|
}
|
|
auto schema =
|
|
unsigned_number<std::uint32_t>(*document, "schemaVersion");
|
|
auto feedId = string_member(*document, "feedId");
|
|
auto sequence =
|
|
unsigned_number<std::uint64_t>(*document, "sequence");
|
|
auto generated = string_member(*document, "generatedAt");
|
|
auto expires = string_member(*document, "expiresAt");
|
|
auto releasesValue =
|
|
member(*document, "releases", is_array, "an array");
|
|
if (!schema || !feedId || !sequence || !generated || !expires ||
|
|
!releasesValue) {
|
|
return Void::Result::fail(
|
|
"Update feed: invalid top-level fields");
|
|
}
|
|
if (*schema != 1 || !valid_token(*feedId, 256)) {
|
|
return Void::Result::fail(
|
|
"Update feed: unsupported schema or invalid feedId");
|
|
}
|
|
if (policy.minimumSequence &&
|
|
*sequence <= *policy.minimumSequence) {
|
|
return Void::Result::fail(
|
|
"Update feed: sequence is not newer than the replay floor");
|
|
}
|
|
const auto generatedAt = parse_timestamp(*generated);
|
|
const auto expiresAt = parse_timestamp(*expires);
|
|
if (!generatedAt || !expiresAt || *expiresAt <= *generatedAt) {
|
|
return Void::Result::fail(
|
|
"Update feed: timestamps are invalid");
|
|
}
|
|
if (policy.requireUnexpired && policy.now >= *expiresAt) {
|
|
return Void::Result::fail("Update feed: feed has expired");
|
|
}
|
|
const auto& values = (*releasesValue)->as_array();
|
|
if (values.size() > policy.maxReleases) {
|
|
return Void::Result::fail(
|
|
"Update feed: release count exceeds policy");
|
|
}
|
|
Feed feed{.schemaVersion = *schema,
|
|
.feedId = std::move(*feedId),
|
|
.sequence = *sequence,
|
|
.generatedAt = *generatedAt,
|
|
.expiresAt = *expiresAt};
|
|
std::set<std::tuple<std::string, std::string, std::string,
|
|
std::string, std::string, std::string>>
|
|
identities;
|
|
feed.releases.reserve(values.size());
|
|
for (const auto& value : values) {
|
|
auto release = parse_release(value);
|
|
if (!release) {
|
|
return std::unexpected{release.error()};
|
|
}
|
|
auto identity =
|
|
std::tuple{release->component, release->artifactId,
|
|
release->channel, release->version.to_string(),
|
|
release->platform, release->architecture};
|
|
if (!identities.insert(std::move(identity)).second) {
|
|
return Void::Result::fail(
|
|
"Update feed: ambiguous duplicate release identity");
|
|
}
|
|
feed.releases.push_back(std::move(*release));
|
|
}
|
|
return feed;
|
|
}
|
|
|
|
struct ComponentDocumentHeader {
|
|
std::string channel;
|
|
std::uint64_t sequence{0};
|
|
std::chrono::system_clock::time_point generatedAt;
|
|
std::chrono::system_clock::time_point expiresAt;
|
|
Semver::Version productVersion;
|
|
};
|
|
|
|
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
|
|
optional_token(const Json::Value& object, std::string_view name)
|
|
{
|
|
const auto* value = object.find(name);
|
|
if (value == nullptr || value->is_null()) {
|
|
return std::optional<std::string>{};
|
|
}
|
|
if (!value->is_string() || !valid_token(value->as_string(), 256)) {
|
|
return Void::Result::fail(std::format(
|
|
"Component feed: {} must be null or a safe token", name));
|
|
}
|
|
return std::optional<std::string>{value->as_string()};
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
|
|
optional_string(const Json::Value& object, std::string_view name)
|
|
{
|
|
const auto* value = object.find(name);
|
|
if (value == nullptr || value->is_null()) {
|
|
return std::optional<std::string>{};
|
|
}
|
|
if (!value->is_string()) {
|
|
return Void::Result::fail(std::format(
|
|
"Component feed: {} must be null or a string", name));
|
|
}
|
|
return std::optional<std::string>{value->as_string()};
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<
|
|
std::map<std::string, Semver::VersionRange>>
|
|
parse_dependencies(const Json::Value& object)
|
|
{
|
|
const auto* dependencies = object.find("dependencies");
|
|
if (dependencies == nullptr || !dependencies->is_object()) {
|
|
return Void::Result::fail(
|
|
"Component feed: dependencies must be an object");
|
|
}
|
|
std::map<std::string, Semver::VersionRange> result;
|
|
for (const auto& [component, value] : dependencies->as_object()) {
|
|
if (!valid_token(component, 256) || !value.is_string()) {
|
|
return Void::Result::fail(
|
|
"Component feed: dependency contains an unsafe field");
|
|
}
|
|
auto range = Semver::parse_range(value.as_string());
|
|
if (!range) {
|
|
return Void::Result::fail(std::format(
|
|
"Component feed: dependency {} has an invalid range",
|
|
component));
|
|
}
|
|
result.emplace(component, std::move(*range));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<std::map<std::string, std::string>>
|
|
parse_dependency_constraints(const Json::Value& object)
|
|
{
|
|
const auto* dependencies = object.find("dependencies");
|
|
if (dependencies == nullptr || !dependencies->is_object()) {
|
|
return Void::Result::fail(
|
|
"Component feed: dependencies must be an object");
|
|
}
|
|
std::map<std::string, std::string> result;
|
|
for (const auto& [component, value] : dependencies->as_object()) {
|
|
if (!valid_token(component, 256) || !value.is_string() ||
|
|
value.as_string().empty() ||
|
|
value.as_string().size() > 512) {
|
|
return Void::Result::fail(
|
|
"Component feed: dependency contains an unsafe field");
|
|
}
|
|
result.emplace(component, value.as_string());
|
|
}
|
|
return result;
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<ComponentDocumentHeader>
|
|
parse_component_header(const Json::Value& document,
|
|
std::string_view expectedDocument,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
auto schema =
|
|
unsigned_number<std::uint32_t>(document, "schemaVersion");
|
|
auto type = string_member(document, "document");
|
|
auto channel = string_member(document, "channel");
|
|
auto sequence =
|
|
unsigned_number<std::uint64_t>(document, "sequence");
|
|
auto generated = string_member(document, "generatedAt");
|
|
auto expires = string_member(document, "expiresAt");
|
|
auto productVersion = string_member(document, "productVersion");
|
|
if (!schema || !type || !channel || !sequence || !generated ||
|
|
!expires || !productVersion || *schema != 2 ||
|
|
*type != expectedDocument || !valid_token(*channel, 64)) {
|
|
return Void::Result::fail(
|
|
"Component feed: invalid discovery document header");
|
|
}
|
|
if (policy.minimumSequence &&
|
|
*sequence <= *policy.minimumSequence) {
|
|
return Void::Result::fail("Component feed: sequence is not "
|
|
"newer than the replay floor");
|
|
}
|
|
const auto generatedAt = parse_timestamp(*generated);
|
|
const auto expiresAt = parse_timestamp(*expires);
|
|
auto version = Semver::parse_strict(*productVersion);
|
|
if (!generatedAt || !expiresAt || *expiresAt <= *generatedAt ||
|
|
!version) {
|
|
return Void::Result::fail(
|
|
"Component feed: timestamp or product version is invalid");
|
|
}
|
|
if (policy.requireUnexpired && policy.now >= *expiresAt) {
|
|
return Void::Result::fail(
|
|
"Component feed: discovery document has expired");
|
|
}
|
|
return ComponentDocumentHeader{.channel = std::move(*channel),
|
|
.sequence = *sequence,
|
|
.generatedAt = *generatedAt,
|
|
.expiresAt = *expiresAt,
|
|
.productVersion =
|
|
std::move(*version)};
|
|
}
|
|
|
|
[[nodiscard]] bool bounded_url(std::string_view value) noexcept
|
|
{
|
|
return value.starts_with("https://") && value.size() <= 8192 &&
|
|
std::ranges::none_of(
|
|
value, [](const unsigned char character) {
|
|
return character < 0x20 || character == 0x7f;
|
|
});
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<ComponentCatalogEntry>
|
|
parse_catalog_entry(const Json::Value& value)
|
|
{
|
|
if (!value.is_object()) {
|
|
return Void::Result::fail(
|
|
"Component feed: catalog entry must be an object");
|
|
}
|
|
auto componentId = string_member(value, "componentId");
|
|
auto pluginId = optional_token(value, "pluginId");
|
|
auto kind = string_member(value, "kind");
|
|
auto versionText = string_member(value, "componentVersion");
|
|
auto activation = string_member(value, "activation");
|
|
auto sequence = unsigned_number<std::uint64_t>(value, "sequence");
|
|
auto latestUrl = string_member(value, "latestUrl");
|
|
auto artifactSha = string_member(value, "artifactSha256");
|
|
auto dependencyConstraints = parse_dependency_constraints(value);
|
|
auto dependencies = parse_dependencies(value);
|
|
if (!componentId || !pluginId || !kind || !versionText ||
|
|
!activation || !sequence || !latestUrl || !artifactSha ||
|
|
!dependencyConstraints || !dependencies ||
|
|
!valid_token(*componentId, 256) || !valid_token(*kind, 128) ||
|
|
!valid_token(*activation, 128) || !bounded_url(*latestUrl) ||
|
|
!valid_sha256(*artifactSha)) {
|
|
return Void::Result::fail(
|
|
"Component feed: catalog entry contains an unsafe field");
|
|
}
|
|
auto version = Semver::parse_strict(*versionText);
|
|
if (!version) {
|
|
return Void::Result::fail(
|
|
"Component feed: component version is invalid SemVer");
|
|
}
|
|
return ComponentCatalogEntry{
|
|
.componentId = std::move(*componentId),
|
|
.pluginId = std::move(*pluginId),
|
|
.kind = std::move(*kind),
|
|
.componentVersion = std::move(*version),
|
|
.activation = std::move(*activation),
|
|
.dependencyConstraints = std::move(*dependencyConstraints),
|
|
.dependencies = std::move(*dependencies),
|
|
.sequence = *sequence,
|
|
.latestUrl = std::move(*latestUrl),
|
|
.artifactSha256 = std::move(*artifactSha)};
|
|
}
|
|
|
|
[[nodiscard]] bool compatible(const Compatibility& compatibility,
|
|
const Environment& environment) noexcept
|
|
{
|
|
for (const auto& [name, range] : compatibility.versionContracts) {
|
|
const auto installed = environment.versionContracts.find(name);
|
|
if (installed == environment.versionContracts.end() ||
|
|
!range.contains(installed->second)) {
|
|
return false;
|
|
}
|
|
}
|
|
for (const auto& [name, value] : compatibility.exactContracts) {
|
|
const auto installed = environment.exactContracts.find(name);
|
|
if (installed == environment.exactContracts.end() ||
|
|
installed->second != value) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
[[nodiscard]] Void::Result::Result<void>
|
|
enforce_parse_policy(std::string_view payload,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
if (policy.parsePolicy == SchemaParsePolicy::StrictJsonProfile) {
|
|
auto strict = Json::Strict::parse(
|
|
payload, Json::Strict::ParseOptions{
|
|
.maximumDepth = policy.maxJsonDepth,
|
|
.allowDecimals = false,
|
|
});
|
|
if (!strict.has_value()) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::schema_error,
|
|
std::format("Update feed: StrictJsonProfile rejected "
|
|
"payload: {}",
|
|
strict.error().message))};
|
|
}
|
|
}
|
|
return {};
|
|
}
|
|
} // namespace
|
|
|
|
Void::Result::Result<Feed>
|
|
parseFeedPayload(std::string_view payload,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
if (payload.size() > policy.maxPayloadBytes) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::limit_exceeded,
|
|
"Update feed: payload exceeds policy size")};
|
|
}
|
|
if (auto strict = enforce_parse_policy(payload, policy);
|
|
!strict.has_value()) {
|
|
return std::unexpected{std::move(strict.error())};
|
|
}
|
|
return parse_feed(payload, policy);
|
|
}
|
|
|
|
Void::Result::Result<VerifiedFeed>
|
|
verifyFeedEnvelope(std::string_view envelopeJson, const Keyring& keys,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
auto envelope = verifyEnvelope(envelopeJson, keys, policy);
|
|
if (!envelope) {
|
|
return std::unexpected{envelope.error()};
|
|
}
|
|
if (envelope->schemaVersion != 1) {
|
|
return Void::Result::fail(
|
|
"Update feed: aggregate feed requires envelope schema 1");
|
|
}
|
|
auto feed = parseFeedPayload(envelope->signedPayload, policy);
|
|
if (!feed) {
|
|
return std::unexpected{feed.error()};
|
|
}
|
|
return VerifiedFeed{.feed = std::move(*feed),
|
|
.keyId = std::move(envelope->keyId),
|
|
.signedPayload =
|
|
std::move(envelope->signedPayload)};
|
|
}
|
|
|
|
Void::Result::Result<VerifiedEnvelope>
|
|
verifyEnvelope(std::string_view envelopeJson, const Keyring& keys,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
if (envelopeJson.size() > policy.maxEnvelopeBytes) {
|
|
return Void::Result::fail(
|
|
"Update feed: envelope exceeds policy size");
|
|
}
|
|
auto envelope = Json::parse(envelopeJson);
|
|
if (!envelope || !envelope->is_object()) {
|
|
return Void::Result::fail(
|
|
"Update feed: envelope is not a JSON object");
|
|
}
|
|
auto schema =
|
|
unsigned_number<std::uint32_t>(*envelope, "schemaVersion");
|
|
auto keyId = string_member(*envelope, "keyId");
|
|
auto signatureText = string_member(*envelope, "signature");
|
|
if (!schema || !keyId || !signatureText ||
|
|
(*schema != 1 && *schema != 2 && *schema != 3) ||
|
|
!valid_token(*keyId, 256)) {
|
|
return Void::Result::fail("Update feed: invalid envelope fields");
|
|
}
|
|
auto payloadText = string_member(
|
|
*envelope, *schema == 3 ? "signedPayload" : "payload");
|
|
const Json::Value* displayedDocument = nullptr;
|
|
if (*schema == 3) {
|
|
auto document =
|
|
member(*envelope, "document", is_object, "an object");
|
|
if (!document) {
|
|
return std::unexpected{document.error()};
|
|
}
|
|
displayedDocument = *document;
|
|
}
|
|
if (!payloadText) {
|
|
return Void::Result::fail("Update feed: invalid envelope fields");
|
|
}
|
|
const auto key = keys.find(*keyId);
|
|
if (key == keys.end()) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::untrusted_key,
|
|
"Update feed: envelope key is not trusted")};
|
|
}
|
|
auto payload = Encoding::Base64::decode_url(*payloadText);
|
|
auto signature = Encoding::Base64::decode_url(*signatureText);
|
|
if (!payload || !signature ||
|
|
payload->size() > policy.maxPayloadBytes) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::schema_error,
|
|
"Update feed: invalid or oversized envelope encoding")};
|
|
}
|
|
|
|
// Verify exact signed payload bytes BEFORE any payload JSON parsing or
|
|
// schema-3 readable-document mirror comparison.
|
|
const auto signatureBytes =
|
|
std::as_bytes(std::span{signature->data(), signature->size()});
|
|
const auto payloadBytes =
|
|
std::as_bytes(std::span{payload->data(), payload->size()});
|
|
auto valid =
|
|
Crypto::verifyEd25519(payloadBytes, signatureBytes, key->second);
|
|
if (!valid) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::signature_failed, valid.error().message())};
|
|
}
|
|
if (!*valid) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::signature_failed,
|
|
"Update feed: signature verification failed")};
|
|
}
|
|
|
|
if (auto strict = enforce_parse_policy(*payload, policy);
|
|
!strict.has_value()) {
|
|
return std::unexpected{std::move(strict.error())};
|
|
}
|
|
|
|
if (*schema == 3) {
|
|
auto signedDocument = Json::parse(*payload);
|
|
if (!signedDocument || !signedDocument->is_object() ||
|
|
displayedDocument == nullptr ||
|
|
*displayedDocument != *signedDocument) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::mirror_mismatch,
|
|
"Update feed: readable document differs from signed "
|
|
"payload")};
|
|
}
|
|
}
|
|
return VerifiedEnvelope{.schemaVersion = *schema,
|
|
.keyId = std::move(*keyId),
|
|
.signedPayload = std::move(*payload)};
|
|
}
|
|
|
|
Void::Result::Result<ComponentCatalog>
|
|
parseComponentCatalogPayload(std::string_view payload,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
if (payload.size() > policy.maxPayloadBytes) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::limit_exceeded,
|
|
"Component feed: payload exceeds policy size")};
|
|
}
|
|
if (auto strict = enforce_parse_policy(payload, policy);
|
|
!strict.has_value()) {
|
|
return std::unexpected{std::move(strict.error())};
|
|
}
|
|
auto document = Json::parse(payload);
|
|
if (!document || !document->is_object()) {
|
|
return Void::Result::fail(
|
|
"Component feed: catalog payload is not an object");
|
|
}
|
|
auto header = parse_component_header(
|
|
*document, "echoion-component-catalog", policy);
|
|
auto components = member(*document, "components", is_array, "an array");
|
|
if (!header || !components) {
|
|
return Void::Result::fail("Component feed: invalid catalog fields");
|
|
}
|
|
const auto& values = (*components)->as_array();
|
|
if (values.empty() || values.size() > policy.maxReleases) {
|
|
return Void::Result::fail(
|
|
"Component feed: catalog component count exceeds policy");
|
|
}
|
|
ComponentCatalog result{.channel = std::move(header->channel),
|
|
.sequence = header->sequence,
|
|
.generatedAt = header->generatedAt,
|
|
.expiresAt = header->expiresAt,
|
|
.productVersion =
|
|
std::move(header->productVersion)};
|
|
std::set<std::string> identities;
|
|
result.components.reserve(values.size());
|
|
for (const auto& value : values) {
|
|
auto entry = parse_catalog_entry(value);
|
|
if (!entry) {
|
|
return std::unexpected{entry.error()};
|
|
}
|
|
if (entry->sequence != result.sequence ||
|
|
!identities.insert(entry->componentId).second) {
|
|
return Void::Result::fail("Component feed: catalog has a "
|
|
"sequence mismatch or duplicate");
|
|
}
|
|
result.components.push_back(std::move(*entry));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Void::Result::Result<ComponentRelease>
|
|
parseComponentReleasePayload(std::string_view payload,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
if (payload.size() > policy.maxPayloadBytes) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::limit_exceeded,
|
|
"Component feed: payload exceeds policy size")};
|
|
}
|
|
if (auto strict = enforce_parse_policy(payload, policy);
|
|
!strict.has_value()) {
|
|
return std::unexpected{std::move(strict.error())};
|
|
}
|
|
auto document = Json::parse(payload);
|
|
if (!document || !document->is_object()) {
|
|
return Void::Result::fail(
|
|
"Component feed: release payload is not an object");
|
|
}
|
|
auto header = parse_component_header(
|
|
*document, "echoion-component-release", policy);
|
|
auto componentId = string_member(*document, "componentId");
|
|
auto pluginId = optional_token(*document, "pluginId");
|
|
auto kind = string_member(*document, "kind");
|
|
auto componentVersion = string_member(*document, "componentVersion");
|
|
auto sourceSha = string_member(*document, "sourceSha");
|
|
auto sourceTreeHash = string_member(*document, "sourceTreeHash");
|
|
auto abiHash = optional_string(*document, "abiHash");
|
|
auto artifactIdentity = string_member(*document, "artifactIdentity");
|
|
auto activation = string_member(*document, "activation");
|
|
auto platform = string_member(*document, "platform");
|
|
auto architecture = string_member(*document, "architecture");
|
|
auto toolchainContract = string_member(*document, "toolchainContract");
|
|
auto dependencyConstraints = parse_dependency_constraints(*document);
|
|
auto dependencies = parse_dependencies(*document);
|
|
const auto* artifactValue = document->find("artifact");
|
|
if (!header || !componentId || !pluginId || !kind ||
|
|
!componentVersion || !sourceSha || !sourceTreeHash || !abiHash ||
|
|
!artifactIdentity || !activation || !platform || !architecture ||
|
|
!toolchainContract || !dependencyConstraints || !dependencies ||
|
|
artifactValue == nullptr || !artifactValue->is_object() ||
|
|
!valid_token(*componentId, 256) || !valid_token(*kind, 128) ||
|
|
!valid_token(*artifactIdentity, 256) ||
|
|
!valid_token(*activation, 128) || !valid_token(*platform, 64) ||
|
|
!valid_token(*architecture, 64) ||
|
|
!valid_token(*toolchainContract, 256) ||
|
|
!valid_hex(*sourceSha, 40) ||
|
|
!valid_prefixed_hash(*sourceTreeHash, "git-sha1:", 40) ||
|
|
(*abiHash && !valid_prefixed_hash(**abiHash, "sha256:", 64))) {
|
|
return Void::Result::fail(
|
|
"Component feed: release contains an unsafe field");
|
|
}
|
|
auto version = Semver::parse_strict(*componentVersion);
|
|
auto artifactName = string_member(*artifactValue, "name");
|
|
auto artifactUrl = string_member(*artifactValue, "url");
|
|
auto artifactSha = string_member(*artifactValue, "sha256");
|
|
auto artifactSize =
|
|
unsigned_number<std::uint64_t>(*artifactValue, "size");
|
|
auto manifestSha = string_member(*artifactValue, "manifestSha256");
|
|
auto packageType = string_member(*artifactValue, "packageType");
|
|
if (!version || !artifactName || !artifactUrl || !artifactSha ||
|
|
!artifactSize || !manifestSha || !packageType ||
|
|
!valid_token(*artifactName, 256) || !bounded_url(*artifactUrl) ||
|
|
!valid_sha256(*artifactSha) || *artifactSize == 0 ||
|
|
!valid_sha256(*manifestSha) || !valid_package_type(*packageType)) {
|
|
return Void::Result::fail(
|
|
"Component feed: release artifact contains an unsafe field");
|
|
}
|
|
return ComponentRelease{
|
|
.channel = std::move(header->channel),
|
|
.sequence = header->sequence,
|
|
.generatedAt = header->generatedAt,
|
|
.expiresAt = header->expiresAt,
|
|
.productVersion = std::move(header->productVersion),
|
|
.componentId = std::move(*componentId),
|
|
.pluginId = std::move(*pluginId),
|
|
.kind = std::move(*kind),
|
|
.componentVersion = std::move(*version),
|
|
.sourceSha = std::move(*sourceSha),
|
|
.sourceTreeHash = std::move(*sourceTreeHash),
|
|
.abiHash = std::move(*abiHash),
|
|
.artifactIdentity = std::move(*artifactIdentity),
|
|
.activation = std::move(*activation),
|
|
.platform = std::move(*platform),
|
|
.architecture = std::move(*architecture),
|
|
.toolchainContract = std::move(*toolchainContract),
|
|
.dependencyConstraints = std::move(*dependencyConstraints),
|
|
.dependencies = std::move(*dependencies),
|
|
.artifact = {.name = std::move(*artifactName),
|
|
.url = std::move(*artifactUrl),
|
|
.sha256 = std::move(*artifactSha),
|
|
.size = *artifactSize,
|
|
.manifestSha256 = std::move(*manifestSha),
|
|
.packageType = std::move(*packageType)}};
|
|
}
|
|
|
|
Void::Result::Result<void> validateComponentSet(
|
|
const ComponentCatalog& catalog,
|
|
const std::map<std::string, ComponentRelease>& releases)
|
|
{
|
|
if (catalog.components.size() != releases.size()) {
|
|
return Void::Result::fail(
|
|
"Component set: release count does not match the catalog");
|
|
}
|
|
for (const auto& entry : catalog.components) {
|
|
const auto release = releases.find(entry.componentId);
|
|
if (release == releases.end()) {
|
|
return Void::Result::fail(std::format(
|
|
"Component set: release {} is missing", entry.componentId));
|
|
}
|
|
const auto& value = release->second;
|
|
if (value.componentId != entry.componentId ||
|
|
value.componentVersion != entry.componentVersion ||
|
|
value.productVersion != catalog.productVersion ||
|
|
value.channel != catalog.channel ||
|
|
value.sequence != catalog.sequence ||
|
|
value.artifact.sha256 != entry.artifactSha256 ||
|
|
value.activation != entry.activation ||
|
|
value.pluginId != entry.pluginId || value.kind != entry.kind ||
|
|
value.dependencyConstraints != entry.dependencyConstraints ||
|
|
value.dependencies.size() != entry.dependencies.size()) {
|
|
return Void::Result::fail(std::format(
|
|
"Component set: release {} does not match the catalog",
|
|
entry.componentId));
|
|
}
|
|
for (const auto& [dependencyId, range] : value.dependencies) {
|
|
const auto dependency = releases.find(dependencyId);
|
|
const auto catalogRange = entry.dependencies.find(dependencyId);
|
|
if (dependency == releases.end() ||
|
|
catalogRange == entry.dependencies.end() ||
|
|
!range.contains(dependency->second.componentVersion) ||
|
|
!catalogRange->second.contains(
|
|
dependency->second.componentVersion)) {
|
|
return Void::Result::fail(std::format(
|
|
"Component set: dependency {} of {} is incompatible",
|
|
dependencyId, entry.componentId));
|
|
}
|
|
}
|
|
}
|
|
return {};
|
|
}
|
|
|
|
std::optional<Release> selectRelease(const Feed& feed,
|
|
const SelectionRequest& request)
|
|
{
|
|
const Release* selected = nullptr;
|
|
for (const auto& release : feed.releases) {
|
|
if (release.component != request.component ||
|
|
release.artifactId != request.artifactId ||
|
|
release.channel != request.channel ||
|
|
release.platform != request.environment.platform ||
|
|
release.architecture != request.environment.architecture ||
|
|
(request.requiredCohort &&
|
|
release.cohort != *request.requiredCohort) ||
|
|
!compatible(release.compatibility, request.environment)) {
|
|
continue;
|
|
}
|
|
if (request.currentVersion) {
|
|
const auto comparison =
|
|
release.version <=> *request.currentVersion;
|
|
if (comparison == 0 && !request.includeCurrent) {
|
|
continue;
|
|
}
|
|
if (comparison < 0 && !request.allowDowngrade) {
|
|
continue;
|
|
}
|
|
}
|
|
if (selected == nullptr || release.version > selected->version) {
|
|
selected = &release;
|
|
}
|
|
}
|
|
if (selected == nullptr) {
|
|
return std::nullopt;
|
|
}
|
|
return *selected;
|
|
}
|
|
|
|
Void::Result::Result<VerifiedSelection>
|
|
verify_and_select_release(std::string_view envelopeJson,
|
|
const Keyring& keys,
|
|
const SelectionRequest& request,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
auto verified = verifyFeedEnvelope(envelopeJson, keys, policy);
|
|
if (!verified.has_value()) {
|
|
return std::unexpected{std::move(verified.error())};
|
|
}
|
|
auto selected = selectRelease(verified->feed, request);
|
|
if (!selected.has_value()) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::schema_error,
|
|
"Update feed: no compatible release matched selection "
|
|
"request")};
|
|
}
|
|
|
|
VerifiedSelection out;
|
|
out.m_signed_envelope.assign(envelopeJson);
|
|
out.m_signed_payload = std::move(verified->signedPayload);
|
|
out.m_signer_key_id = std::move(verified->keyId);
|
|
out.m_feed_id = verified->feed.feedId;
|
|
out.m_sequence = verified->feed.sequence;
|
|
out.m_expires_at = verified->feed.expiresAt;
|
|
out.m_parse_policy = policy.parsePolicy;
|
|
out.m_release = ReleaseIdentity{
|
|
.component = std::move(selected->component),
|
|
.artifact_id = std::move(selected->artifactId),
|
|
.channel = std::move(selected->channel),
|
|
.version = std::move(selected->version),
|
|
.sequence = verified->feed.sequence,
|
|
.sha256 = std::move(selected->sha256),
|
|
.size = selected->size,
|
|
.url = std::move(selected->url),
|
|
.package_type = std::move(selected->packageType),
|
|
};
|
|
return out;
|
|
}
|
|
|
|
Void::Result::Result<VerifiedSelection> verify_and_select_component_set(
|
|
std::string_view catalogEnvelopeJson,
|
|
const std::map<std::string, std::string>& releaseEnvelopeJsons,
|
|
const Keyring& keys, std::string_view primaryComponentId,
|
|
const VerificationPolicy& policy)
|
|
{
|
|
auto cat_env = verifyEnvelope(catalogEnvelopeJson, keys, policy);
|
|
if (!cat_env.has_value()) {
|
|
return std::unexpected{std::move(cat_env.error())};
|
|
}
|
|
auto catalog =
|
|
parseComponentCatalogPayload(cat_env->signedPayload, policy);
|
|
if (!catalog.has_value()) {
|
|
return std::unexpected{std::move(catalog.error())};
|
|
}
|
|
if (catalog->components.size() >
|
|
UpdateLimits::kDefaultMaxComponentsPerTransaction) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::limit_exceeded,
|
|
"Component set: exceeds 32-component transaction limit")};
|
|
}
|
|
|
|
std::map<std::string, ComponentRelease> releases;
|
|
std::size_t edge_count = 0;
|
|
for (const auto& [comp_id, env_json] : releaseEnvelopeJsons) {
|
|
auto rel_env = verifyEnvelope(env_json, keys, policy);
|
|
if (!rel_env.has_value()) {
|
|
return std::unexpected{std::move(rel_env.error())};
|
|
}
|
|
auto rel =
|
|
parseComponentReleasePayload(rel_env->signedPayload, policy);
|
|
if (!rel.has_value()) {
|
|
return std::unexpected{std::move(rel.error())};
|
|
}
|
|
edge_count += rel->dependencies.size();
|
|
if (edge_count > UpdateLimits::kDefaultMaxDependencyEdges) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::limit_exceeded,
|
|
"Component set: exceeds 256 dependency-edge limit")};
|
|
}
|
|
releases.emplace(comp_id, std::move(*rel));
|
|
}
|
|
|
|
if (auto valid = validateComponentSet(*catalog, releases);
|
|
!valid.has_value()) {
|
|
return std::unexpected{std::move(valid.error())};
|
|
}
|
|
|
|
auto primary_it = releases.find(std::string{primaryComponentId});
|
|
if (primary_it == releases.end()) {
|
|
return std::unexpected{make_update_error(
|
|
UpdateErrorCode::invalid_argument,
|
|
"Component set: primaryComponentId not present in verified "
|
|
"set")};
|
|
}
|
|
|
|
const auto& primary = primary_it->second;
|
|
VerifiedSelection out;
|
|
out.m_signed_envelope.assign(catalogEnvelopeJson);
|
|
out.m_signed_payload = std::move(cat_env->signedPayload);
|
|
out.m_signer_key_id = std::move(cat_env->keyId);
|
|
out.m_feed_id = "component-catalog";
|
|
out.m_sequence = catalog->sequence;
|
|
out.m_expires_at = catalog->expiresAt;
|
|
out.m_parse_policy = policy.parsePolicy;
|
|
out.m_release = ReleaseIdentity{
|
|
.component = primary.componentId,
|
|
.artifact_id = primary.artifactIdentity,
|
|
.channel = primary.channel,
|
|
.version = primary.componentVersion,
|
|
.sequence = primary.sequence,
|
|
.sha256 = primary.artifact.sha256,
|
|
.size = primary.artifact.size,
|
|
.url = primary.artifact.url,
|
|
.package_type = primary.artifact.packageType,
|
|
};
|
|
out.m_components = std::move(releases);
|
|
return out;
|
|
}
|
|
} // namespace Void::Update
|