diff --git a/include/Void/Update/Feed.hpp b/include/Void/Update/Feed.hpp index 6016714..0014fde 100644 --- a/include/Void/Update/Feed.hpp +++ b/include/Void/Update/Feed.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -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 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& + 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 m_components{}; + + friend Void::Result::Result + verify_and_select_release(std::string_view envelopeJson, + const Keyring& keys, + const SelectionRequest& request, + const VerificationPolicy& policy); + + friend Void::Result::Result + verify_and_select_component_set( + std::string_view catalogEnvelopeJson, + const std::map& + 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 + 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 + verify_and_select_component_set( + std::string_view catalogEnvelopeJson, + const std::map& releaseEnvelopeJsons, + const Keyring& keys, std::string_view primaryComponentId, + const VerificationPolicy& policy = {}); } // namespace Void::Update diff --git a/include/Void/Update/Install.hpp b/include/Void/Update/Install.hpp new file mode 100644 index 0000000..278a1d1 --- /dev/null +++ b/include/Void/Update/Install.hpp @@ -0,0 +1,228 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 load(); + + [[nodiscard]] std::optional + 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 + 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> 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 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 + rotate_key_authenticated( + std::string new_key_id, + const Ed25519PublicKey& new_public_key, + std::span signature, + std::string_view authorizing_key_id); + + [[nodiscard]] Void::Result::Result + rotate_key_operator(std::string new_key_id, + const Ed25519PublicKey& new_public_key); + + [[nodiscard]] Void::Result::Result + 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> 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 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 + download( + const DownloadRequest& request, + const std::function< + Void::Result::Result(std::span)>& + 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 bytes) noexcept; + + [[nodiscard]] Void::Result::Result download( + const DownloadRequest& request, + const std::function< + Void::Result::Result(std::span)>& + on_chunk) override; + + private: + + struct Entry { + std::filesystem::path path{}; + std::string validator{}; + }; + mutable std::mutex m_mu{}; + std::map> m_entries{}; + bool m_fail_next{false}; + std::optional m_truncate_bytes{}; + }; + + struct LifecycleHooks { + /// Required when ActivationMode::ExternalLifecycle is selected. + std::function( + const Semver::Version&, const std::filesystem::path&)> + activate_external{}; + /// Cooperative health probe executed outside coordinator locks. + /// Defaults to immediately healthy if unset. + std::function( + const Semver::Version&, const std::filesystem::path&)> + health_probe{}; + /// Invoked before rollback on readiness failure to stop/join the + /// candidate cleanly. + std::function stop_candidate{}; + /// Returns currently pinned live generations (e.g. loaded plugins) + /// that pruning must not delete. + std::function()> live_pinned_versions{}; + /// Owning progress event snapshot invoked outside coordinator locks. + std::function on_progress{}; + /// Optional post-commit cleanup hook (also usable to inject cleanup + /// failures in tests to verify CleanupPending without rollback). + std::function()> + 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 transport, + LifecycleHooks hooks = {}); + + InstallCoordinator(const InstallCoordinator&) = delete; + InstallCoordinator& operator=(const InstallCoordinator&) = delete; + + [[nodiscard]] Void::Result::Result + 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 reconcile(); + + /// Retry post-commit cleanup/pruning after a CleanupPending + /// outcome. Never rolls back a committed version. + [[nodiscard]] Void::Result::Result + 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 m_transport; + LifecycleHooks m_hooks{}; + mutable std::mutex m_state_mu{}; + bool m_active{false}; + bool m_shutdown{false}; + }; + +} // namespace Void::Update diff --git a/include/Void/Update/Types.hpp b/include/Void/Update/Types.hpp new file mode 100644 index 0000000..ddb67d2 --- /dev/null +++ b/include/Void/Update/Types.hpp @@ -0,0 +1,209 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(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 isolated_archive_worker{}; + std::stop_token stop{}; + const Void::Time::MonotonicClock* monotonic_clock{nullptr}; + const Void::Time::CivilClock* civil_clock{nullptr}; + }; + +} // namespace Void::Update diff --git a/include/Void/Update/Update.hpp b/include/Void/Update/Update.hpp index a495265..753b755 100644 --- a/include/Void/Update/Update.hpp +++ b/include/Void/Update/Update.hpp @@ -1,4 +1,6 @@ #pragma once #include +#include +#include #include diff --git a/include/Void/Update/VersionStore.hpp b/include/Void/Update/VersionStore.hpp index cef46f2..e1e604e 100644 --- a/include/Void/Update/VersionStore.hpp +++ b/include/Void/Update/VersionStore.hpp @@ -8,10 +8,16 @@ #include #include #include +#include #include namespace Void::Update { + struct PruneReport { + std::vector removed{}; + std::vector skipped_due_to_pins{}; + bool batch_limit_reached{false}; + }; struct PendingActivation { std::optional previousVersion; Semver::Version candidateVersion; @@ -86,6 +92,16 @@ namespace Void::Update Void::Result::Result> 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 + pruneWithPins(std::size_t retainedPreviousVersions, + std::span pinnedVersions, + std::size_t batchLimit = 16); + [[nodiscard]] Void::Result::Result> currentVersion() const; [[nodiscard]] Void::Result::Result> diff --git a/src/Update/Feed.cpp b/src/Update/Feed.cpp index 1950e17..76a8ed2 100644 --- a/src/Update/Feed.cpp +++ b/src/Update/Feed.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -592,6 +593,26 @@ namespace Void::Update } return true; } + [[nodiscard]] Void::Result::Result + 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 @@ -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 + 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 verify_and_select_component_set( + std::string_view catalogEnvelopeJson, + const std::map& 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 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 diff --git a/src/Update/Install.cpp b/src/Update/Install.cpp new file mode 100644 index 0000000..098ddd2 --- /dev/null +++ b/src/Update/Install.cpp @@ -0,0 +1,1292 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Update +{ + namespace + { + std::atomic g_install_seq{0}; + + [[nodiscard]] std::string sha256_hex(std::string_view data) + { + auto d = Crypto::sha256(data); + if (!d.has_value()) { + return {}; + } + return Encoding::Hex::encode(*d); + } + + [[nodiscard]] std::string + state_to_string(InstallState state) noexcept + { + switch (state) { + case InstallState::Verified: + return "Verified"; + case InstallState::Downloading: + return "Downloading"; + case InstallState::Staged: + return "Staged"; + case InstallState::Published: + return "Published"; + case InstallState::Activated: + return "Activated"; + case InstallState::HealthyCommitted: + return "HealthyCommitted"; + case InstallState::CleanupPending: + return "CleanupPending"; + case InstallState::RolledBack: + return "RolledBack"; + case InstallState::RecoveryRequired: + return "RecoveryRequired"; + } + return "RecoveryRequired"; + } + + [[nodiscard]] std::optional + parse_state(std::string_view text) noexcept + { + if (text == "Verified") { + return InstallState::Verified; + } + if (text == "Downloading") { + return InstallState::Downloading; + } + if (text == "Staged") { + return InstallState::Staged; + } + if (text == "Published") { + return InstallState::Published; + } + if (text == "Activated") { + return InstallState::Activated; + } + if (text == "HealthyCommitted") { + return InstallState::HealthyCommitted; + } + if (text == "CleanupPending") { + return InstallState::CleanupPending; + } + if (text == "RolledBack") { + return InstallState::RolledBack; + } + if (text == "RecoveryRequired") { + return InstallState::RecoveryRequired; + } + return std::nullopt; + } + + [[nodiscard]] std::string floor_key(std::string_view feed_id, + std::string_view channel) + { + return std::format("{}\x1f{}", feed_id, channel); + } + + struct JournalRecord { + std::string install_id{}; + InstallState state{InstallState::Verified}; + ActivationMode activation_mode{ + ActivationMode::InternalVersionStore}; + std::string component{}; + std::string channel{}; + std::string version{}; + std::string signer_key_id{}; + std::uint64_t sequence{0}; + std::string diagnostic{}; + }; + + [[nodiscard]] std::string + serialize_journal_payload(const JournalRecord& rec) + { + Json::Value::Object_t obj; + obj.emplace_back("schemaVersion", Json::Value{std::int64_t{1}}); + obj.emplace_back("installId", Json::Value{rec.install_id}); + obj.emplace_back("state", Json::Value{state_to_string(rec.state)}); + obj.emplace_back( + "activationMode", + Json::Value{ + rec.activation_mode == ActivationMode::ExternalLifecycle + ? std::string{"external"} + : std::string{"internal"}}); + obj.emplace_back("component", Json::Value{rec.component}); + obj.emplace_back("channel", Json::Value{rec.channel}); + obj.emplace_back("version", Json::Value{rec.version}); + obj.emplace_back("signerKeyId", Json::Value{rec.signer_key_id}); + obj.emplace_back( + "sequence", Json::Value{static_cast(rec.sequence)}); + obj.emplace_back("diagnostic", Json::Value{rec.diagnostic}); + return Json::serialize(Json::Value{std::move(obj)}); + } + + [[nodiscard]] Void::Result::Result + write_operation_journal(const std::filesystem::path& path, + const JournalRecord& rec) + { + const std::string payload = serialize_journal_payload(rec); + const std::string checksum = sha256_hex(payload); + if (checksum.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + "Update: failed to checksum operation journal")}; + } + Json::Value::Object_t wrapper; + wrapper.emplace_back("schemaVersion", Json::Value{std::int64_t{1}}); + wrapper.emplace_back("sha256", Json::Value{checksum}); + wrapper.emplace_back("payload", Json::Value{payload}); + const std::string serialized = + Json::serialize(Json::Value{std::move(wrapper)}); + auto res = Void::FileSystem::replace_file( + path, serialized, + Void::FileSystem::ReplaceOptions{ + .durability = + Void::FileSystem::ReplaceDurability::durable_sync, + .mode = 0600}); + if (!res.has_value()) { + return std::unexpected{make_update_error( + res.error().durability_unknown + ? UpdateErrorCode::unknown_outcome + : UpdateErrorCode::io_error, + std::format("Update: write operation journal failed: {}", + res.error().error.message()))}; + } + return {}; + } + + [[nodiscard]] Void::Result::Result> + read_operation_journal(const std::filesystem::path& path) + { + std::error_code ec; + if (!std::filesystem::exists(path, ec)) { + if (ec) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + std::format("Update: inspect journal failed: {}", + ec.message()), + ec)}; + } + return std::optional{std::nullopt}; + } + + auto content = Void::FileSystem::read_file_bounded( + path, Void::FileSystem::ReadFileOptions{.max_bytes = 256 * 1024}); + if (!content.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + std::format("Update: unreadable operation journal: {}", + content.error().message()))}; + } + + auto wrapper = Json::parse(*content); + if (!wrapper.has_value() || !wrapper->is_object()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal is not valid JSON")}; + } + const auto* ver = wrapper->find("schemaVersion"); + const auto* sha = wrapper->find("sha256"); + const auto* pay = wrapper->find("payload"); + if (!ver || !ver->is_number() || ver->get_int().value_or(0) != 1 || + !sha || !sha->is_string() || !pay || !pay->is_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal has unknown schema or missing " + "checksum")}; + } + const std::string actual_sha = sha256_hex(pay->as_string()); + if (actual_sha != sha->as_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal checksum mismatch")}; + } + + auto doc = Json::parse(pay->as_string()); + if (!doc.has_value() || !doc->is_object()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal payload is corrupt")}; + } + const auto* state_val = doc->find("state"); + const auto* id_val = doc->find("installId"); + const auto* ver_val = doc->find("version"); + if (!state_val || !state_val->is_string() || !id_val || + !id_val->is_string() || !ver_val || !ver_val->is_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal missing required fields")}; + } + const auto parsed_state = parse_state(state_val->as_string()); + if (!parsed_state.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: unknown state in operation journal")}; + } + + JournalRecord rec; + rec.install_id = id_val->as_string(); + rec.state = *parsed_state; + if (const auto* m = doc->find("activationMode"); + m && m->is_string() && m->as_string() == "external") { + rec.activation_mode = ActivationMode::ExternalLifecycle; + } + if (const auto* c = doc->find("component"); c && c->is_string()) { + rec.component = c->as_string(); + } + if (const auto* ch = doc->find("channel"); ch && ch->is_string()) { + rec.channel = ch->as_string(); + } + rec.version = ver_val->as_string(); + if (const auto* k = doc->find("signerKeyId"); k && k->is_string()) { + rec.signer_key_id = k->as_string(); + } + if (const auto* s = doc->find("sequence"); s && s->is_number()) { + rec.sequence = s->get_uint().value_or(0); + } + if (const auto* d = doc->find("diagnostic"); d && d->is_string()) { + rec.diagnostic = d->as_string(); + } + return std::optional{std::move(rec)}; + } + + void remove_journal_best_effort(const std::filesystem::path& path) + { + std::error_code ec; + (void)std::filesystem::remove(path, ec); + } + } // namespace + + // ── ReplayFloorStore ───────────────────────────────────────────────────── + + ReplayFloorStore::ReplayFloorStore(std::filesystem::path file_path) + : m_path(std::move(file_path)) + { + } + + Void::Result::Result ReplayFloorStore::load() + { + std::lock_guard lk{m_mu}; + std::error_code ec; + if (!std::filesystem::exists(m_path, ec)) { + if (ec) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + std::format("ReplayFloorStore: inspect failed: {}", + ec.message()), + ec)}; + } + m_floors.clear(); + m_loaded = true; + return {}; + } + + auto text = Void::FileSystem::read_file_bounded( + m_path, Void::FileSystem::ReadFileOptions{.max_bytes = 1024 * 1024}); + if (!text.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + std::format("ReplayFloorStore: cannot read floor file: {}", + text.error().message()))}; + } + + auto wrapper = Json::parse(*text); + if (!wrapper.has_value() || !wrapper->is_object()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: corrupt floor file JSON")}; + } + const auto* ver = wrapper->find("schemaVersion"); + const auto* sha = wrapper->find("sha256"); + const auto* pay = wrapper->find("payload"); + if (!ver || !ver->is_number() || ver->get_int().value_or(0) != 1 || + !sha || !sha->is_string() || !pay || !pay->is_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: unknown schema or missing checksum")}; + } + if (sha256_hex(pay->as_string()) != sha->as_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: floor file checksum mismatch")}; + } + + auto doc = Json::parse(pay->as_string()); + if (!doc.has_value() || !doc->is_object()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: floor payload is not an object")}; + } + + std::map> loaded; + for (const auto& [k, v] : doc->as_object()) { + auto seq = v.get_uint(); + if (!seq.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: invalid sequence value")}; + } + loaded.emplace(k, *seq); + } + m_floors = std::move(loaded); + m_loaded = true; + return {}; + } + + std::optional + ReplayFloorStore::floor(std::string_view feed_id, + std::string_view channel) const + { + std::lock_guard lk{m_mu}; + const std::string key = floor_key(feed_id, channel); + auto it = m_floors.find(key); + if (it == m_floors.end()) { + return std::nullopt; + } + return it->second; + } + + Void::Result::Result + ReplayFloorStore::advance(std::string_view feed_id, + std::string_view channel, + std::uint64_t sequence, + bool require_strictly_greater) + { + if (feed_id.empty() || channel.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "ReplayFloorStore: feed_id and channel are required")}; + } + { + std::lock_guard lk{m_mu}; + if (!m_loaded) { + // Load before mutating to never clobber an existing persisted + // floor. + } + } + if (!m_loaded) { + if (auto ld = load(); !ld.has_value()) { + return ld; + } + } + + std::lock_guard lk{m_mu}; + const std::string key = floor_key(feed_id, channel); + auto it = m_floors.find(key); + if (it != m_floors.end()) { + if (sequence < it->second || + (require_strictly_greater && sequence == it->second)) { + return std::unexpected{make_update_error( + UpdateErrorCode::replay_rejected, + std::format("ReplayFloorStore: sequence {} rejected below " + "floor {}", + sequence, it->second))}; + } + if (sequence == it->second) { + return {}; + } + } + + auto next_map = m_floors; + next_map[key] = sequence; + + Json::Value::Object_t payload_obj; + for (const auto& [k, v] : next_map) { + payload_obj.emplace_back(k, Json::Value{v}); + } + const std::string payload = + Json::serialize(Json::Value{std::move(payload_obj)}); + const std::string checksum = sha256_hex(payload); + + Json::Value::Object_t wrapper; + wrapper.emplace_back("schemaVersion", Json::Value{std::int64_t{1}}); + wrapper.emplace_back("sha256", Json::Value{checksum}); + wrapper.emplace_back("payload", Json::Value{payload}); + const std::string serialized = + Json::serialize(Json::Value{std::move(wrapper)}); + + if (m_path.has_parent_path()) { + std::error_code ec; + std::filesystem::create_directories(m_path.parent_path(), ec); + } + auto written = Void::FileSystem::replace_file( + m_path, serialized, + Void::FileSystem::ReplaceOptions{ + .durability = Void::FileSystem::ReplaceDurability::durable_sync, + .mode = 0600}); + if (!written.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + std::format("ReplayFloorStore: persist failed: {}", + written.error().error.message()))}; + } + m_floors = std::move(next_map); + return {}; + } + + // ── TrustStore ─────────────────────────────────────────────────────────── + + std::string + TrustStore::rotation_statement(std::string_view new_key_id, + const Ed25519PublicKey& new_public_key) + { + return std::format("VOID_TRUST_ROTATE_V1:{}:{}", new_key_id, + Encoding::Hex::encode(new_public_key)); + } + + Void::Result::Result TrustStore::bootstrap(Keyring keys) + { + if (keys.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "TrustStore::bootstrap: at least one trust key is required")}; + } + std::lock_guard lk{m_mu}; + m_active = std::move(keys); + return {}; + } + + Void::Result::Result TrustStore::rotate_key_authenticated( + std::string new_key_id, const Ed25519PublicKey& new_public_key, + std::span signature, + std::string_view authorizing_key_id) + { + if (new_key_id.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "TrustStore: new_key_id must be non-empty")}; + } + std::lock_guard lk{m_mu}; + if (m_revoked.contains(new_key_id)) { + return std::unexpected{make_update_error( + UpdateErrorCode::untrusted_key, + "TrustStore: cannot re-admit revoked key_id")}; + } + auto auth_it = m_active.find(std::string{authorizing_key_id}); + if (auth_it == m_active.end()) { + return std::unexpected{make_update_error( + UpdateErrorCode::untrusted_key, + "TrustStore: authorizing key is not active")}; + } + const std::string stmt = rotation_statement(new_key_id, new_public_key); + auto ok = Crypto::verifyEd25519( + std::as_bytes(std::span{stmt.data(), stmt.size()}), signature, + auth_it->second); + if (!ok.has_value() || !*ok) { + return std::unexpected{make_update_error( + UpdateErrorCode::signature_failed, + "TrustStore: authenticated key rotation signature failed")}; + } + m_active[std::move(new_key_id)] = new_public_key; + return {}; + } + + Void::Result::Result + TrustStore::rotate_key_operator(std::string new_key_id, + const Ed25519PublicKey& new_public_key) + { + if (new_key_id.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "TrustStore: new_key_id must be non-empty")}; + } + std::lock_guard lk{m_mu}; + if (m_revoked.contains(new_key_id)) { + return std::unexpected{make_update_error( + UpdateErrorCode::untrusted_key, + "TrustStore: cannot re-admit revoked key_id")}; + } + m_active[std::move(new_key_id)] = new_public_key; + return {}; + } + + Void::Result::Result TrustStore::revoke_key(std::string_view key_id) + { + std::lock_guard lk{m_mu}; + auto it = m_active.find(std::string{key_id}); + if (it == m_active.end()) { + return std::unexpected{make_update_error( + UpdateErrorCode::untrusted_key, + "TrustStore: key_id not found in active keyring")}; + } + m_active.erase(it); + m_revoked.emplace(key_id); + return {}; + } + + Keyring TrustStore::snapshot() const + { + std::lock_guard lk{m_mu}; + return m_active; + } + + bool TrustStore::is_revoked(std::string_view key_id) const + { + std::lock_guard lk{m_mu}; + return m_revoked.contains(key_id); + } + + // ── LocalFileArtifactTransport ─────────────────────────────────────────── + + void LocalFileArtifactTransport::map_url(std::string url, + std::filesystem::path file_path, + std::string validator) + { + std::lock_guard lk{m_mu}; + m_entries[std::move(url)] = + Entry{.path = std::move(file_path), + .validator = std::move(validator)}; + } + + void LocalFileArtifactTransport::set_fail_next(bool fail) noexcept + { + std::lock_guard lk{m_mu}; + m_fail_next = fail; + } + + void LocalFileArtifactTransport::set_truncate_bytes( + std::optional bytes) noexcept + { + std::lock_guard lk{m_mu}; + m_truncate_bytes = bytes; + } + + Void::Result::Result LocalFileArtifactTransport::download( + const DownloadRequest& request, + const std::function< + Void::Result::Result(std::span)>& on_chunk) + { + Entry entry; + std::optional truncate_limit; + { + std::lock_guard lk{m_mu}; + if (m_fail_next) { + m_fail_next = false; + return std::unexpected{make_update_error( + UpdateErrorCode::transport_error, + "LocalFileArtifactTransport: injected transport error")}; + } + auto it = m_entries.find(request.url); + if (it == m_entries.end()) { + return std::unexpected{make_update_error( + UpdateErrorCode::transport_error, + std::format("LocalFileArtifactTransport: unknown URL '{}'", + request.url))}; + } + entry = it->second; + truncate_limit = m_truncate_bytes; + } + + std::ifstream in{entry.path, std::ios::binary}; + if (!in.is_open()) { + return std::unexpected{make_update_error( + UpdateErrorCode::transport_error, + std::format("LocalFileArtifactTransport: cannot open '{}'", + entry.path.string()))}; + } + + bool resumed = false; + if (request.resume_offset > 0 && request.resume_validator.has_value() && + *request.resume_validator == entry.validator) { + in.seekg(static_cast(request.resume_offset)); + resumed = static_cast(in); + } + + std::array buf{}; + std::size_t sent = 0; + while (in) { + if (request.stop.stop_requested()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cancelled, + "LocalFileArtifactTransport: cancelled")}; + } + std::size_t want = buf.size(); + if (truncate_limit.has_value()) { + if (sent >= *truncate_limit) { + break; + } + want = std::min(want, *truncate_limit - sent); + } + in.read(reinterpret_cast(buf.data()), + static_cast(want)); + const auto n = static_cast(in.gcount()); + if (n > 0) { + if (auto cb = on_chunk(std::span{buf.data(), n}); + !cb.has_value()) { + return std::unexpected{std::move(cb.error())}; + } + sent += n; + } + } + if (in.bad()) { + return std::unexpected{make_update_error( + UpdateErrorCode::transport_error, + "LocalFileArtifactTransport: I/O error reading artifact")}; + } + return DownloadMetadata{.validator = entry.validator, + .resumed = resumed}; + } + + // ── InstallCoordinator ─────────────────────────────────────────────────── + + InstallCoordinator::InstallCoordinator( + VersionStore& store, ReplayFloorStore& floor_store, + std::shared_ptr transport, LifecycleHooks hooks) + : m_store(store), m_floor_store(floor_store), + m_transport(std::move(transport)), m_hooks(std::move(hooks)) + { + } + + std::filesystem::path InstallCoordinator::operation_journal_path() const + { + return m_store.root() / ".update.op_journal.json"; + } + + void InstallCoordinator::shutdown() noexcept + { + std::lock_guard lk{m_state_mu}; + m_shutdown = true; + } + + bool InstallCoordinator::is_shutdown() const noexcept + { + std::lock_guard lk{m_state_mu}; + return m_shutdown; + } + + Void::Result::Result + InstallCoordinator::install(const VerifiedSelection& selection, + const InstallOptions& options) + { + if (!m_transport) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "InstallCoordinator: ArtifactTransport is required")}; + } + if (options.activation_mode == ActivationMode::ExternalLifecycle && + !m_hooks.activate_external) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "InstallCoordinator: ExternalLifecycle requires " + "activate_external hook")}; + } + + // Serialize one active install per store while keeping transport & + // lifecycle callbacks outside the coordinator state lock. + { + std::lock_guard lk{m_state_mu}; + if (m_shutdown) { + return std::unexpected{make_update_error( + UpdateErrorCode::closed, + "InstallCoordinator: coordinator is shut down")}; + } + if (m_active) { + return std::unexpected{make_update_error( + UpdateErrorCode::conflict, + "InstallCoordinator: another install is already active")}; + } + m_active = true; + } + struct ActiveGuard { + std::mutex& mu; + bool& active; + ~ActiveGuard() noexcept + { + std::lock_guard lk{mu}; + active = false; + } + } active_guard{m_state_mu, m_active}; + + const auto& mono_clock = + options.monotonic_clock + ? *options.monotonic_clock + : Void::Time::SystemMonotonicClock::instance(); + const auto& civil_clock = options.civil_clock + ? *options.civil_clock + : Void::Time::SystemCivilClock::instance(); + const auto deadline = mono_clock.now() + options.install_deadline; + + if (options.stop.stop_requested()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cancelled, + "InstallCoordinator: cancelled before admission")}; + } + if (civil_clock.now() >= selection.expires_at()) { + return std::unexpected{make_update_error( + UpdateErrorCode::expired, + "InstallCoordinator: verified selection is expired")}; + } + if (selection.release().size == 0 || + selection.release().size > options.max_artifact_bytes) { + return std::unexpected{make_update_error( + UpdateErrorCode::limit_exceeded, + "InstallCoordinator: artifact size exceeds policy")}; + } + + if (auto init = m_store.initialize(); !init.has_value()) { + return std::unexpected{std::move(init.error())}; + } + + // Check whether an unrecovered journal exists before admitting new + // work. + auto existing_j = read_operation_journal(operation_journal_path()); + if (!existing_j.has_value()) { + return std::unexpected{std::move(existing_j.error())}; + } + if (existing_j->has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "InstallCoordinator: prior operation journal present; run " + "reconcile() first")}; + } + + // Advance durable replay floor before download/install. + if (auto fl = m_floor_store.advance(selection.feed_id(), + selection.release().channel, + selection.sequence()); + !fl.has_value()) { + return std::unexpected{std::move(fl.error())}; + } + + const std::string install_id = + std::format("inst-{}-{}", static_cast(::getpid()), + g_install_seq.fetch_add(1, std::memory_order_relaxed)); + + InstallReceipt receipt{ + .install_id = install_id, + .state = InstallState::Verified, + .release = selection.release(), + .signer_key_id = selection.signer_key_id(), + }; + + auto emit_progress = [&]() { + if (m_hooks.on_progress) { + try { + m_hooks.on_progress(receipt); + } catch (...) { + } + } + }; + + auto persist_state = [&](InstallState st, + std::string diag = {}) -> Void::Result::Result { + receipt.state = st; + receipt.diagnostic = std::move(diag); + JournalRecord rec{ + .install_id = receipt.install_id, + .state = receipt.state, + .activation_mode = options.activation_mode, + .component = receipt.release.component, + .channel = receipt.release.channel, + .version = receipt.release.version.to_string(), + .signer_key_id = receipt.signer_key_id, + .sequence = receipt.release.sequence, + .diagnostic = receipt.diagnostic, + }; + auto w = write_operation_journal(operation_journal_path(), rec); + emit_progress(); + return w; + }; + + // 1. Download artifact to exclusive staging file while checking exact + // size and incremental SHA-256. + if (auto ps = persist_state(InstallState::Downloading); + !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + const auto staging_root = m_store.root() / "staging"; + const auto download_path = + staging_root / std::format(".dl-{}.tar.zst", install_id); + struct FileCleanup { + std::filesystem::path p{}; + ~FileCleanup() noexcept + { + if (!p.empty()) { + std::error_code ec; + (void)std::filesystem::remove(p, ec); + } + } + } dl_cleanup{download_path}; + + auto hasher = Crypto::Hasher::create(Crypto::HashAlgorithm::Sha256); + if (!hasher.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{std::move(hasher.error())}; + } + + int dl_fd = ::open(download_path.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + 0600); + if (dl_fd < 0) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::staging_error, + "InstallCoordinator: cannot create staging download file")}; + } + + std::uint64_t downloaded_bytes = 0; + DownloadRequest dreq{ + .url = receipt.release.url, + .expected_sha256 = receipt.release.sha256, + .expected_size = receipt.release.size, + .max_bytes = std::min(options.max_artifact_bytes, + options.staging_quota_bytes), + .stop = options.stop, + }; + + auto dl_res = m_transport->download( + dreq, + [&](std::span chunk) -> Void::Result::Result { + if (options.stop.stop_requested()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cancelled, + "InstallCoordinator: cancelled during download")}; + } + if (mono_clock.now() >= deadline) { + return std::unexpected{make_update_error( + UpdateErrorCode::timeout, + "InstallCoordinator: install deadline expired during " + "download")}; + } + const auto n = static_cast(chunk.size()); + if (n > dreq.max_bytes - downloaded_bytes || + n > receipt.release.size - downloaded_bytes) { + return std::unexpected{make_update_error( + UpdateErrorCode::size_mismatch, + "InstallCoordinator: downloaded bytes exceed declared " + "artifact size")}; + } + if (auto u = hasher->update(chunk); !u.has_value()) { + return std::unexpected{std::move(u.error())}; + } + std::size_t off = 0; + while (off < chunk.size()) { + const ssize_t w = ::write( + dl_fd, + reinterpret_cast(chunk.data()) + off, + chunk.size() - off); + if (w < 0 && errno == EINTR) { + continue; + } + if (w <= 0) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + "InstallCoordinator: write staging artifact " + "failed")}; + } + off += static_cast(w); + } + downloaded_bytes += n; + return {}; + }); + + const bool sync_ok = (::fsync(dl_fd) == 0); + (void)::close(dl_fd); + if (!dl_res.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{std::move(dl_res.error())}; + } + if (!sync_ok) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + "InstallCoordinator: fsync staging artifact failed")}; + } + if (downloaded_bytes != receipt.release.size) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::size_mismatch, + std::format("InstallCoordinator: downloaded {} bytes != " + "expected {}", + downloaded_bytes, receipt.release.size))}; + } + auto digest = hasher->finalize(); + if (!digest.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{std::move(digest.error())}; + } + const std::string actual_sha = Encoding::Hex::encode(*digest); + if (actual_sha != receipt.release.sha256) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::digest_mismatch, + "InstallCoordinator: artifact SHA-256 mismatch")}; + } + + // 2. Safe staged extraction via Archive + atomic publication into + // VersionStore. + Archive::StagedExtractionOptions ext_opts{}; + ext_opts.limits.max_total_bytes = + std::min(ext_opts.limits.max_total_bytes, + options.staging_quota_bytes); + ext_opts.limits.max_file_bytes = + std::min(ext_opts.limits.max_file_bytes, + options.staging_quota_bytes); + ext_opts.stop = options.stop; + ext_opts.deadline = deadline; + ext_opts.clock = &mono_clock; + + Void::Result::Result staged = + options.isolated_archive_worker.has_value() + ? Archive::extract_staged_isolated( + download_path, staging_root, + Archive::IsolationOptions{ + .worker_executable = *options.isolated_archive_worker, + .timeout = options.install_deadline, + .extraction = ext_opts}) + : Archive::extract_staged(download_path, staging_root, ext_opts); + if (!staged.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::staging_error, + std::format("InstallCoordinator: archive extraction failed: {}", + staged.error().message()))}; + } + if (auto ps = persist_state(InstallState::Staged); !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + // Publish staged tree as an immediate child of store/staging, then hand + // off to VersionStore::publish(). + const std::string ready_name = + std::format("{}.ready.{}", receipt.release.version.to_string(), + install_id); + auto stage_pub = staged->publish(ready_name); + if (!stage_pub.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::staging_error, + std::format("InstallCoordinator: staging handoff failed: {}", + stage_pub.error().message()))}; + } + if (stage_pub->outcome == Archive::PublicationOutcome::Unknown) { + return std::unexpected{make_update_error( + UpdateErrorCode::unknown_outcome, stage_pub->diagnostic)}; + } + + struct ReadyDirCleanup { + std::filesystem::path p{}; + ~ReadyDirCleanup() noexcept + { + if (!p.empty()) { + std::error_code ec; + (void)std::filesystem::remove_all(p, ec); + } + } + } ready_cleanup{stage_pub->destination_path}; + + if (auto pub = + m_store.publish(receipt.release.version, + stage_pub->destination_path); + !pub.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::staging_error, + std::format("InstallCoordinator: VersionStore::publish failed: " + "{}", + pub.error().message()))}; + } + ready_cleanup.p.clear(); // moved into versions/ + + if (auto ps = persist_state(InstallState::Published); !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + // 3. Activation (InternalVersionStore vs ExternalLifecycle — strictly + // separate!). + const auto published_dir = m_store.versionPath(receipt.release.version); + if (options.activation_mode == ActivationMode::InternalVersionStore) { + if (auto act = m_store.activate(receipt.release.version); + !act.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::activation_failed, act.error().message())}; + } + } else { + if (auto act = m_hooks.activate_external(receipt.release.version, + published_dir); + !act.has_value()) { + (void)m_store.recordFailed(receipt.release.version); + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::activation_failed, act.error().message())}; + } + } + if (auto ps = persist_state(InstallState::Activated); !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + // 4. Bounded cooperative health/readiness probes outside locks. + const auto readiness_deadline = + std::min(deadline, mono_clock.now() + options.readiness_timeout); + const std::size_t required_healthy = + std::max(1, options.consecutive_healthy_required); + std::size_t consecutive_ok = 0; + bool ready = false; + std::string readiness_diag; + + if (!m_hooks.health_probe) { + ready = true; + } else { + for (;;) { + if (options.stop.stop_requested()) { + readiness_diag = "cancelled before durable commit"; + break; + } + if (mono_clock.now() > readiness_deadline) { + readiness_diag = "readiness timeout expired"; + break; + } + auto probe = + m_hooks.health_probe(receipt.release.version, published_dir); + if (!probe.has_value()) { + readiness_diag = probe.error().message(); + break; + } + if (*probe) { + ++consecutive_ok; + if (consecutive_ok >= required_healthy) { + ready = true; + break; + } + } else { + consecutive_ok = 0; + } + if (mono_clock.now() >= readiness_deadline) { + readiness_diag = "candidate did not reach readiness"; + break; + } + if (!*probe && (options.monotonic_clock != nullptr || + options.health_probe_interval <= + std::chrono::milliseconds{0})) { + readiness_diag = "candidate health probe returned unhealthy"; + break; + } + if (options.health_probe_interval > + std::chrono::milliseconds{0} && + options.monotonic_clock == nullptr) { + std::this_thread::sleep_for(options.health_probe_interval); + } + } + } + + if (!ready) { + if (m_hooks.stop_candidate) { + m_hooks.stop_candidate(receipt.release.version); + } + if (options.activation_mode == + ActivationMode::InternalVersionStore) { + if (auto rb = m_store.rollback(); !rb.has_value()) { + (void)persist_state(InstallState::RecoveryRequired, + rb.error().message()); + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + std::format("InstallCoordinator: rollback failed: {}", + rb.error().message()))}; + } + } else { + (void)m_store.recordFailed(receipt.release.version); + } + (void)persist_state(InstallState::RolledBack, readiness_diag); + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + + // 5. Durable commit via VersionStore's single commit marker. + if (options.activation_mode == ActivationMode::InternalVersionStore) { + if (auto cm = m_store.commit(); !cm.has_value()) { + (void)persist_state(InstallState::RecoveryRequired, + cm.error().message()); + return std::unexpected{make_update_error( + UpdateErrorCode::unknown_outcome, + std::format("InstallCoordinator: commit outcome uncertain: " + "{}", + cm.error().message()))}; + } + } else { + if (auto rh = m_store.recordHealthy(receipt.release.version); + !rh.has_value()) { + (void)persist_state(InstallState::RecoveryRequired, + rh.error().message()); + return std::unexpected{make_update_error( + UpdateErrorCode::unknown_outcome, + std::format("InstallCoordinator: recordHealthy failed: {}", + rh.error().message()))}; + } + } + + if (auto ps = persist_state(InstallState::HealthyCommitted); + !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + // 6. Post-commit cleanup/pruning: failures become CleanupPending and + // NEVER trigger rollback of the committed version. + std::vector pins; + if (m_hooks.live_pinned_versions) { + pins = m_hooks.live_pinned_versions(); + } + std::string cleanup_diag; + if (auto pr = m_store.pruneWithPins(options.retained_previous_versions, + pins, options.prune_batch_limit); + !pr.has_value()) { + cleanup_diag = pr.error().message(); + } else if (m_hooks.post_commit_cleanup_hook) { + if (auto hk = m_hooks.post_commit_cleanup_hook(); !hk.has_value()) { + cleanup_diag = hk.error().message(); + } + } + + if (!cleanup_diag.empty()) { + receipt.cleanup_retryable = true; + (void)persist_state(InstallState::CleanupPending, cleanup_diag); + return receipt; + } + + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + + Void::Result::Result InstallCoordinator::reconcile() + { + auto journal = read_operation_journal(operation_journal_path()); + if (!journal.has_value()) { + return std::unexpected{std::move(journal.error())}; + } + + if (auto rec = m_store.reconcile(); !rec.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + std::format("InstallCoordinator::reconcile: VersionStore " + "reconcile failed: {}", + rec.error().message()))}; + } + + auto current = m_store.currentVersion(); + if (!current.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, current.error().message())}; + } + + InstallReceipt receipt{}; + if (!journal->has_value()) { + receipt.state = InstallState::HealthyCommitted; + if (current->has_value()) { + receipt.release.version = **current; + } + return receipt; + } + + const auto& j = **journal; + receipt.install_id = j.install_id; + receipt.signer_key_id = j.signer_key_id; + receipt.release.component = j.component; + receipt.release.channel = j.channel; + receipt.release.sequence = j.sequence; + if (auto pv = Semver::parse_strict(j.version); pv.has_value()) { + receipt.release.version = *pv; + } + + if (j.state == InstallState::RecoveryRequired) { + receipt.state = InstallState::RecoveryRequired; + receipt.diagnostic = j.diagnostic; + return receipt; + } + if (j.state == InstallState::CleanupPending) { + receipt.state = InstallState::CleanupPending; + receipt.diagnostic = j.diagnostic; + receipt.cleanup_retryable = true; + return receipt; + } + + // Determine outcome from VersionStore's authoritative durable evidence. + auto healthy = m_store.healthyPublishedVersions(); + bool candidate_healthy = false; + if (healthy.has_value()) { + for (const auto& hv : *healthy) { + if (hv.to_string() == j.version) { + candidate_healthy = true; + break; + } + } + } + + const bool is_current = + current->has_value() && (*current)->to_string() == j.version; + if (candidate_healthy && + (is_current || + j.activation_mode == ActivationMode::ExternalLifecycle)) { + receipt.state = InstallState::HealthyCommitted; + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + + // Candidate was not committed; VersionStore::reconcile() restored the + // previous version if activation had started. + receipt.state = InstallState::RolledBack; + receipt.diagnostic = "reconciled uncommitted operation"; + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + + Void::Result::Result + InstallCoordinator::retry_cleanup(const InstallOptions& options) + { + auto journal = read_operation_journal(operation_journal_path()); + if (!journal.has_value()) { + return std::unexpected{std::move(journal.error())}; + } + if (!journal->has_value()) { + return InstallReceipt{.state = InstallState::HealthyCommitted}; + } + const auto& j = **journal; + if (j.state != InstallState::CleanupPending && + j.state != InstallState::HealthyCommitted) { + return std::unexpected{make_update_error( + UpdateErrorCode::conflict, + "InstallCoordinator::retry_cleanup: journal is not in " + "CleanupPending state")}; + } + + std::vector pins; + if (m_hooks.live_pinned_versions) { + pins = m_hooks.live_pinned_versions(); + } + if (auto pr = m_store.pruneWithPins(options.retained_previous_versions, + pins, options.prune_batch_limit); + !pr.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cleanup_pending, pr.error().message())}; + } + if (m_hooks.post_commit_cleanup_hook) { + if (auto hk = m_hooks.post_commit_cleanup_hook(); !hk.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cleanup_pending, hk.error().message())}; + } + } + + InstallReceipt receipt{ + .install_id = j.install_id, + .state = InstallState::HealthyCommitted, + .signer_key_id = j.signer_key_id, + .cleanup_retryable = false, + }; + if (auto pv = Semver::parse_strict(j.version); pv.has_value()) { + receipt.release.version = *pv; + } + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + +} // namespace Void::Update diff --git a/src/Update/VersionStore.cpp b/src/Update/VersionStore.cpp index fe67952..836349d 100644 --- a/src/Update/VersionStore.cpp +++ b/src/Update/VersionStore.cpp @@ -1721,6 +1721,124 @@ namespace Void::Update return removed; } + Void::Result::Result + VersionStore::pruneWithPins(std::size_t retainedPreviousVersions, + std::span + 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{}); + std::set> publishedNames; + for (const auto& version : *published) { + publishedNames.insert(version.to_string()); + } + + std::set> retained; + std::optional 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> 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> VersionStore::currentVersion() const { diff --git a/src/Update/module.cmake b/src/Update/module.cmake index 0fac0c3..183c9ce 100644 --- a/src/Update/module.cmake +++ b/src/Update/module.cmake @@ -1,3 +1,3 @@ void_add_module(Update - INTERNAL_DEPS Crypto Data Functional System Text + INTERNAL_DEPS Archive Crypto Data Functional System Text Time ) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index f1feb57..dc26c00 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -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) diff --git a/tests/package/UpdateOnly/CMakeLists.txt b/tests/package/UpdateOnly/CMakeLists.txt new file mode 100644 index 0000000..56102e7 --- /dev/null +++ b/tests/package/UpdateOnly/CMakeLists.txt @@ -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) diff --git a/tests/package/UpdateOnly/main.cpp b/tests/package/UpdateOnly/main.cpp new file mode 100644 index 0000000..d8657a2 --- /dev/null +++ b/tests/package/UpdateOnly/main.cpp @@ -0,0 +1,22 @@ +#include +#include + +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; +} diff --git a/tests/standalone/Update/UpdateHardening.cpp b/tests/standalone/Update/UpdateHardening.cpp new file mode 100644 index 0000000..7e497c7 --- /dev/null +++ b/tests/standalone/Update/UpdateHardening.cpp @@ -0,0 +1,456 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Update; + + std::span as_bytes(std::string_view s) + { + return std::as_bytes(std::span{s.data(), s.size()}); + } + + std::vector to_vec(std::string_view s) + { + std::vector out(s.size()); + for (std::size_t i = 0; i < s.size(); ++i) { + out[i] = static_cast(static_cast(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(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 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 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(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(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(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(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(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(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(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(); + 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 pinned; + LifecycleHooks hooks{ + .health_probe = [&](const Void::Semver::Version&, + const std::filesystem::path&) { + ++probe_calls; + return Void::Result::Result{true}; + }, + .live_pinned_versions = [&]() { return pinned; }, + .post_commit_cleanup_hook = [&]() -> Void::Result::Result { + 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(r1->state), + static_cast(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(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{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(rb->state), + static_cast(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(cp->state), + static_cast(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(rec1->state), + static_cast(InstallState::CleanupPending)); + Void::Testing::expect_eq(static_cast(rec2->state), + static_cast(InstallState::CleanupPending)); + + fail_cleanup = false; + auto retried = coord.retry_cleanup(iopts); + Void::Testing::require(retried.has_value()); + Void::Testing::expect_eq(static_cast(retried->state), + static_cast(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(r3->state), + static_cast(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(UpdateErrorCode::recovery_required)); + Void::Testing::expect( + std::filesystem::exists(coord.operation_journal_path())); +}