feat(update): fix schema-3 verify-before-parse and add replay floor, TrustStore, pin pruning, and InstallCoordinator

This commit is contained in:
faumaray committed 2026-11-25 21:04:52 +03:00
1 parent 00d7478335
commit 47736cb6ce
13 files changed
+2663 -23

No files matched your search

+107
View File
@@ -4,6 +4,7 @@
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <Void/Update/Types.hpp>
#include <array>
#include <chrono>
@@ -68,6 +69,8 @@ namespace Void::Update
std::chrono::system_clock::time_point now{
std::chrono::system_clock::now()};
bool requireUnexpired{true};
SchemaParsePolicy parsePolicy{SchemaParsePolicy::LegacyGeneralJson};
std::size_t maxJsonDepth{64};
};
struct VerifiedFeed {
@@ -193,4 +196,108 @@ namespace Void::Update
/// Select the greatest compatible version, independent of feed order.
[[nodiscard]] std::optional<Release>
selectRelease(const Feed& feed, const SelectionRequest& request);
/// Non-forgeable signature-verified release selection retaining the exact
/// verified envelope bytes, signer key ID, policy decision, and selected
/// release/component metadata. Can only be constructed by verified factory
/// functions.
class VerifiedSelection
{
public:
VerifiedSelection(const VerifiedSelection&) = default;
VerifiedSelection(VerifiedSelection&&) noexcept = default;
VerifiedSelection& operator=(const VerifiedSelection&) = default;
VerifiedSelection& operator=(VerifiedSelection&&) noexcept = default;
[[nodiscard]] const std::string&
signed_envelope_bytes() const noexcept
{
return m_signed_envelope;
}
[[nodiscard]] const std::string&
signed_payload_bytes() const noexcept
{
return m_signed_payload;
}
[[nodiscard]] const std::string& signer_key_id() const noexcept
{
return m_signer_key_id;
}
[[nodiscard]] const std::string& feed_id() const noexcept
{
return m_feed_id;
}
[[nodiscard]] std::uint64_t sequence() const noexcept
{
return m_sequence;
}
[[nodiscard]] std::chrono::system_clock::time_point
expires_at() const noexcept
{
return m_expires_at;
}
[[nodiscard]] SchemaParsePolicy parse_policy() const noexcept
{
return m_parse_policy;
}
[[nodiscard]] const ReleaseIdentity& release() const noexcept
{
return m_release;
}
[[nodiscard]] const std::map<std::string, ComponentRelease>&
component_releases() const noexcept
{
return m_components;
}
private:
VerifiedSelection() = default;
std::string m_signed_envelope{};
std::string m_signed_payload{};
std::string m_signer_key_id{};
std::string m_feed_id{};
std::uint64_t m_sequence{0};
std::chrono::system_clock::time_point m_expires_at{};
SchemaParsePolicy m_parse_policy{
SchemaParsePolicy::LegacyGeneralJson};
ReleaseIdentity m_release{};
std::map<std::string, ComponentRelease> m_components{};
friend Void::Result::Result<VerifiedSelection>
verify_and_select_release(std::string_view envelopeJson,
const Keyring& keys,
const SelectionRequest& request,
const VerificationPolicy& policy);
friend 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);
};
/// Verify an aggregate feed envelope (verify-before-parse), validate
/// policy, and produce a non-forgeable VerifiedSelection for the best
/// compatible release.
[[nodiscard]] Void::Result::Result<VerifiedSelection>
verify_and_select_release(std::string_view envelopeJson,
const Keyring& keys,
const SelectionRequest& request,
const VerificationPolicy& policy = {});
/// Verify a signed component catalog envelope and signed per-component
/// release envelopes, validate dependency closure and transaction limits
/// (<= 32 components, <= 256 dependency edges), and return a non-forgeable
/// VerifiedSelection.
[[nodiscard]] 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 = {});
} // namespace Void::Update
+228
View File
@@ -0,0 +1,228 @@
#pragma once
#include <Void/Archive/Archive.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Update/Feed.hpp>
#include <Void/Update/Types.hpp>
#include <Void/Update/VersionStore.hpp>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Update
{
/// Durable high-water sequence floor per (feed_id, channel) persisted via
/// atomic file replacement + directory sync. Monotonic across restarts, key
/// rotations, and civil-clock rollbacks; corrupt floor files fail with
/// RecoveryRequired instead of resetting to zero.
class ReplayFloorStore
{
public:
explicit ReplayFloorStore(std::filesystem::path file_path);
[[nodiscard]] Void::Result::Result<void> load();
[[nodiscard]] std::optional<std::uint64_t>
floor(std::string_view feed_id,
std::string_view channel) const;
/// Validate `sequence >= stored_floor` (or strictly `>` when
/// `require_strictly_greater` is true) and durably persist the new
/// high-water mark before returning.
[[nodiscard]] Void::Result::Result<void>
advance(std::string_view feed_id, std::string_view channel,
std::uint64_t sequence,
bool require_strictly_greater = false);
private:
std::filesystem::path m_path{};
mutable std::mutex m_mu{};
std::map<std::string, std::uint64_t, std::less<>> m_floors{};
bool m_loaded{false};
};
/// Explicit trust-root store supporting application bootstrap,
/// authenticated old-trust key rotation, operator-approved rotation, and
/// key revocation without rewriting historical signed bytes.
class TrustStore
{
public:
[[nodiscard]] static std::string
rotation_statement(std::string_view new_key_id,
const Ed25519PublicKey& new_public_key);
[[nodiscard]] Void::Result::Result<void> bootstrap(Keyring keys);
/// Rotate in `new_key_id` using an Ed25519 signature produced by an
/// active trusted key (`authorizing_key_id`) over
/// `rotation_statement(new_key_id, new_public_key)`.
[[nodiscard]] Void::Result::Result<void>
rotate_key_authenticated(
std::string new_key_id,
const Ed25519PublicKey& new_public_key,
std::span<const std::byte> signature,
std::string_view authorizing_key_id);
[[nodiscard]] Void::Result::Result<void>
rotate_key_operator(std::string new_key_id,
const Ed25519PublicKey& new_public_key);
[[nodiscard]] Void::Result::Result<void>
revoke_key(std::string_view key_id);
[[nodiscard]] Keyring snapshot() const;
[[nodiscard]] bool is_revoked(std::string_view key_id) const;
private:
mutable std::mutex m_mu{};
Keyring m_active{};
std::set<std::string, std::less<>> m_revoked{};
};
struct DownloadRequest {
std::string url{};
std::string expected_sha256{};
std::uint64_t expected_size{0};
std::uint64_t max_bytes{0};
std::optional<std::string> resume_validator{};
std::uint64_t resume_offset{0};
std::stop_token stop{};
};
struct DownloadMetadata {
std::string validator{};
bool resumed{false};
};
/// Abstract bounded artifact download transport. Concrete Net/HTTP
/// transports implement this interface without coupling Update to Net.
class ArtifactTransport
{
public:
virtual ~ArtifactTransport() = default;
[[nodiscard]] virtual Void::Result::Result<DownloadMetadata>
download(
const DownloadRequest& request,
const std::function<
Void::Result::Result<void>(std::span<const std::byte>)>&
on_chunk) = 0;
};
/// Offline local-file transport for deterministic update workflow and
/// installed-consumer testing.
class LocalFileArtifactTransport final : public ArtifactTransport
{
public:
void map_url(std::string url, std::filesystem::path file_path,
std::string validator = "v1");
void set_fail_next(bool fail) noexcept;
void set_truncate_bytes(std::optional<std::size_t> bytes) noexcept;
[[nodiscard]] Void::Result::Result<DownloadMetadata> download(
const DownloadRequest& request,
const std::function<
Void::Result::Result<void>(std::span<const std::byte>)>&
on_chunk) override;
private:
struct Entry {
std::filesystem::path path{};
std::string validator{};
};
mutable std::mutex m_mu{};
std::map<std::string, Entry, std::less<>> m_entries{};
bool m_fail_next{false};
std::optional<std::size_t> m_truncate_bytes{};
};
struct LifecycleHooks {
/// Required when ActivationMode::ExternalLifecycle is selected.
std::function<Void::Result::Result<void>(
const Semver::Version&, const std::filesystem::path&)>
activate_external{};
/// Cooperative health probe executed outside coordinator locks.
/// Defaults to immediately healthy if unset.
std::function<Void::Result::Result<bool>(
const Semver::Version&, const std::filesystem::path&)>
health_probe{};
/// Invoked before rollback on readiness failure to stop/join the
/// candidate cleanly.
std::function<void(const Semver::Version&)> stop_candidate{};
/// Returns currently pinned live generations (e.g. loaded plugins)
/// that pruning must not delete.
std::function<std::vector<Semver::Version>()> live_pinned_versions{};
/// Owning progress event snapshot invoked outside coordinator locks.
std::function<void(const InstallReceipt&)> on_progress{};
/// Optional post-commit cleanup hook (also usable to inject cleanup
/// failures in tests to verify CleanupPending without rollback).
std::function<Void::Result::Result<void>()>
post_commit_cleanup_hook{};
};
/// Serialized per-store installation orchestrator combining verified
/// selections, monotonic replay floors, exact-digest streaming downloads,
/// Archive atomic staging, VersionStore single-commit activation,
/// checksummed operation journaling, and pin-aware bounded pruning.
class InstallCoordinator
{
public:
InstallCoordinator(VersionStore& store,
ReplayFloorStore& floor_store,
std::shared_ptr<ArtifactTransport> transport,
LifecycleHooks hooks = {});
InstallCoordinator(const InstallCoordinator&) = delete;
InstallCoordinator& operator=(const InstallCoordinator&) = delete;
[[nodiscard]] Void::Result::Result<InstallReceipt>
install(const VerifiedSelection& selection,
const InstallOptions& options = {});
/// Idempotent recovery pass inspecting both the checksummed
/// operation journal and VersionStore's durable activation/health
/// evidence. Corrupt or unknown journal records halt with
/// RecoveryRequired without discarding evidence.
[[nodiscard]] Void::Result::Result<InstallReceipt> reconcile();
/// Retry post-commit cleanup/pruning after a CleanupPending
/// outcome. Never rolls back a committed version.
[[nodiscard]] Void::Result::Result<InstallReceipt>
retry_cleanup(const InstallOptions& options = {});
void shutdown() noexcept;
[[nodiscard]] bool is_shutdown() const noexcept;
[[nodiscard]] std::filesystem::path
operation_journal_path() const;
private:
VersionStore& m_store;
ReplayFloorStore& m_floor_store;
std::shared_ptr<ArtifactTransport> m_transport;
LifecycleHooks m_hooks{};
mutable std::mutex m_state_mu{};
bool m_active{false};
bool m_shutdown{false};
};
} // namespace Void::Update
+209
View File
@@ -0,0 +1,209 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
#include <stop_token>
#include <string>
#include <system_error>
#include <utility>
namespace Void::Update
{
enum class UpdateErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
signature_failed = 2,
untrusted_key = 3,
replay_rejected = 4,
expired = 5,
schema_error = 6,
mirror_mismatch = 7,
digest_mismatch = 8,
size_mismatch = 9,
limit_exceeded = 10,
transport_error = 11,
staging_error = 12,
activation_failed = 13,
health_check_failed = 14,
recovery_required = 15,
cleanup_pending = 16,
unknown_outcome = 17,
conflict = 18,
cancelled = 19,
timeout = 20,
closed = 21,
io_error = 22
};
[[nodiscard]] inline Void::Result::Error
make_update_error(UpdateErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case UpdateErrorCode::none:
kind = ErrorKind::internal;
break;
case UpdateErrorCode::invalid_argument:
case UpdateErrorCode::schema_error:
kind = ErrorKind::invalid_argument;
break;
case UpdateErrorCode::signature_failed:
case UpdateErrorCode::untrusted_key:
case UpdateErrorCode::mirror_mismatch:
case UpdateErrorCode::digest_mismatch:
case UpdateErrorCode::size_mismatch:
case UpdateErrorCode::recovery_required:
kind = ErrorKind::corrupt;
break;
case UpdateErrorCode::replay_rejected:
case UpdateErrorCode::expired:
case UpdateErrorCode::conflict:
case UpdateErrorCode::cleanup_pending:
kind = ErrorKind::conflict;
break;
case UpdateErrorCode::limit_exceeded:
kind = ErrorKind::exhausted;
break;
case UpdateErrorCode::transport_error:
case UpdateErrorCode::staging_error:
case UpdateErrorCode::io_error:
kind = ErrorKind::io;
break;
case UpdateErrorCode::activation_failed:
case UpdateErrorCode::health_check_failed:
case UpdateErrorCode::unknown_outcome:
kind = ErrorKind::internal;
break;
case UpdateErrorCode::cancelled:
case UpdateErrorCode::closed:
kind = ErrorKind::cancelled;
break;
case UpdateErrorCode::timeout:
kind = ErrorKind::timeout;
break;
}
const ErrorCode domain_code{Void::Result::kUpdateErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code, sys_err};
}
/// Explicit JSON parsing policy for signed payloads (C-07).
/// LegacyGeneralJson preserves existing accepted documents;
/// StrictJsonProfile additionally enforces Void::Json::Strict rules
/// (no duplicate keys, integer-only strict numbers, bounded nesting depth).
enum class SchemaParsePolicy : std::uint8_t {
LegacyGeneralJson = 0,
StrictJsonProfile = 1
};
enum class InstallState : std::uint8_t {
Verified = 0,
Downloading,
Staged,
Published,
Activated,
HealthyCommitted,
CleanupPending,
RolledBack,
RecoveryRequired
};
enum class ActivationMode : std::uint8_t {
InternalVersionStore = 0,
ExternalLifecycle = 1
};
struct UpdateLimits {
static constexpr std::size_t kDefaultMaxActiveInstalls = 1;
static constexpr std::size_t kDefaultMaxQueuedSelections = 8;
static constexpr std::size_t kDefaultMaxConcurrentDownloads = 2;
static constexpr std::uint64_t kDefaultMaxArtifactBytes =
512ULL * 1024 * 1024;
static constexpr std::uint64_t kDefaultStagingQuotaBytes =
2ULL * 1024 * 1024 * 1024;
static constexpr std::size_t kDefaultMaxComponentsPerTransaction =
32;
static constexpr std::size_t kDefaultMaxDependencyEdges = 256;
static constexpr std::chrono::milliseconds kDefaultInstallDeadline{
std::chrono::minutes{10}};
static constexpr std::chrono::milliseconds kDefaultReadinessTimeout{
std::chrono::seconds{30}};
static constexpr std::chrono::milliseconds
kDefaultHealthProbeInterval{std::chrono::seconds{1}};
static constexpr std::size_t kDefaultConsecutiveHealthyRequired = 3;
static constexpr std::size_t kDefaultRetainedPreviousVersions = 2;
static constexpr std::size_t kDefaultPruneBatchLimit = 16;
};
struct ReleaseIdentity {
std::string component{};
std::string artifact_id{};
std::string channel{};
Semver::Version version{};
std::uint64_t sequence{0};
std::string sha256{};
std::uint64_t size{0};
std::string url{};
std::string package_type{};
};
struct InstallReceipt {
std::string install_id{};
InstallState state{InstallState::Verified};
ReleaseIdentity release{};
std::string signer_key_id{};
std::string diagnostic{};
bool cleanup_retryable{false};
};
struct InstallOptions {
ActivationMode activation_mode{
ActivationMode::InternalVersionStore};
std::size_t max_active_installs{
UpdateLimits::kDefaultMaxActiveInstalls};
std::size_t max_queued_selections{
UpdateLimits::kDefaultMaxQueuedSelections};
std::size_t max_concurrent_downloads{
UpdateLimits::kDefaultMaxConcurrentDownloads};
std::uint64_t max_artifact_bytes{
UpdateLimits::kDefaultMaxArtifactBytes};
std::uint64_t staging_quota_bytes{
UpdateLimits::kDefaultStagingQuotaBytes};
std::size_t max_components{
UpdateLimits::kDefaultMaxComponentsPerTransaction};
std::size_t max_dependency_edges{
UpdateLimits::kDefaultMaxDependencyEdges};
std::chrono::milliseconds install_deadline{
UpdateLimits::kDefaultInstallDeadline};
std::chrono::milliseconds readiness_timeout{
UpdateLimits::kDefaultReadinessTimeout};
std::chrono::milliseconds health_probe_interval{
UpdateLimits::kDefaultHealthProbeInterval};
std::size_t consecutive_healthy_required{
UpdateLimits::kDefaultConsecutiveHealthyRequired};
std::size_t retained_previous_versions{
UpdateLimits::kDefaultRetainedPreviousVersions};
std::size_t prune_batch_limit{
UpdateLimits::kDefaultPruneBatchLimit};
bool allow_resumable_download{false};
std::optional<std::filesystem::path> isolated_archive_worker{};
std::stop_token stop{};
const Void::Time::MonotonicClock* monotonic_clock{nullptr};
const Void::Time::CivilClock* civil_clock{nullptr};
};
} // namespace Void::Update
+2
View File
@@ -1,4 +1,6 @@
#pragma once
#include <Void/Update/Feed.hpp>
#include <Void/Update/Install.hpp>
#include <Void/Update/Types.hpp>
#include <Void/Update/VersionStore.hpp>
+16
View File
@@ -8,10 +8,16 @@
#include <cstdint>
#include <filesystem>
#include <optional>
#include <span>
#include <vector>
namespace Void::Update
{
struct PruneReport {
std::vector<Semver::Version> removed{};
std::vector<Semver::Version> skipped_due_to_pins{};
bool batch_limit_reached{false};
};
struct PendingActivation {
std::optional<Semver::Version> previousVersion;
Semver::Version candidateVersion;
@@ -86,6 +92,16 @@ namespace Void::Update
Void::Result::Result<std::vector<Semver::Version>>
prune(std::size_t retainedPreviousVersions);
/// Pin-aware bounded pruning pass. Never deletes the active
/// version, pending activation candidate/previous, top
/// `retainedPreviousVersions` healthy versions, or any version in
/// `pinnedVersions`. Reports pin-blocked candidates and honors
/// `batchLimit` (default 16 publications per pass).
[[nodiscard]] Void::Result::Result<PruneReport>
pruneWithPins(std::size_t retainedPreviousVersions,
std::span<const Semver::Version> pinnedVersions,
std::size_t batchLimit = 16);
[[nodiscard]] Void::Result::Result<std::optional<Semver::Version>>
currentVersion() const;
[[nodiscard]] Void::Result::Result<std::optional<PendingActivation>>