feat(update): fix schema-3 verify-before-parse and add replay floor, TrustStore, pin pruning, and InstallCoordinator
This commit is contained in:
1 parent
00d7478335
commit
47736cb6ce
13 files changed
+2663
-23
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -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>>
|
||||
|
||||
+193
-22
@@ -1,6 +1,7 @@
|
||||
#include <Void/Update/Feed.hpp>
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/Text/Base64.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
@@ -592,6 +593,26 @@ namespace Void::Update
|
||||
}
|
||||
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>
|
||||
@@ -599,8 +620,13 @@ namespace Void::Update
|
||||
const VerificationPolicy& policy)
|
||||
{
|
||||
if (payload.size() > policy.maxPayloadBytes) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: payload exceeds policy size");
|
||||
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);
|
||||
}
|
||||
@@ -665,25 +691,21 @@ namespace Void::Update
|
||||
}
|
||||
const auto key = keys.find(*keyId);
|
||||
if (key == keys.end()) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: envelope key is not trusted");
|
||||
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 Void::Result::fail(
|
||||
"Update feed: invalid or oversized envelope encoding");
|
||||
}
|
||||
if (*schema == 3) {
|
||||
auto signedDocument = Json::parse(*payload);
|
||||
if (!signedDocument || !signedDocument->is_object() ||
|
||||
displayedDocument == nullptr ||
|
||||
*displayedDocument != *signedDocument) {
|
||||
return Void::Result::fail("Update feed: readable document "
|
||||
"differs from signed payload");
|
||||
}
|
||||
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 =
|
||||
@@ -691,11 +713,30 @@ namespace Void::Update
|
||||
auto valid =
|
||||
Crypto::verifyEd25519(payloadBytes, signatureBytes, key->second);
|
||||
if (!valid) {
|
||||
return std::unexpected{valid.error()};
|
||||
return std::unexpected{make_update_error(
|
||||
UpdateErrorCode::signature_failed, valid.error().message())};
|
||||
}
|
||||
if (!*valid) {
|
||||
return Void::Result::fail(
|
||||
"Update feed: signature verification failed");
|
||||
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),
|
||||
@@ -707,8 +748,13 @@ namespace Void::Update
|
||||
const VerificationPolicy& policy)
|
||||
{
|
||||
if (payload.size() > policy.maxPayloadBytes) {
|
||||
return Void::Result::fail(
|
||||
"Component feed: payload exceeds policy size");
|
||||
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()) {
|
||||
@@ -754,8 +800,13 @@ namespace Void::Update
|
||||
const VerificationPolicy& policy)
|
||||
{
|
||||
if (payload.size() > policy.maxPayloadBytes) {
|
||||
return Void::Result::fail(
|
||||
"Component feed: payload exceeds policy size");
|
||||
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()) {
|
||||
@@ -919,4 +970,124 @@ namespace Void::Update
|
||||
}
|
||||
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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1721,6 +1721,124 @@ namespace Void::Update
|
||||
return removed;
|
||||
}
|
||||
|
||||
Void::Result::Result<PruneReport>
|
||||
VersionStore::pruneWithPins(std::size_t retainedPreviousVersions,
|
||||
std::span<const Semver::Version>
|
||||
pinnedVersions,
|
||||
std::size_t batchLimit)
|
||||
{
|
||||
if (batchLimit == 0) {
|
||||
return Void::Result::fail(
|
||||
"VersionStore::pruneWithPins: batchLimit must be positive");
|
||||
}
|
||||
for (const auto& path : {m_root, m_root / "versions"}) {
|
||||
if (auto checked = require_real_directory(path); !checked) {
|
||||
return std::unexpected{checked.error()};
|
||||
}
|
||||
}
|
||||
auto lock = FileLock::acquire(m_root / ".update.lock");
|
||||
if (!lock) {
|
||||
return std::unexpected{lock.error()};
|
||||
}
|
||||
if (auto cleaned = cleanup_pruning_entries(m_root / "versions");
|
||||
!cleaned) {
|
||||
return std::unexpected{cleaned.error()};
|
||||
}
|
||||
|
||||
auto current = currentVersion();
|
||||
if (!current) {
|
||||
return std::unexpected{current.error()};
|
||||
}
|
||||
auto pending = pendingActivation();
|
||||
if (!pending) {
|
||||
return std::unexpected{pending.error()};
|
||||
}
|
||||
auto history = read_health_history(m_root);
|
||||
if (!history) {
|
||||
return std::unexpected{history.error()};
|
||||
}
|
||||
auto published = published_versions(m_root / "versions");
|
||||
if (!published) {
|
||||
return std::unexpected{published.error()};
|
||||
}
|
||||
|
||||
std::sort(published->begin(), published->end(),
|
||||
std::greater<Semver::Version>{});
|
||||
std::set<std::string, std::less<>> publishedNames;
|
||||
for (const auto& version : *published) {
|
||||
publishedNames.insert(version.to_string());
|
||||
}
|
||||
|
||||
std::set<std::string, std::less<>> retained;
|
||||
std::optional<std::string> currentName;
|
||||
if (*current) {
|
||||
currentName = (**current).to_string();
|
||||
retained.insert(*currentName);
|
||||
}
|
||||
if (*pending) {
|
||||
retained.insert((*pending)->candidateVersion.to_string());
|
||||
if ((*pending)->previousVersion) {
|
||||
retained.insert((*pending)->previousVersion->to_string());
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t retainedPrevious = 0;
|
||||
for (auto iterator = history->committedOrder.rbegin();
|
||||
iterator != history->committedOrder.rend() &&
|
||||
retainedPrevious < retainedPreviousVersions;
|
||||
++iterator) {
|
||||
const auto state = history->states.find(*iterator);
|
||||
if (publishedNames.contains(*iterator) &&
|
||||
state != history->states.end() &&
|
||||
state->second == HealthState::healthy &&
|
||||
(!currentName || *iterator != *currentName) &&
|
||||
!retained.contains(*iterator)) {
|
||||
retained.insert(*iterator);
|
||||
++retainedPrevious;
|
||||
}
|
||||
}
|
||||
|
||||
std::set<std::string, std::less<>> pinnedNames;
|
||||
for (const auto& v : pinnedVersions) {
|
||||
pinnedNames.insert(v.to_string());
|
||||
}
|
||||
|
||||
PruneReport report;
|
||||
for (const auto& version : *published) {
|
||||
const auto name = version.to_string();
|
||||
if (retained.contains(name)) {
|
||||
continue;
|
||||
}
|
||||
const auto state = history->states.find(name);
|
||||
if (state == history->states.end() ||
|
||||
(state->second != HealthState::healthy &&
|
||||
state->second != HealthState::failed &&
|
||||
state->second != HealthState::retired)) {
|
||||
continue;
|
||||
}
|
||||
if (pinnedNames.contains(name)) {
|
||||
report.skipped_due_to_pins.push_back(version);
|
||||
continue;
|
||||
}
|
||||
if (report.removed.size() >= batchLimit) {
|
||||
report.batch_limit_reached = true;
|
||||
break;
|
||||
}
|
||||
if (state->second != HealthState::retired) {
|
||||
if (auto recorded = append_health_event(m_root, 'D', name);
|
||||
!recorded) {
|
||||
return std::unexpected{recorded.error()};
|
||||
}
|
||||
}
|
||||
if (auto pruned = quarantine_and_remove(m_root / "versions", name);
|
||||
!pruned) {
|
||||
return std::unexpected{pruned.error()};
|
||||
}
|
||||
report.removed.push_back(version);
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<Semver::Version>>
|
||||
VersionStore::currentVersion() const
|
||||
{
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
void_add_module(Update
|
||||
INTERNAL_DEPS Crypto Data Functional System Text
|
||||
INTERNAL_DEPS Archive Crypto Data Functional System Text Time
|
||||
)
|
||||
@@ -206,6 +206,14 @@ if(_has_archive)
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
has_modules(_has_update Update Archive Crypto Data Functional System Text Time)
|
||||
if(_has_update)
|
||||
run_consumer(UpdateOnly "${install_prefix}" "UpdateOnly"
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidUpdateOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS Update)
|
||||
|
||||
add_executable(void_update_only_consumer main.cpp)
|
||||
target_link_libraries(void_update_only_consumer PRIVATE Void::Update)
|
||||
target_compile_features(void_update_only_consumer PRIVATE cxx_std_26)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME UpdateOnlyConsumer COMMAND void_update_only_consumer)
|
||||
@@ -0,0 +1,22 @@
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/Update/Update.hpp>
|
||||
|
||||
int main()
|
||||
{
|
||||
auto k = Void::Crypto::Ed25519PrivateKey::generate();
|
||||
if (!k.has_value()) {
|
||||
return 1;
|
||||
}
|
||||
auto pub = k->public_key();
|
||||
if (!pub.has_value()) {
|
||||
return 2;
|
||||
}
|
||||
Void::Update::TrustStore trust;
|
||||
if (!trust.bootstrap({{"k1", pub->bytes}}).has_value()) {
|
||||
return 3;
|
||||
}
|
||||
if (!trust.snapshot().contains("k1")) {
|
||||
return 4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
#include <Void/Archive/Archive.hpp>
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Text/Base64.hpp>
|
||||
#include <Void/Text/Hex.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
#include <Void/Update/Update.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace Void::Update;
|
||||
|
||||
std::span<const std::byte> as_bytes(std::string_view s)
|
||||
{
|
||||
return std::as_bytes(std::span{s.data(), s.size()});
|
||||
}
|
||||
|
||||
std::vector<std::byte> to_vec(std::string_view s)
|
||||
{
|
||||
std::vector<std::byte> out(s.size());
|
||||
for (std::size_t i = 0; i < s.size(); ++i) {
|
||||
out[i] = static_cast<std::byte>(static_cast<unsigned char>(s[i]));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string sign_b64url(std::string_view payload,
|
||||
const Void::Crypto::Ed25519PrivateKey& key)
|
||||
{
|
||||
auto sig = Void::Crypto::sign_ed25519(as_bytes(payload), key);
|
||||
Void::Testing::require(sig.has_value());
|
||||
return Void::Encoding::Base64::encode_url(
|
||||
std::string_view{reinterpret_cast<const char*>(sig->bytes.data()),
|
||||
sig->bytes.size()});
|
||||
}
|
||||
|
||||
std::string make_feed_payload(std::string_view version,
|
||||
std::uint64_t sequence, std::string_view url,
|
||||
std::uint64_t size, std::string_view sha256)
|
||||
{
|
||||
return std::format(
|
||||
R"json({{
|
||||
"schemaVersion": 1,
|
||||
"feedId": "vendor-main",
|
||||
"sequence": {},
|
||||
"generatedAt": "2026-01-01T00:00:00Z",
|
||||
"expiresAt": "2099-01-01T00:00:00Z",
|
||||
"releases": [{{
|
||||
"component": "service",
|
||||
"artifactId": "main",
|
||||
"channel": "stable",
|
||||
"version": "{}",
|
||||
"cohort": "linux-abi-2",
|
||||
"platform": "linux",
|
||||
"arch": "x86_64",
|
||||
"url": "{}",
|
||||
"size": {},
|
||||
"sha256": "{}",
|
||||
"packageType": "tar.zst",
|
||||
"compatibility": {{
|
||||
"versionContracts": {{}},
|
||||
"exactContracts": {{}}
|
||||
}},
|
||||
"releaseManifestSha256": "2222222222222222222222222222222222222222222222222222222222222222"
|
||||
}}]
|
||||
}})json",
|
||||
sequence, version, url, size, sha256);
|
||||
}
|
||||
|
||||
std::string make_envelope_v1(std::string_view key_id,
|
||||
std::string_view payload,
|
||||
const Void::Crypto::Ed25519PrivateKey& key)
|
||||
{
|
||||
return std::format(
|
||||
R"json({{"schemaVersion":1,"keyId":"{}","payload":"{}","signature":"{}"}})json",
|
||||
key_id, Void::Encoding::Base64::encode_url(payload),
|
||||
sign_b64url(payload, key));
|
||||
}
|
||||
|
||||
struct BuiltPackage {
|
||||
std::filesystem::path path{};
|
||||
std::uint64_t size{0};
|
||||
std::string sha256{};
|
||||
};
|
||||
|
||||
BuiltPackage build_test_package(const std::filesystem::path& dir,
|
||||
std::string_view version)
|
||||
{
|
||||
const auto pkg_path = dir / std::format("service-{}.tar.zst", version);
|
||||
const std::array<Void::Archive::CreateEntry, 1> entries{{
|
||||
Void::Archive::CreateEntry{
|
||||
.path = "version.txt",
|
||||
.type = Void::Archive::EntryType::RegularFile,
|
||||
.executable = false,
|
||||
.content = to_vec(version),
|
||||
},
|
||||
}};
|
||||
Void::Testing::require(
|
||||
Void::Archive::create_archive(pkg_path, entries).has_value());
|
||||
auto digest = Void::Crypto::sha256File(pkg_path);
|
||||
Void::Testing::require(digest.has_value());
|
||||
return BuiltPackage{
|
||||
.path = pkg_path,
|
||||
.size = std::filesystem::file_size(pkg_path),
|
||||
.sha256 = Void::Encoding::Hex::encode(*digest),
|
||||
};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test update_schema3_verify_before_parse_and_strict_json_profile()
|
||||
{
|
||||
auto priv = Void::Crypto::Ed25519PrivateKey::generate();
|
||||
Void::Testing::require(priv.has_value());
|
||||
auto pub = priv->public_key();
|
||||
Void::Testing::require(pub.has_value());
|
||||
Keyring keys{{"k1", pub->bytes}};
|
||||
|
||||
// 1. Schema-3 envelope with INVALID signature AND MALFORMED non-JSON
|
||||
// payload must fail at signature verification (NOT JSON parse / mirror
|
||||
// mismatch!).
|
||||
{
|
||||
constexpr std::string_view corrupt_payload = "{not valid json!!!";
|
||||
const std::array<std::byte, 64> bad_sig{};
|
||||
const std::string env = std::format(
|
||||
R"json({{"schemaVersion":3,"keyId":"k1","document":{{"ok":1}},"signedPayload":"{}","signature":"{}"}})json",
|
||||
Void::Encoding::Base64::encode_url(corrupt_payload),
|
||||
Void::Encoding::Base64::encode_url(std::string_view{
|
||||
reinterpret_cast<const char*>(bad_sig.data()),
|
||||
bad_sig.size()}));
|
||||
auto res = verifyEnvelope(env, keys);
|
||||
Void::Testing::require(!res.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
res.error().code().value,
|
||||
static_cast<std::int32_t>(UpdateErrorCode::signature_failed));
|
||||
}
|
||||
|
||||
// 2. Schema-3 envelope with VALID signature and mismatched display mirror
|
||||
// fails with mirror_mismatch AFTER signature passes.
|
||||
{
|
||||
constexpr std::string_view signed_doc = R"json({"ok":1})json";
|
||||
const std::string env = std::format(
|
||||
R"json({{"schemaVersion":3,"keyId":"k1","document":{{"ok":2}},"signedPayload":"{}","signature":"{}"}})json",
|
||||
Void::Encoding::Base64::encode_url(signed_doc),
|
||||
sign_b64url(signed_doc, *priv));
|
||||
auto res = verifyEnvelope(env, keys);
|
||||
Void::Testing::require(!res.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
res.error().code().value,
|
||||
static_cast<std::int32_t>(UpdateErrorCode::mirror_mismatch));
|
||||
}
|
||||
|
||||
// 3. Mutating whitespace of signed bytes breaks signature verification.
|
||||
{
|
||||
constexpr std::string_view signed_doc = R"json({"ok":1})json";
|
||||
constexpr std::string_view mutated_doc = R"json({ "ok": 1 })json";
|
||||
const std::string env = std::format(
|
||||
R"json({{"schemaVersion":1,"keyId":"k1","payload":"{}","signature":"{}"}})json",
|
||||
Void::Encoding::Base64::encode_url(mutated_doc),
|
||||
sign_b64url(signed_doc, *priv));
|
||||
auto res = verifyEnvelope(env, keys);
|
||||
Void::Testing::require(!res.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
res.error().code().value,
|
||||
static_cast<std::int32_t>(UpdateErrorCode::signature_failed));
|
||||
}
|
||||
|
||||
// 4. SchemaParsePolicy::StrictJsonProfile rejects duplicate keys and
|
||||
// decimals while LegacyGeneralJson retains legacy acceptance.
|
||||
{
|
||||
constexpr std::string_view dup_payload =
|
||||
R"json({"a":1,"a":2})json";
|
||||
const std::string env = make_envelope_v1("k1", dup_payload, *priv);
|
||||
|
||||
VerificationPolicy legacy{};
|
||||
legacy.parsePolicy = SchemaParsePolicy::LegacyGeneralJson;
|
||||
Void::Testing::expect(verifyEnvelope(env, keys, legacy).has_value());
|
||||
|
||||
VerificationPolicy strict{};
|
||||
strict.parsePolicy = SchemaParsePolicy::StrictJsonProfile;
|
||||
auto strict_res = verifyEnvelope(env, keys, strict);
|
||||
Void::Testing::require(!strict_res.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
strict_res.error().code().value,
|
||||
static_cast<std::int32_t>(UpdateErrorCode::schema_error));
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test update_replay_floor_and_trust_store_rotation_revocation()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_update_floor_"};
|
||||
const auto floor_path = tmp / "replay_floor.json";
|
||||
|
||||
// 1. Durable monotonic floor survives restart & rejects replay.
|
||||
{
|
||||
ReplayFloorStore store{floor_path};
|
||||
Void::Testing::require(store.load().has_value());
|
||||
Void::Testing::require(store.advance("vendor-main", "stable", 10).has_value());
|
||||
Void::Testing::expect_eq(
|
||||
store.floor("vendor-main", "stable").value_or(0), 10ULL);
|
||||
}
|
||||
{
|
||||
ReplayFloorStore reloaded{floor_path};
|
||||
Void::Testing::require(reloaded.load().has_value());
|
||||
Void::Testing::expect_eq(
|
||||
reloaded.floor("vendor-main", "stable").value_or(0), 10ULL);
|
||||
|
||||
auto replay = reloaded.advance("vendor-main", "stable", 9);
|
||||
Void::Testing::require(!replay.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
replay.error().code().value,
|
||||
static_cast<std::int32_t>(UpdateErrorCode::replay_rejected));
|
||||
Void::Testing::require(
|
||||
reloaded.advance("vendor-main", "stable", 11).has_value());
|
||||
}
|
||||
|
||||
// Corrupt floor file triggers RecoveryRequired (never resets to 0).
|
||||
{
|
||||
std::ofstream corrupt{floor_path, std::ios::binary | std::ios::trunc};
|
||||
corrupt << R"({"schemaVersion":1,"sha256":"0000","payload":"{}"})";
|
||||
}
|
||||
{
|
||||
ReplayFloorStore broken{floor_path};
|
||||
auto r = broken.load();
|
||||
Void::Testing::require(!r.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
r.error().code().value,
|
||||
static_cast<std::int32_t>(UpdateErrorCode::recovery_required));
|
||||
}
|
||||
|
||||
// 2. TrustStore bootstrap, authenticated rotation, and revocation.
|
||||
auto k1 = Void::Crypto::Ed25519PrivateKey::generate();
|
||||
auto k2 = Void::Crypto::Ed25519PrivateKey::generate();
|
||||
Void::Testing::require(k1.has_value() && k2.has_value());
|
||||
auto pub1 = k1->public_key();
|
||||
auto pub2 = k2->public_key();
|
||||
Void::Testing::require(pub1.has_value() && pub2.has_value());
|
||||
|
||||
TrustStore trust;
|
||||
Void::Testing::require(trust.bootstrap({{"k1", pub1->bytes}}).has_value());
|
||||
|
||||
const std::string stmt = TrustStore::rotation_statement("k2", pub2->bytes);
|
||||
auto rot_sig = Void::Crypto::sign_ed25519(as_bytes(stmt), *k1);
|
||||
Void::Testing::require(rot_sig.has_value());
|
||||
|
||||
// Bad signature rejected.
|
||||
auto bad_sig = *rot_sig;
|
||||
bad_sig.bytes[0] ^= std::byte{0xFF};
|
||||
Void::Testing::expect(!trust
|
||||
.rotate_key_authenticated("k2", pub2->bytes,
|
||||
bad_sig.view(), "k1")
|
||||
.has_value());
|
||||
|
||||
// Valid authenticated rotation succeeds.
|
||||
Void::Testing::require(
|
||||
trust
|
||||
.rotate_key_authenticated("k2", pub2->bytes, rot_sig->view(), "k1")
|
||||
.has_value());
|
||||
Void::Testing::expect(trust.snapshot().contains("k2"));
|
||||
|
||||
// Revoking k1 removes it and forbids silent re-admission.
|
||||
Void::Testing::require(trust.revoke_key("k1").has_value());
|
||||
Void::Testing::expect(trust.is_revoked("k1"));
|
||||
Void::Testing::expect(!trust.snapshot().contains("k1"));
|
||||
Void::Testing::expect(
|
||||
!trust.rotate_key_operator("k1", pub1->bytes).has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test update_coordinator_install_rollback_pins_cleanup_pending_and_reconcile()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_update_coord_"};
|
||||
const auto pkg_dir = tmp / "packages";
|
||||
const auto store_dir = tmp / "store";
|
||||
const auto floor_path = tmp / "floor.json";
|
||||
std::filesystem::create_directories(pkg_dir);
|
||||
|
||||
auto priv = Void::Crypto::Ed25519PrivateKey::generate();
|
||||
Void::Testing::require(priv.has_value());
|
||||
auto pub = priv->public_key();
|
||||
Void::Testing::require(pub.has_value());
|
||||
Keyring keys{{"k1", pub->bytes}};
|
||||
|
||||
auto transport = std::make_shared<LocalFileArtifactTransport>();
|
||||
VersionStore vstore{store_dir};
|
||||
ReplayFloorStore floors{floor_path};
|
||||
Void::Testing::require(floors.load().has_value());
|
||||
|
||||
const SelectionRequest sel_req{
|
||||
.component = "service",
|
||||
.artifactId = "main",
|
||||
.channel = "stable",
|
||||
.environment = {.platform = "linux", .architecture = "x86_64"},
|
||||
};
|
||||
|
||||
auto make_verified_pkg = [&](std::string_view ver, std::uint64_t seq) {
|
||||
auto pkg = build_test_package(pkg_dir, ver);
|
||||
const std::string url =
|
||||
std::format("https://updates.invalid/service-{}.tar.zst", ver);
|
||||
transport->map_url(url, pkg.path);
|
||||
const std::string payload =
|
||||
make_feed_payload(ver, seq, url, pkg.size, pkg.sha256);
|
||||
const std::string env = make_envelope_v1("k1", payload, *priv);
|
||||
auto sel = verify_and_select_release(env, keys, sel_req);
|
||||
Void::Testing::require(sel.has_value());
|
||||
return *sel;
|
||||
};
|
||||
|
||||
// 1. Install v1.0.0 cleanly (internal activation + 3 consecutive probes).
|
||||
std::size_t probe_calls = 0;
|
||||
bool fail_cleanup = false;
|
||||
std::vector<Void::Semver::Version> pinned;
|
||||
LifecycleHooks hooks{
|
||||
.health_probe = [&](const Void::Semver::Version&,
|
||||
const std::filesystem::path&) {
|
||||
++probe_calls;
|
||||
return Void::Result::Result<bool>{true};
|
||||
},
|
||||
.live_pinned_versions = [&]() { return pinned; },
|
||||
.post_commit_cleanup_hook = [&]() -> Void::Result::Result<void> {
|
||||
if (fail_cleanup) {
|
||||
return std::unexpected{make_update_error(
|
||||
UpdateErrorCode::cleanup_pending,
|
||||
"injected post-commit cleanup failure")};
|
||||
}
|
||||
return {};
|
||||
},
|
||||
};
|
||||
|
||||
InstallCoordinator coord{vstore, floors, transport, hooks};
|
||||
Void::Time::ManualClock mono;
|
||||
InstallOptions iopts{};
|
||||
iopts.health_probe_interval = std::chrono::milliseconds{0};
|
||||
iopts.consecutive_healthy_required = 3;
|
||||
iopts.retained_previous_versions = 1;
|
||||
iopts.monotonic_clock = &mono;
|
||||
|
||||
auto sel_100 = make_verified_pkg("1.0.0", 1);
|
||||
auto r1 = coord.install(sel_100, iopts);
|
||||
Void::Testing::require(r1.has_value());
|
||||
Void::Testing::expect_eq(static_cast<int>(r1->state),
|
||||
static_cast<int>(InstallState::HealthyCommitted));
|
||||
Void::Testing::expect_eq(probe_calls, 3U);
|
||||
auto cur = vstore.currentVersion();
|
||||
Void::Testing::require(cur.has_value() && cur->has_value());
|
||||
Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.0.0"});
|
||||
|
||||
// 2. Truncated / bad-digest download fails before activation, leaving 1.0.0
|
||||
// active.
|
||||
auto sel_110 = make_verified_pkg("1.1.0", 2);
|
||||
transport->set_truncate_bytes(4);
|
||||
auto bad_dl = coord.install(sel_110, iopts);
|
||||
transport->set_truncate_bytes(std::nullopt);
|
||||
Void::Testing::require(!bad_dl.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
bad_dl.error().code().value,
|
||||
static_cast<std::int32_t>(UpdateErrorCode::size_mismatch));
|
||||
cur = vstore.currentVersion();
|
||||
Void::Testing::require(cur.has_value() && cur->has_value());
|
||||
Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.0.0"});
|
||||
|
||||
// 3. Unhealthy candidate rolls back cleanly via VersionStore.
|
||||
bool stopped_candidate = false;
|
||||
{
|
||||
LifecycleHooks unhealthy_hooks{
|
||||
.health_probe = [](const Void::Semver::Version&,
|
||||
const std::filesystem::path&) {
|
||||
return Void::Result::Result<bool>{false};
|
||||
},
|
||||
.stop_candidate = [&](const Void::Semver::Version&) {
|
||||
stopped_candidate = true;
|
||||
},
|
||||
};
|
||||
InstallCoordinator bad_coord{vstore, floors, transport, unhealthy_hooks};
|
||||
auto rb = bad_coord.install(sel_110, iopts);
|
||||
Void::Testing::require(rb.has_value());
|
||||
Void::Testing::expect_eq(static_cast<int>(rb->state),
|
||||
static_cast<int>(InstallState::RolledBack));
|
||||
Void::Testing::expect(stopped_candidate);
|
||||
cur = vstore.currentVersion();
|
||||
Void::Testing::require(cur.has_value() && cur->has_value());
|
||||
Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.0.0"});
|
||||
}
|
||||
|
||||
// 4. Post-commit cleanup failure reports CleanupPending WITHOUT rolling
|
||||
// back committed candidate, and retry_cleanup resolves it.
|
||||
auto sel_120 = make_verified_pkg("1.2.0", 3);
|
||||
fail_cleanup = true;
|
||||
auto cp = coord.install(sel_120, iopts);
|
||||
Void::Testing::require(cp.has_value());
|
||||
Void::Testing::expect_eq(static_cast<int>(cp->state),
|
||||
static_cast<int>(InstallState::CleanupPending));
|
||||
Void::Testing::expect(cp->cleanup_retryable);
|
||||
cur = vstore.currentVersion();
|
||||
Void::Testing::require(cur.has_value() && cur->has_value());
|
||||
Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.2.0"});
|
||||
|
||||
// Reconcile is idempotent and preserves CleanupPending until retried.
|
||||
auto rec1 = coord.reconcile();
|
||||
auto rec2 = coord.reconcile();
|
||||
Void::Testing::require(rec1.has_value() && rec2.has_value());
|
||||
Void::Testing::expect_eq(static_cast<int>(rec1->state),
|
||||
static_cast<int>(InstallState::CleanupPending));
|
||||
Void::Testing::expect_eq(static_cast<int>(rec2->state),
|
||||
static_cast<int>(InstallState::CleanupPending));
|
||||
|
||||
fail_cleanup = false;
|
||||
auto retried = coord.retry_cleanup(iopts);
|
||||
Void::Testing::require(retried.has_value());
|
||||
Void::Testing::expect_eq(static_cast<int>(retried->state),
|
||||
static_cast<int>(InstallState::HealthyCommitted));
|
||||
|
||||
// 5. Pin-aware pruning protects pinned live generation 1.0.0 while pruning
|
||||
// unpinned old versions.
|
||||
auto v100 = Void::Semver::parse_strict("1.0.0");
|
||||
Void::Testing::require(v100.has_value());
|
||||
pinned = {*v100};
|
||||
auto sel_130 = make_verified_pkg("1.3.0", 4);
|
||||
auto r3 = coord.install(sel_130, iopts);
|
||||
Void::Testing::require(r3.has_value());
|
||||
Void::Testing::expect_eq(static_cast<int>(r3->state),
|
||||
static_cast<int>(InstallState::HealthyCommitted));
|
||||
Void::Testing::expect(std::filesystem::exists(vstore.versionPath(*v100)));
|
||||
|
||||
auto prune_rep = vstore.pruneWithPins(1, pinned, 16);
|
||||
Void::Testing::require(prune_rep.has_value());
|
||||
Void::Testing::expect_eq(prune_rep->skipped_due_to_pins.size(), 1U);
|
||||
Void::Testing::expect_eq(prune_rep->skipped_due_to_pins[0].to_string(),
|
||||
std::string{"1.0.0"});
|
||||
|
||||
// 6. Corrupt operation journal halts reconcile with RecoveryRequired
|
||||
// without deleting the journal file.
|
||||
{
|
||||
std::ofstream bad_j{coord.operation_journal_path(),
|
||||
std::ios::binary | std::ios::trunc};
|
||||
bad_j << R"({"schemaVersion":99,"sha256":"dead","payload":"{}"})";
|
||||
}
|
||||
auto rec_err = coord.reconcile();
|
||||
Void::Testing::require(!rec_err.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
rec_err.error().code().value,
|
||||
static_cast<std::int32_t>(UpdateErrorCode::recovery_required));
|
||||
Void::Testing::expect(
|
||||
std::filesystem::exists(coord.operation_journal_path()));
|
||||
}
|
||||
Reference in new issue
Block a user