From 7ea146dd3699e571a7e6a75c1f00b9a9c067ad84 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 5 Sep 2026 18:09:11 +0200 Subject: [PATCH] Cut idunn-daemon and the vendored cultmesh fork out of Odin Idunn now lives at https://github.com/GameCult/Idunn with its full 136-commit history. Odin no longer contains the deployment authority that manages it. Also removes vendor/cultmesh-rs, the private fork that had diverged from CultLib in both directions. Its unique capability -- the RUDP document server and the message_id correlation rework -- was reconciled into CultLib first, so this deletes a duplicate rather than a capability. The four crates that consumed it by path (muninn-daemon, odin-core, odin-daemon, sleipnir-daemon) now consume CultLib at c13b6ba like everything else. What deliberately stays in Odin: crates/odin-core/src/idunn.rs, which is Odin's own projection of Idunn state for aggregation and is Odin's to own; src/odin/idunn-rudp.cjs, its client for talking to Idunn; and deployment/idunn/recipe.toml, which despite the path is Odin's own deployment recipe expressed in Idunn's format -- it builds odin-daemon. odin-core: 22 passed, 0 failed, unchanged across the cut. odin-daemon still fails to compile on Windows for the pre-existing Unix-only std::os::fd reason. Co-Authored-By: Claude Opus 5 --- Cargo.toml | 2 - crates/idunn-daemon/Cargo.toml | 37 - .../idunn-daemon/src/bin/idunn-provision.rs | 6 - crates/idunn-daemon/src/control_plane.rs | 5923 ------------- crates/idunn-daemon/src/deployment.rs | 2110 ----- crates/idunn-daemon/src/deployment_plan.rs | 1560 ---- crates/idunn-daemon/src/drivers.rs | 7337 ----------------- crates/idunn-daemon/src/lib.rs | 5 - crates/idunn-daemon/src/main.rs | 3 - crates/idunn-daemon/src/provisioning.rs | 2455 ------ crates/idunn-daemon/tests/fixtures/README.md | 12 - .../bifrost-release-authority-v1.payload.hex | 1 - crates/muninn-daemon/Cargo.toml | 2 +- crates/odin-core/Cargo.toml | 2 +- crates/odin-daemon/Cargo.toml | 2 +- crates/sleipnir-daemon/Cargo.toml | 2 +- vendor/cultmesh-rs/Cargo.lock | 1360 --- vendor/cultmesh-rs/Cargo.toml | 20 - vendor/cultmesh-rs/src/lib.rs | 1557 ---- .../cultmesh-rs/src/rudp_document_server.rs | 647 -- .../cultmesh-rs/tests/rudp_document_server.rs | 553 -- 21 files changed, 4 insertions(+), 23592 deletions(-) delete mode 100644 crates/idunn-daemon/Cargo.toml delete mode 100644 crates/idunn-daemon/src/bin/idunn-provision.rs delete mode 100644 crates/idunn-daemon/src/control_plane.rs delete mode 100644 crates/idunn-daemon/src/deployment.rs delete mode 100644 crates/idunn-daemon/src/deployment_plan.rs delete mode 100644 crates/idunn-daemon/src/drivers.rs delete mode 100644 crates/idunn-daemon/src/lib.rs delete mode 100644 crates/idunn-daemon/src/main.rs delete mode 100644 crates/idunn-daemon/src/provisioning.rs delete mode 100644 crates/idunn-daemon/tests/fixtures/README.md delete mode 100644 crates/idunn-daemon/tests/fixtures/bifrost-release-authority-v1.payload.hex delete mode 100644 vendor/cultmesh-rs/Cargo.lock delete mode 100644 vendor/cultmesh-rs/Cargo.toml delete mode 100644 vendor/cultmesh-rs/src/lib.rs delete mode 100644 vendor/cultmesh-rs/src/rudp_document_server.rs delete mode 100644 vendor/cultmesh-rs/tests/rudp_document_server.rs diff --git a/Cargo.toml b/Cargo.toml index 09a0ec3..d6d1640 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,6 @@ [workspace] members = [ "crates/sleipnir-daemon", - "crates/idunn-daemon", "crates/muninn-daemon", "crates/muninn-move-tracker", "crates/muninn-psmoveapi-tracker", @@ -11,7 +10,6 @@ members = [ resolver = "3" exclude = [ "vendor/cultcache-rs", - "vendor/cultmesh-rs", "vendor/cultnet-rs", ] diff --git a/crates/idunn-daemon/Cargo.toml b/crates/idunn-daemon/Cargo.toml deleted file mode 100644 index d8427e5..0000000 --- a/crates/idunn-daemon/Cargo.toml +++ /dev/null @@ -1,37 +0,0 @@ -[package] -name = "idunn-daemon" -version = "0.1.0" -edition.workspace = true -license.workspace = true -publish.workspace = true - -[[bin]] -name = "idunn" -path = "src/main.rs" - -[[bin]] -name = "idunn-provision" -path = "src/bin/idunn-provision.rs" - -[lib] -name = "idunn_daemon" -path = "src/lib.rs" - -[dependencies] -anyhow = "1" -cultmesh-rs = { path = "../../vendor/cultmesh-rs" } -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" } -cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } -rmp-serde = "1.3" -sha2 = "0.10" -chrono = "0.4" -serde = { version = "1", features = ["derive"] } -ed25519-dalek = "2.2" -toml = "0.8" -uuid = { version = "1", features = ["v4"] } - -[dev-dependencies] -tempfile = "3" - -[target.'cfg(unix)'.dependencies] -libc = "0.2" diff --git a/crates/idunn-daemon/src/bin/idunn-provision.rs b/crates/idunn-daemon/src/bin/idunn-provision.rs deleted file mode 100644 index cab36d3..0000000 --- a/crates/idunn-daemon/src/bin/idunn-provision.rs +++ /dev/null @@ -1,6 +0,0 @@ -fn main() { - if let Err(error) = idunn_daemon::provisioning::run(std::env::args().skip(1)) { - eprintln!("idunn-provision: {error:#}"); - std::process::exit(1); - } -} diff --git a/crates/idunn-daemon/src/control_plane.rs b/crates/idunn-daemon/src/control_plane.rs deleted file mode 100644 index 1f8361b..0000000 --- a/crates/idunn-daemon/src/control_plane.rs +++ /dev/null @@ -1,5923 +0,0 @@ -use std::collections::{BTreeMap, BTreeSet}; -use std::env; -use std::fs::{self, File, OpenOptions}; -use std::path::{Path, PathBuf}; -use std::thread; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use anyhow::{Context, Result, anyhow, bail, ensure}; -use cultcache_rs::{ - CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, -}; -use cultnet_rs::{ - AuthenticatedOdinRuntimeTopologyCorrelation, GameCultProviderHealthIdentity, - IDUNN_DEPLOYMENT_BRAKE_SCHEMA, IDUNN_LIFECYCLE_BRAKE_SCHEMA, IDUNN_PROCESS_WRITE_LEASE_SCHEMA, - IdunnDeploymentBrakeObservation, IdunnDeploymentBrakeOperatorIdentity, - IdunnDeploymentBrakeRecord, IdunnExpectedIncarnationRecord, IdunnLifecycleBrakeObservation, - IdunnLifecycleBrakeRecord, IdunnProcessWriteLeaseRecord, IdunnRuntimeActivationLaunch, - IdunnRuntimeActivationRecord, IdunnServiceIdentity, OdinTopologyAuthenticationContext, - OdinTopologyDisagreement, OdinTopologyIdentity, RuntimePresenceAuthenticationContext, - ServiceIdentityProfile, ServiceIdentitySigner, ServiceIdentityTrustAnchor, - authenticate_odin_runtime_topology_correlation, authenticate_runtime_presence_claim, - correlate_runtime_presence_claim, derive_service_identity_id, - evaluate_idunn_continuity_restart, evaluate_idunn_deployment_brake, open_service_identity_at, - verify_idunn_deployment_brake_authorization, verify_runtime_authority, -}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use uuid::Uuid; - -use crate::deployment::{DependencyKind, OperatorBinding, RouteBinding, capability_compatible}; -use crate::deployment_plan::{ - CompiledDeploymentPlan, DependencyProviderAuthority, SealedRelease, compile_deployment_plan, -}; -use crate::drivers::{ - CultCacheTopologyDriver, CultCacheWriteLeaseDriver, DockerRunnerDriver, FrozenSourceReceipt, - GitSourceDriver, InstalledReleaseObservation, NginxRouteDriver, ProcessIdentity, - RouteObservation, RoutePreflightReceipt, RunnerPort, SourcePort, - SystemdTransientWorkloadDriver, TopologyPort, WorkloadObservation, WorkloadPort, - WriteLeasePort, -}; - -const DEPLOYMENT_COMMAND_SCHEMA: &str = "idunn.deployment_command.v2"; -const DEPLOYMENT_TRANSACTION_SCHEMA: &str = "idunn.deployment_transaction.v2"; -const ADMITTED_GENERATION_SCHEMA: &str = "idunn.admitted_generation.v2"; -const DEFAULT_TOPOLOGY_MAXIMUM_AGE_MILLIS: u64 = 30_000; -const DEFAULT_TOPOLOGY_MAXIMUM_FUTURE_SKEW_MILLIS: u64 = 2_000; - -/// An immutable request. Execution state deliberately does not fit in this -/// record; status is derived from the transactions created for it. -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "idunn.deployment_command", - schema = "idunn.deployment_command.v2" -)] -struct DeploymentCommand { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - command_id: String, - #[cultcache(key = 2)] - kind: CommandKind, - #[cultcache(key = 3)] - selector: String, - #[cultcache(key = 4)] - requested_by: String, - #[cultcache(key = 5)] - requested_at_unix_millis: u64, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -enum CommandKind { - Deploy, - Continuity, -} - -impl DeploymentCommand { - fn validate(&self) -> Result<()> { - ensure!( - self.schema_version == DEPLOYMENT_COMMAND_SCHEMA, - "deployment command schema is unsupported" - ); - require_id(&self.command_id, "deployment command id")?; - require_selector(&self.selector)?; - require_value(&self.requested_by, "deployment requester")?; - ensure!( - self.requested_at_unix_millis > 0, - "deployment command has no request time" - ); - match self.kind { - CommandKind::Deploy => ensure!( - !self.command_id.starts_with("continuity-"), - "operator deployment uses the continuity command namespace" - ), - CommandKind::Continuity => ensure!( - self.command_id.starts_with("continuity-") - && !self.selector.starts_with("profile:"), - "continuity command identity or selector is invalid" - ), - } - Ok(()) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -#[repr(u8)] -enum DeploymentPhase { - Sealing, - Starting, - Warming, - Fencing, - Leasing, - AwaitingReady, - Routing, - Committing, - Complete, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct DeploymentAuthorization { - authorization_id: String, - brake_sha256: String, - canonical_brake_bytes: Vec, - authorized_at_unix_millis: u64, -} - -impl DeploymentAuthorization { - fn validate_shape(&self) -> Result<()> { - require_id(&self.authorization_id, "deployment authorization id")?; - ensure!( - !self.canonical_brake_bytes.is_empty() - && self.brake_sha256 == sha256_id(&self.canonical_brake_bytes) - && self.authorized_at_unix_millis > 0, - "deployment authorization receipt is incomplete" - ); - let record: IdunnDeploymentBrakeRecord = - rmp_serde::from_slice(&self.canonical_brake_bytes)?; - record.validate()?; - ensure!( - rmp_serde::to_vec(&record)? == self.canonical_brake_bytes - && record.authorization_id.as_deref() == Some(&self.authorization_id), - "deployment authorization receipt is noncanonical or mismatched" - ); - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct TopologyEvidence { - canonical_bytes: Vec, - canonical_sha256: String, - signer_identity_id: String, - publisher_sequence: u64, - admitted_at_unix_millis: u64, -} - -impl TopologyEvidence { - fn from_authenticated( - topology: &AuthenticatedOdinRuntimeTopologyCorrelation, - admitted_at_unix_millis: u64, - ) -> Result { - let record = topology.record(); - let evidence = Self { - canonical_bytes: topology.canonical_bytes().to_vec(), - canonical_sha256: sha256_id(topology.canonical_bytes()), - signer_identity_id: record.signer_identity_id.clone(), - publisher_sequence: record.publisher_sequence, - admitted_at_unix_millis, - }; - evidence.validate_shape()?; - Ok(evidence) - } - - fn validate_shape(&self) -> Result<()> { - ensure!( - !self.canonical_bytes.is_empty() - && self.canonical_sha256 == sha256_id(&self.canonical_bytes), - "topology evidence bytes or digest are invalid" - ); - require_id(&self.signer_identity_id, "Odin topology signer")?; - ensure!( - self.publisher_sequence > 0 && self.admitted_at_unix_millis > 0, - "topology evidence sequence or admission time is invalid" - ); - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct RuntimePresenceEvidence { - canonical_bytes: Vec, - canonical_sha256: String, - message_id: String, - challenged_at_unix_millis: u64, - admitted_at_unix_millis: u64, -} - -impl RuntimePresenceEvidence { - fn from_present( - present: &cultnet_rs::VerifiedRuntimePresence, - message_id: String, - challenged_at_unix_millis: u64, - admitted_at_unix_millis: u64, - ) -> Result { - let evidence = Self { - canonical_bytes: present.canonical_bytes().to_vec(), - canonical_sha256: present.signed_presence_sha256().to_owned(), - message_id, - challenged_at_unix_millis, - admitted_at_unix_millis, - }; - evidence.validate_shape()?; - Ok(evidence) - } - - fn validate_shape(&self) -> Result<()> { - ensure!( - !self.canonical_bytes.is_empty() - && self.canonical_sha256 == sha256_id(&self.canonical_bytes), - "runtime presence evidence bytes or digest are invalid" - ); - require_id(&self.message_id, "runtime presence challenge")?; - ensure!( - self.challenged_at_unix_millis > 0 - && self.admitted_at_unix_millis >= self.challenged_at_unix_millis, - "runtime presence evidence timeline is invalid" - ); - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "source", rename_all = "kebab-case", deny_unknown_fields)] -enum WarmingEvidence { - OdinTopology { evidence: TopologyEvidence }, - FirstOdinDirect { evidence: RuntimePresenceEvidence }, -} - -impl WarmingEvidence { - fn validate_shape(&self) -> Result<()> { - match self { - Self::OdinTopology { evidence } => evidence.validate_shape(), - Self::FirstOdinDirect { evidence } => evidence.validate_shape(), - } - } - - fn canonical_sha256(&self) -> &str { - match self { - Self::OdinTopology { evidence } => &evidence.canonical_sha256, - Self::FirstOdinDirect { evidence } => &evidence.canonical_sha256, - } - } -} - -/// Opaque capability minted only after the transaction CAS stores exact -/// Warming evidence. Adjacent drivers receive only the candidate identity and -/// signed-presence digest needed to bind the write lease; they cannot inspect -/// or construct semantic admission. -#[derive(Clone, Debug)] -pub struct SequenceAdmittedWarming { - transaction_id: String, - evidence: WarmingEvidence, - signed_presence_sha256: String, - runtime_instance_id: String, -} - -impl SequenceAdmittedWarming { - fn from_topology( - transaction_id: String, - evidence: TopologyEvidence, - authenticated: AuthenticatedOdinRuntimeTopologyCorrelation, - ) -> Result { - let record = authenticated.record(); - let signed_presence_sha256 = record - .signed_presence_sha256 - .clone() - .context("Warming topology has no signed presence")?; - let runtime_instance_id = record - .runtime_instance_id - .clone() - .context("Warming topology has no runtime instance")?; - Ok(Self { - transaction_id, - evidence: WarmingEvidence::OdinTopology { evidence }, - signed_presence_sha256, - runtime_instance_id, - }) - } - - fn from_first_odin_presence( - transaction_id: String, - evidence: RuntimePresenceEvidence, - present: cultnet_rs::VerifiedRuntimePresence, - ) -> Result { - ensure!( - present.canonical_bytes() == evidence.canonical_bytes - && present.signed_presence_sha256() == evidence.canonical_sha256, - "direct first-Odin Warming evidence differs from its authenticated presence" - ); - let runtime_instance_id = present.record().runtime_instance_id.clone(); - Ok(Self { - transaction_id, - signed_presence_sha256: evidence.canonical_sha256.clone(), - evidence: WarmingEvidence::FirstOdinDirect { evidence }, - runtime_instance_id, - }) - } - - #[cfg(test)] - pub(crate) fn for_test( - transaction_id: impl Into, - authenticated: AuthenticatedOdinRuntimeTopologyCorrelation, - admitted_at_unix_millis: u64, - ) -> Result { - let record = authenticated.record(); - ensure!( - record.present - && !record.ready - && record.observed_presence_state.as_deref() == Some("warming") - && record.observed_write_lease_sha256.is_none() - && record.disagreements.is_empty(), - "test receipt is not exact Warming evidence" - ); - let transaction_id = transaction_id.into(); - require_id(&transaction_id, "test transaction id")?; - let evidence = - TopologyEvidence::from_authenticated(&authenticated, admitted_at_unix_millis)?; - let signed_presence_sha256 = record - .signed_presence_sha256 - .clone() - .context("test Warming receipt has no signed presence")?; - let runtime_instance_id = record - .runtime_instance_id - .clone() - .context("test Warming receipt has no runtime instance")?; - let token = Self::from_topology(transaction_id, evidence, authenticated)?; - ensure!( - token.signed_presence_sha256 == signed_presence_sha256 - && token.runtime_instance_id == runtime_instance_id, - "test Warming token extraction changed" - ); - Ok(token) - } - - pub(crate) fn transaction_id(&self) -> &str { - &self.transaction_id - } - - pub(crate) fn evidence_sha256(&self) -> &str { - self.evidence.canonical_sha256() - } - - pub(crate) fn signed_presence_sha256(&self) -> &str { - &self.signed_presence_sha256 - } - - pub(crate) fn runtime_instance_id(&self) -> &str { - &self.runtime_instance_id - } -} - -/// Ready proof with the same construction boundary. Dependency planning and -/// promotion receive this token, never caller-supplied digest/sequence tuples. -#[derive(Clone, Debug)] -pub(crate) struct SequenceAdmittedReady { - transaction_id: String, - evidence: TopologyEvidence, - expected: IdunnExpectedIncarnationRecord, - authenticated: AuthenticatedOdinRuntimeTopologyCorrelation, -} - -impl SequenceAdmittedReady { - #[cfg(test)] - pub(crate) fn for_test( - expected: &IdunnExpectedIncarnationRecord, - authenticated: AuthenticatedOdinRuntimeTopologyCorrelation, - admitted_at_unix_millis: u64, - ) -> Result { - expected.validate()?; - let record = authenticated.record(); - ensure!( - record.expected_projection_sha256 == expected.canonical_sha256()? - && record.target == expected.target - && record.runtime_id == expected.runtime_id - && record.present - && record.ready - && record.observed_presence_state.as_deref() == Some("active") - && record.disagreements.is_empty(), - "test receipt is not exact Ready evidence" - ); - let evidence = - TopologyEvidence::from_authenticated(&authenticated, admitted_at_unix_millis)?; - Ok(Self { - transaction_id: "test-sequence-admission".into(), - evidence, - expected: expected.clone(), - authenticated, - }) - } - - pub(crate) fn authenticated(&self) -> &AuthenticatedOdinRuntimeTopologyCorrelation { - &self.authenticated - } - - pub(crate) fn expected(&self) -> &IdunnExpectedIncarnationRecord { - &self.expected - } - - pub(crate) fn transaction_id(&self) -> &str { - &self.transaction_id - } - - pub(crate) fn evidence_sha256(&self) -> &str { - &self.evidence.canonical_sha256 - } - - pub(crate) fn publisher_sequence(&self) -> u64 { - self.evidence.publisher_sequence - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "result", rename_all = "kebab-case", deny_unknown_fields)] -enum FencingEvidence { - SkippedStateless, - Revoked { - incumbent_lease_sha256: Option, - candidate_lease_path_verified_empty: bool, - }, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "result", rename_all = "kebab-case", deny_unknown_fields)] -enum LeasingEvidence { - SkippedStateless, - Prepared { - lease: IdunnProcessWriteLeaseRecord, - lease_sha256: String, - }, - Granted { - lease: IdunnProcessWriteLeaseRecord, - lease_sha256: String, - }, -} - -impl LeasingEvidence { - fn lease(&self) -> Option<&IdunnProcessWriteLeaseRecord> { - match self { - Self::SkippedStateless | Self::Prepared { .. } => None, - Self::Granted { lease, .. } => Some(lease), - } - } - - fn prepared_lease(&self) -> Option<(&IdunnProcessWriteLeaseRecord, &str)> { - match self { - Self::Prepared { - lease, - lease_sha256, - } => Some((lease, lease_sha256)), - Self::SkippedStateless | Self::Granted { .. } => None, - } - } - - fn lease_sha256(&self) -> Option<&str> { - match self { - Self::SkippedStateless | Self::Prepared { .. } => None, - Self::Granted { lease_sha256, .. } => Some(lease_sha256), - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "result", rename_all = "kebab-case", deny_unknown_fields)] -enum RoutingEvidence { - SkippedUnrouted, - Promoted { - observation: RouteObservation, - promoted_at_unix_millis: u64, - }, -} - -impl RoutingEvidence { - fn observation(&self) -> Option<&RouteObservation> { - match self { - Self::SkippedUnrouted => None, - Self::Promoted { observation, .. } => Some(observation), - } - } - - fn promoted_at_unix_millis(&self) -> Option { - match self { - Self::SkippedUnrouted => None, - Self::Promoted { - promoted_at_unix_millis, - .. - } => Some(*promoted_at_unix_millis), - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct IsolationEvidence { - candidate_uid: u32, - candidate_pid_namespace_id: u64, - candidate_mount_namespace_id: u64, - incumbent_uid: Option, - incumbent_pid_namespace_id: Option, - incumbent_mount_namespace_id: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "outcome", rename_all = "kebab-case", deny_unknown_fields)] -enum TransactionCompletion { - Admitted { generation_id: String }, - FailedBeforeFencing { error: String }, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -enum CleanupEvidence { - Pending, - Skipped, - Complete, -} - -impl CleanupEvidence { - fn is_complete(self) -> bool { - matches!(self, Self::Skipped | Self::Complete) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct PreFencingAbort { - error: String, - candidate_cleanup: CleanupEvidence, - topology_reconciliation: CleanupEvidence, - source_cleanup: CleanupEvidence, -} - -impl PreFencingAbort { - fn is_complete(&self) -> bool { - self.candidate_cleanup.is_complete() - && self.topology_reconciliation.is_complete() - && self.source_cleanup.is_complete() - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "result", rename_all = "kebab-case", deny_unknown_fields)] -enum IncumbentCleanupEvidence { - SkippedNoIncumbent, - Pending { - generation_id: String, - workload: WorkloadObservation, - }, - Complete { - generation_id: String, - }, -} - -impl IncumbentCleanupEvidence { - fn is_complete(&self) -> bool { - matches!(self, Self::SkippedNoIncumbent | Self::Complete { .. }) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -enum SourceCleanupEvidence { - SkippedContinuity, - Pending, - Complete, -} - -impl SourceCleanupEvidence { - fn is_complete(self) -> bool { - !matches!(self, Self::Pending) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct PostCommitCleanup { - incumbent: IncumbentCleanupEvidence, - source: SourceCleanupEvidence, -} - -impl PostCommitCleanup { - fn is_complete(&self) -> bool { - self.incumbent.is_complete() && self.source.is_complete() - } -} - -/// The sole owner of an in-flight deployment decision. Every actuator result -/// is durable here before a later phase is entered. -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "idunn.deployment_transaction", - schema = "idunn.deployment_transaction.v2" -)] -struct DeploymentTransaction { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - transaction_id: String, - #[cultcache(key = 2)] - command_id: String, - #[cultcache(key = 3)] - command_kind: CommandKind, - #[cultcache(key = 4)] - target: String, - #[cultcache(key = 5)] - ordinal: u32, - #[cultcache(key = 6)] - phase: DeploymentPhase, - #[cultcache(key = 7)] - created_at_unix_millis: u64, - #[cultcache(key = 8)] - updated_at_unix_millis: u64, - #[cultcache(key = 9)] - incumbent_generation_id: Option, - #[cultcache(key = 10)] - plan: Option, - #[cultcache(key = 11)] - frozen_source: Option, - #[cultcache(key = 12)] - sealed_release: Option, - #[cultcache(key = 13)] - installed_release: Option, - #[cultcache(key = 14)] - expected: Option, - #[cultcache(key = 15)] - expected_publication_sha256: Option, - #[cultcache(key = 16)] - deployment_authorization: Option, - #[cultcache(key = 17)] - lifecycle_authorized_at_unix_millis: Option, - #[cultcache(key = 18)] - activation: Option, - #[cultcache(key = 19)] - workload: Option, - #[cultcache(key = 20)] - activation_publication_sha256: Option, - #[cultcache(key = 21)] - latest_odin_observation: Option, - #[cultcache(key = 22)] - warming: Option, - #[cultcache(key = 23)] - route_preflight: Option, - #[cultcache(key = 24)] - isolation: Option, - #[cultcache(key = 25)] - fencing: Option, - #[cultcache(key = 26)] - leasing: Option, - #[cultcache(key = 27)] - ready: Option, - #[cultcache(key = 28)] - routing: Option, - #[cultcache(key = 29)] - odin_publisher_sequence_cursor: u64, - #[cultcache(key = 30)] - last_error: Option, - #[cultcache(key = 31)] - completion: Option, - #[cultcache(key = 32)] - pre_fencing_abort: Option, - #[cultcache(key = 33)] - post_commit_cleanup: Option, -} - -impl DeploymentTransaction { - fn new( - command: &DeploymentCommand, - target: String, - ordinal: u32, - incumbent: Option<&AdmittedGeneration>, - now: u64, - ) -> Result { - let transaction = Self { - schema_version: DEPLOYMENT_TRANSACTION_SCHEMA.into(), - transaction_id: format!("tx-{}", Uuid::new_v4()), - command_id: command.command_id.clone(), - command_kind: command.kind, - target, - ordinal, - phase: DeploymentPhase::Sealing, - created_at_unix_millis: now, - updated_at_unix_millis: now, - incumbent_generation_id: incumbent.map(|value| value.generation_id.clone()), - plan: None, - frozen_source: None, - sealed_release: None, - installed_release: None, - expected: None, - expected_publication_sha256: None, - deployment_authorization: None, - lifecycle_authorized_at_unix_millis: None, - activation: None, - workload: None, - activation_publication_sha256: None, - latest_odin_observation: None, - warming: None, - route_preflight: None, - isolation: None, - fencing: None, - leasing: None, - ready: None, - routing: None, - odin_publisher_sequence_cursor: incumbent - .map_or(0, |value| value.odin_publisher_sequence_cursor), - last_error: None, - completion: None, - pre_fencing_abort: None, - post_commit_cleanup: None, - }; - transaction.validate()?; - Ok(transaction) - } - - fn from_continuity( - command: &DeploymentCommand, - incumbent: &AdmittedGeneration, - now: u64, - ) -> Result { - let mut transaction = - Self::new(command, incumbent.target.clone(), 0, Some(incumbent), now)?; - transaction.plan = Some(incumbent.plan.clone()); - transaction.sealed_release = Some(incumbent.sealed_release.clone()); - transaction.installed_release = Some(incumbent.installed_release.clone()); - transaction.expected = Some(incumbent.expected.clone()); - transaction.validate()?; - Ok(transaction) - } - - fn rejected(command: &DeploymentCommand, error: anyhow::Error, now: u64) -> Result { - let mut transaction = Self::new(command, command.selector.clone(), 0, None, now)?; - let detail = truncate(&format!("{error:#}"), 2048); - transaction.phase = DeploymentPhase::Complete; - transaction.updated_at_unix_millis = now; - transaction.last_error = Some(detail.clone()); - transaction.pre_fencing_abort = Some(PreFencingAbort { - error: detail.clone(), - candidate_cleanup: CleanupEvidence::Skipped, - topology_reconciliation: CleanupEvidence::Skipped, - source_cleanup: CleanupEvidence::Skipped, - }); - transaction.completion = Some(TransactionCompletion::FailedBeforeFencing { error: detail }); - transaction.validate()?; - Ok(transaction) - } - - fn is_terminal(&self) -> bool { - if self.phase != DeploymentPhase::Complete { - return false; - } - match &self.completion { - Some(TransactionCompletion::FailedBeforeFencing { .. }) => self - .pre_fencing_abort - .as_ref() - .is_some_and(PreFencingAbort::is_complete), - Some(TransactionCompletion::Admitted { .. }) => self - .post_commit_cleanup - .as_ref() - .is_some_and(PostCommitCleanup::is_complete), - None => false, - } - } - - /// Complete transactions retain retryable cleanup work, but admission has - /// already transferred current-incarnation authority to AdmittedGeneration. - fn owns_target_authority(&self) -> bool { - self.phase != DeploymentPhase::Complete - } - - /// Admission has moved to the new generation at Complete, but an exact - /// draining incumbent still reserves its process and candidate endpoint. - /// No later mutation for the same target may overlap that cleanup. - fn blocks_new_target_mutation(&self) -> bool { - self.owns_target_authority() - || self - .post_commit_cleanup - .as_ref() - .is_some_and(|cleanup| !cleanup.is_complete()) - } - - fn validate(&self) -> Result<()> { - ensure!( - self.schema_version == DEPLOYMENT_TRANSACTION_SCHEMA, - "deployment transaction schema is unsupported" - ); - require_id(&self.transaction_id, "deployment transaction id")?; - require_id(&self.command_id, "transaction command id")?; - require_id(&self.target, "transaction target")?; - ensure!( - self.created_at_unix_millis > 0 - && self.updated_at_unix_millis >= self.created_at_unix_millis, - "deployment transaction timestamps are invalid" - ); - if let Some(generation) = &self.incumbent_generation_id { - require_id(generation, "incumbent generation id")?; - } - if let Some(plan) = &self.plan { - plan.validate()?; - ensure!( - plan.parsed_inputs()?.1.target == self.target, - "transaction plan belongs to another target" - ); - } - if let (Some(plan), Some(frozen)) = (&self.plan, &self.frozen_source) { - frozen.validate_against(plan)?; - } - if let (Some(plan), Some(release)) = (&self.plan, &self.sealed_release) { - release.validate_against(plan)?; - } - if let Some(expected) = &self.expected { - expected.validate()?; - ensure!(expected.target == self.target, "Expected target differs"); - if let Some(plan) = &self.plan { - ensure!(expected.plan_id == plan.plan_id, "Expected plan differs"); - } - if let Some(release) = &self.sealed_release { - ensure!( - expected.sealed_release_id == release.sealed_release_id, - "Expected release differs" - ); - } - if let Some(digest) = &self.expected_publication_sha256 { - ensure!( - digest == &expected.canonical_sha256()?, - "Expected publication receipt differs" - ); - } - } - if let (Some(expected), Some(activation)) = (&self.expected, &self.activation) { - activation.validate()?; - ensure!( - activation.expected_projection_sha256 == expected.canonical_sha256()?, - "activation belongs to another Expected projection" - ); - if let Some(workload) = &self.workload { - ensure!( - workload.runtime_instance_id == activation.runtime_instance_id, - "workload belongs to another activation" - ); - } - if let Some(digest) = &self.activation_publication_sha256 { - ensure!( - digest == &activation.canonical_sha256()?, - "activation publication receipt differs" - ); - } - } - ensure!( - self.workload.is_none() || self.activation.is_some(), - "workload observation exists without its prepared activation" - ); - for evidence in [&self.latest_odin_observation, &self.ready] - .into_iter() - .flatten() - { - evidence.validate_shape()?; - ensure!( - evidence.publisher_sequence <= self.odin_publisher_sequence_cursor, - "topology evidence exceeds the transaction replay cursor" - ); - } - if let Some(warming) = &self.warming { - warming.validate_shape()?; - match warming { - WarmingEvidence::OdinTopology { evidence } => ensure!( - evidence.publisher_sequence <= self.odin_publisher_sequence_cursor, - "Warming topology evidence exceeds the transaction replay cursor" - ), - WarmingEvidence::FirstOdinDirect { .. } => ensure!( - self.target == "odin" && self.incumbent_generation_id.is_none(), - "direct Warming evidence is reserved for first Odin bootstrap" - ), - } - } - if let Some(leasing) = &self.leasing { - if let Some(expected) = &self.expected { - ensure!( - matches!( - (expected.write_lease_required, leasing), - (true, LeasingEvidence::Prepared { .. }) - | (true, LeasingEvidence::Granted { .. }) - | (false, LeasingEvidence::SkippedStateless) - ), - "lease evidence differs from the Expected state contract" - ); - } - let lease_and_sha256 = match leasing { - LeasingEvidence::SkippedStateless => None, - LeasingEvidence::Prepared { - lease, - lease_sha256, - } - | LeasingEvidence::Granted { - lease, - lease_sha256, - } => Some((lease, lease_sha256)), - }; - if let Some((lease, lease_sha256)) = lease_and_sha256 { - lease.validate()?; - ensure!( - lease.canonical_sha256()? == *lease_sha256, - "lease evidence digest differs" - ); - } - } - if let (Some(expected), Some(fencing)) = (&self.expected, &self.fencing) { - match fencing { - FencingEvidence::SkippedStateless => ensure!( - !expected.write_lease_required, - "stateful candidate claims stateless fencing" - ), - FencingEvidence::Revoked { - candidate_lease_path_verified_empty, - .. - } => ensure!( - *candidate_lease_path_verified_empty == expected.write_lease_required, - "candidate lease-path fencing differs from Expected" - ), - } - } - if let Some(error) = &self.last_error { - require_detail(error, "transaction error")?; - } - if let Some(authorization) = &self.deployment_authorization { - authorization.validate_shape()?; - } - if let Some(abort) = &self.pre_fencing_abort { - require_detail(&abort.error, "pre-fencing abort error")?; - ensure!( - self.post_commit_cleanup.is_none(), - "aborted transaction also carries post-commit cleanup" - ); - ensure!( - matches!( - ( - self.workload.is_some() || self.activation.is_some(), - abort.candidate_cleanup - ), - (true, CleanupEvidence::Pending | CleanupEvidence::Complete) - | (false, CleanupEvidence::Skipped) - ), - "abort candidate cleanup differs from its prepared activation" - ); - let topology_cleanup_required = self.command_kind == CommandKind::Deploy - && self.expected_publication_sha256.is_some(); - ensure!( - matches!( - (topology_cleanup_required, abort.topology_reconciliation), - (true, CleanupEvidence::Pending | CleanupEvidence::Complete) - | (false, CleanupEvidence::Skipped) - ), - "abort topology cleanup differs from published deployment Expected" - ); - ensure!( - matches!( - (self.command_kind, abort.source_cleanup), - ( - CommandKind::Deploy, - CleanupEvidence::Pending | CleanupEvidence::Complete - ) | (CommandKind::Continuity, CleanupEvidence::Skipped) - ) || (self.command_kind == CommandKind::Deploy - && abort.source_cleanup == CleanupEvidence::Skipped - && self.plan.is_none() - && self.frozen_source.is_none() - && self.expected.is_none() - && self.phase == DeploymentPhase::Complete), - "abort source cleanup differs from command work" - ); - ensure!( - self.phase < DeploymentPhase::Fencing || self.phase == DeploymentPhase::Complete, - "pre-fencing abort crossed the fencing boundary" - ); - } - - let failed = matches!( - self.completion, - Some(TransactionCompletion::FailedBeforeFencing { .. }) - ); - if failed { - ensure!( - self.phase == DeploymentPhase::Complete, - "terminal failure is not Complete" - ); - let abort = required(&self.pre_fencing_abort, "terminal abort evidence")?; - let TransactionCompletion::FailedBeforeFencing { error } = - self.completion.as_ref().unwrap() - else { - unreachable!() - }; - ensure!( - abort.is_complete() && abort.error == *error, - "terminal failure lacks complete matching abort evidence" - ); - } else { - ensure!( - !matches!( - self.completion, - Some(TransactionCompletion::FailedBeforeFencing { .. }) - ), - "non-failure branch carries failure completion" - ); - if self.phase >= DeploymentPhase::Starting { - ensure!( - self.plan.is_some() - && self.sealed_release.is_some() - && self.installed_release.is_some() - && self.expected.is_some() - && self.expected_publication_sha256.is_some(), - "Starting transaction lacks sealed release evidence" - ); - match self.command_kind { - CommandKind::Deploy => ensure!( - self.frozen_source.is_some() && self.deployment_authorization.is_some(), - "deployment entered Starting without frozen source and brake consumption" - ), - CommandKind::Continuity => ensure!( - self.lifecycle_authorized_at_unix_millis.is_some() - && self.deployment_authorization.is_none(), - "continuity entered Starting without its lifecycle gate" - ), - } - } - if self.phase >= DeploymentPhase::Warming { - ensure!( - self.activation.is_some() - && self.workload.is_some() - && self.activation_publication_sha256.is_some(), - "Warming transaction lacks observed activation" - ); - } - if self.phase >= DeploymentPhase::Fencing { - ensure!( - self.warming.is_some() && self.isolation.is_some(), - "Fencing transaction lacks warming or isolation evidence" - ); - ensure!( - self.expected - .as_ref() - .and_then(|expected| expected.route.as_ref()) - .is_some() - == self.route_preflight.is_some(), - "route preflight does not match routed Expected" - ); - if let Some(preflight) = &self.route_preflight { - preflight.validate()?; - } - } - if self.phase >= DeploymentPhase::Leasing { - ensure!(self.fencing.is_some(), "Leasing lacks fencing evidence"); - } - if self.phase >= DeploymentPhase::AwaitingReady { - ensure!( - matches!( - self.leasing.as_ref(), - Some(LeasingEvidence::SkippedStateless) - | Some(LeasingEvidence::Granted { .. }) - ), - "AwaitingReady lacks finalized lease evidence" - ); - } - if self.phase >= DeploymentPhase::Routing { - ensure!(self.ready.is_some(), "Routing lacks Ready evidence"); - } - if self.phase >= DeploymentPhase::Committing { - ensure!(self.routing.is_some(), "Committing lacks routing evidence"); - } - if let Some(RoutingEvidence::Promoted { - observation, - promoted_at_unix_millis, - }) = &self.routing - { - observation.validate()?; - ensure!( - *promoted_at_unix_millis > 0 - && *promoted_at_unix_millis <= self.updated_at_unix_millis, - "route promotion time is outside the durable transaction timeline" - ); - } - if self.phase == DeploymentPhase::Complete { - ensure!( - matches!( - self.completion, - Some(TransactionCompletion::Admitted { .. }) - ), - "successful Complete transaction lacks admission receipt" - ); - ensure!( - self.pre_fencing_abort.is_none() && self.post_commit_cleanup.is_some(), - "admitted transaction lacks exclusive post-commit cleanup evidence" - ); - let TransactionCompletion::Admitted { generation_id } = - self.completion.as_ref().unwrap() - else { - unreachable!() - }; - ensure!( - generation_id == &format!("generation-{}", self.transaction_id), - "admission completion names another transaction generation" - ); - } else { - ensure!( - self.completion.is_none() && self.post_commit_cleanup.is_none(), - "non-Complete transaction has completion or post-commit state" - ); - } - } - if let Some(cleanup) = &self.post_commit_cleanup { - ensure!( - self.phase == DeploymentPhase::Complete - && matches!( - self.completion, - Some(TransactionCompletion::Admitted { .. }) - ), - "post-commit cleanup exists without an admitted Complete transaction" - ); - match (&self.incumbent_generation_id, &cleanup.incumbent) { - (None, IncumbentCleanupEvidence::SkippedNoIncumbent) => {} - ( - Some(expected), - IncumbentCleanupEvidence::Pending { generation_id, .. } - | IncumbentCleanupEvidence::Complete { generation_id }, - ) if expected == generation_id => {} - _ => bail!("post-commit incumbent cleanup names another generation"), - } - ensure!( - matches!( - (self.command_kind, cleanup.source), - (CommandKind::Deploy, SourceCleanupEvidence::Pending) - | (CommandKind::Deploy, SourceCleanupEvidence::Complete) - | ( - CommandKind::Continuity, - SourceCleanupEvidence::SkippedContinuity - ) - ), - "post-commit source cleanup differs from command kind" - ); - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct AdmittedOdinAuthority { - signer_identity_id: String, - signer_public_key: Vec, -} - -impl AdmittedOdinAuthority { - fn from_anchor(anchor: &ServiceIdentityTrustAnchor) -> Result { - ensure!( - derive_service_identity_id::(&anchor.public_key)? - == anchor.identity_id, - "Odin topology anchor identity differs from its key" - ); - Ok(Self { - signer_identity_id: anchor.identity_id.clone(), - signer_public_key: anchor.public_key.clone(), - }) - } - - fn validate(&self) -> Result<()> { - require_id(&self.signer_identity_id, "admitted Odin signer")?; - ensure!( - derive_service_identity_id::(&self.signer_public_key)? - == self.signer_identity_id, - "admitted Odin signer identity differs from its key" - ); - Ok(()) - } -} - -/// The only current-incarnation owner. Unit state, route state, topology -/// projections, and CLI output are observations of this record, never peers. -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "idunn.admitted_generation", - schema = "idunn.admitted_generation.v2" -)] -struct AdmittedGeneration { - #[cultcache(key = 0)] - schema_version: String, - #[cultcache(key = 1)] - target: String, - #[cultcache(key = 2)] - generation_id: String, - #[cultcache(key = 3)] - command_id: String, - #[cultcache(key = 4)] - transaction_id: String, - #[cultcache(key = 5)] - admitted_at_unix_millis: u64, - #[cultcache(key = 6)] - plan: CompiledDeploymentPlan, - #[cultcache(key = 7)] - sealed_release: SealedRelease, - #[cultcache(key = 8)] - installed_release: InstalledReleaseObservation, - #[cultcache(key = 9)] - expected: IdunnExpectedIncarnationRecord, - #[cultcache(key = 10)] - activation: IdunnRuntimeActivationRecord, - #[cultcache(key = 11)] - workload: WorkloadObservation, - #[cultcache(key = 12)] - leasing: LeasingEvidence, - #[cultcache(key = 13)] - ready: TopologyEvidence, - #[cultcache(key = 14)] - latest_odin_observation: TopologyEvidence, - #[cultcache(key = 15)] - routing: RoutingEvidence, - #[cultcache(key = 16)] - odin_authority: AdmittedOdinAuthority, - #[cultcache(key = 17)] - odin_publisher_sequence_cursor: u64, - #[cultcache(key = 18)] - route_repair_started_at_unix_millis: Option, -} - -impl AdmittedGeneration { - fn from_transaction( - transaction: &DeploymentTransaction, - odin_authority: AdmittedOdinAuthority, - now: u64, - ) -> Result { - ensure!( - transaction.phase == DeploymentPhase::Committing, - "only Committing can create an admitted generation" - ); - let generation = Self { - schema_version: ADMITTED_GENERATION_SCHEMA.into(), - target: transaction.target.clone(), - generation_id: format!("generation-{}", transaction.transaction_id), - command_id: transaction.command_id.clone(), - transaction_id: transaction.transaction_id.clone(), - admitted_at_unix_millis: now, - plan: required(&transaction.plan, "transaction plan")?.clone(), - sealed_release: required(&transaction.sealed_release, "sealed release")?.clone(), - installed_release: required(&transaction.installed_release, "installed release")? - .clone(), - expected: required(&transaction.expected, "Expected projection")?.clone(), - activation: required(&transaction.activation, "activation")?.clone(), - workload: required(&transaction.workload, "workload")?.clone(), - leasing: required(&transaction.leasing, "lease disposition")?.clone(), - ready: required(&transaction.ready, "Ready receipt")?.clone(), - latest_odin_observation: required( - &transaction.latest_odin_observation, - "latest Odin receipt", - )? - .clone(), - routing: required(&transaction.routing, "route disposition")?.clone(), - odin_authority, - odin_publisher_sequence_cursor: transaction.odin_publisher_sequence_cursor, - route_repair_started_at_unix_millis: None, - }; - generation.validate()?; - Ok(generation) - } - - fn validate(&self) -> Result<()> { - ensure!( - self.schema_version == ADMITTED_GENERATION_SCHEMA, - "admitted generation schema is unsupported" - ); - require_id(&self.target, "admitted target")?; - require_id(&self.generation_id, "admitted generation id")?; - require_id(&self.command_id, "admitted command id")?; - require_id(&self.transaction_id, "admitted transaction id")?; - ensure!(self.admitted_at_unix_millis > 0, "admission has no time"); - self.plan.validate()?; - self.sealed_release.validate_against(&self.plan)?; - self.expected.validate()?; - self.activation.validate()?; - self.ready.validate_shape()?; - self.latest_odin_observation.validate_shape()?; - self.odin_authority.validate()?; - ensure!( - self.target == self.expected.target - && self.expected.plan_id == self.plan.plan_id - && self.expected.sealed_release_id == self.sealed_release.sealed_release_id - && self.activation.expected_projection_sha256 - == self.expected.canonical_sha256()? - && self.activation.runtime_instance_id == self.workload.runtime_instance_id - && self.ready.publisher_sequence <= self.odin_publisher_sequence_cursor - && self.latest_odin_observation.publisher_sequence - == self.odin_publisher_sequence_cursor, - "admitted generation evidence does not describe one incarnation" - ); - ensure!( - self.expected.write_lease_required == self.leasing.lease().is_some(), - "admitted write-lease disposition differs from Expected" - ); - ensure!( - self.expected.route.is_some() == self.routing.observation().is_some(), - "admitted route disposition differs from Expected" - ); - if let Some(route) = self.routing.observation() { - route.validate()?; - ensure!( - route.runtime_instance_id == self.activation.runtime_instance_id, - "admitted route observation belongs to another runtime instance" - ); - } - if let Some(started_at) = self.route_repair_started_at_unix_millis { - ensure!(started_at > 0, "admitted route repair has no start time"); - ensure!( - matches!(&self.routing, RoutingEvidence::Promoted { .. }), - "only a promoted routed generation can own route repair intent" - ); - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct RuntimeOptions { - state_store: PathBuf, - bindings_dir: PathBuf, - source_root: PathBuf, - staging_root: PathBuf, - topology_store: PathBuf, - odin_correlation_store: PathBuf, - odin_trust_anchor: PathBuf, - idunn_identity_store: PathBuf, - deployment_brake_operator_anchor: PathBuf, - source_identity: Option, - topology_maximum_age_millis: u64, - topology_maximum_future_skew_millis: u64, - poll_millis: u64, -} - -impl Default for RuntimeOptions { - fn default() -> Self { - Self { - state_store: PathBuf::from("/var/lib/gamecult/idunn/control.cc"), - bindings_dir: PathBuf::from("/etc/gamecult/idunn/bindings"), - source_root: PathBuf::from("/var/lib/gamecult/idunn/sources"), - staging_root: PathBuf::from("/var/lib/gamecult/idunn/staging"), - topology_store: PathBuf::from("/var/lib/gamecult/idunn/topology.cc"), - odin_correlation_store: PathBuf::from( - "/var/lib/gamecult/odin/idunn-runtime-topology.cc", - ), - odin_trust_anchor: PathBuf::from("/etc/gamecult/idunn/odin-topology-anchor.cc"), - idunn_identity_store: PathBuf::from( - "/var/lib/gamecult/idunn/idunn-service-identity.cc", - ), - deployment_brake_operator_anchor: PathBuf::from( - "/etc/gamecult/idunn/deployment-brake-operator-anchor.cc", - ), - source_identity: None, - topology_maximum_age_millis: DEFAULT_TOPOLOGY_MAXIMUM_AGE_MILLIS, - topology_maximum_future_skew_millis: DEFAULT_TOPOLOGY_MAXIMUM_FUTURE_SKEW_MILLIS, - poll_millis: 500, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -enum Command { - Serve(RuntimeOptions), - Up { - selector: String, - requested_by: String, - state_store: PathBuf, - wait: bool, - timeout_seconds: u64, - }, - Status { - state_store: PathBuf, - command_id: Option, - }, -} - -pub fn run(args: impl Iterator) -> Result<()> { - match parse(args)? { - Command::Serve(options) => serve(options), - Command::Up { - selector, - requested_by, - state_store, - wait, - timeout_seconds, - } => submit( - &state_store, - &selector, - &requested_by, - wait, - timeout_seconds, - ), - Command::Status { - state_store, - command_id, - } => status(&state_store, command_id.as_deref()), - } -} - -fn parse(args: impl Iterator) -> Result { - let mut args = args.peekable(); - let command = args.next().ok_or_else(|| anyhow!(usage()))?; - match command.as_str() { - "serve" => parse_serve(args), - "up" => parse_up(args), - "status" => parse_status(args), - "--help" | "-h" | "help" => bail!(usage()), - _ => bail!("unknown Idunn command {command:?}\n\n{}", usage()), - } -} - -fn parse_serve(mut args: impl Iterator) -> Result { - let mut options = RuntimeOptions::default(); - let mut source_uid = None; - let mut source_gid = None; - while let Some(argument) = args.next() { - match argument.as_str() { - "--state-store" => options.state_store = path_value(&mut args, &argument)?, - "--bindings-dir" => options.bindings_dir = path_value(&mut args, &argument)?, - "--source-root" => options.source_root = path_value(&mut args, &argument)?, - "--staging-root" => options.staging_root = path_value(&mut args, &argument)?, - "--topology-store" => options.topology_store = path_value(&mut args, &argument)?, - "--odin-correlation-store" => { - options.odin_correlation_store = path_value(&mut args, &argument)? - } - "--odin-trust-anchor" => options.odin_trust_anchor = path_value(&mut args, &argument)?, - "--idunn-identity-store" => { - options.idunn_identity_store = path_value(&mut args, &argument)? - } - "--deployment-brake-operator-anchor" => { - options.deployment_brake_operator_anchor = path_value(&mut args, &argument)? - } - "--topology-maximum-age-millis" => { - options.topology_maximum_age_millis = u64_value(&mut args, &argument)? - } - "--topology-maximum-future-skew-millis" => { - options.topology_maximum_future_skew_millis = u64_value(&mut args, &argument)? - } - "--source-uid" => source_uid = Some(u32_value(&mut args, &argument)?), - "--source-gid" => source_gid = Some(u32_value(&mut args, &argument)?), - "--poll-millis" => options.poll_millis = u64_value(&mut args, &argument)?, - "--help" | "-h" => bail!(usage()), - _ => bail!("unknown Idunn serve option {argument:?}"), - } - } - ensure!( - options.poll_millis > 0 && options.topology_maximum_age_millis > 0, - "poll and topology maximum age must be positive" - ); - options.source_identity = match (source_uid, source_gid) { - (Some(uid), Some(gid)) => { - ensure!( - uid > 0 && gid > 0, - "source UID and GID must be unprivileged" - ); - Some(ProcessIdentity { uid, gid }) - } - (None, None) => None, - _ => bail!("--source-uid and --source-gid must be supplied together"), - }; - Ok(Command::Serve(options)) -} - -fn parse_up(mut args: impl Iterator) -> Result { - let selector = args - .next() - .ok_or_else(|| anyhow!("idunn up requires a service or profile selector"))?; - require_selector(&selector)?; - let mut state_store = RuntimeOptions::default().state_store; - let mut requested_by = env::var("SUDO_USER") - .or_else(|_| env::var("USER")) - .or_else(|_| env::var("USERNAME")) - .unwrap_or_else(|_| "operator".into()); - let mut wait = true; - let mut timeout_seconds = 1800; - while let Some(argument) = args.next() { - match argument.as_str() { - "--state-store" => state_store = path_value(&mut args, &argument)?, - "--requested-by" => requested_by = string_value(&mut args, &argument)?, - "--no-wait" => wait = false, - "--timeout-seconds" => timeout_seconds = u64_value(&mut args, &argument)?, - "--help" | "-h" => bail!(usage()), - _ => bail!("unknown Idunn up option {argument:?}"), - } - } - ensure!(timeout_seconds > 0, "--timeout-seconds must be positive"); - require_value(&requested_by, "deployment requester")?; - Ok(Command::Up { - selector, - requested_by, - state_store, - wait, - timeout_seconds, - }) -} - -fn parse_status(mut args: impl Iterator) -> Result { - let mut state_store = RuntimeOptions::default().state_store; - let mut command_id = None; - while let Some(argument) = args.next() { - match argument.as_str() { - "--state-store" => state_store = path_value(&mut args, &argument)?, - "--command" => command_id = Some(string_value(&mut args, &argument)?), - "--help" | "-h" => bail!(usage()), - _ => bail!("unknown Idunn status option {argument:?}"), - } - } - Ok(Command::Status { - state_store, - command_id, - }) -} - -#[derive(Clone)] -struct Stored { - envelope: CultCacheEnvelope, - value: T, -} - -#[derive(Default)] -struct ControlSnapshot { - commands: Vec>, - transactions: Vec>, - admitted: Vec>, -} - -impl ControlSnapshot { - fn read(path: &Path) -> Result { - if !path.exists() { - return Ok(Self::default()); - } - let mut snapshot = Self::default(); - for envelope in SingleFileMessagePackBackingStore::new(path) - .pull_all_read_only_snapshot() - .context("reading Idunn control snapshot")? - { - match envelope.r#type.as_str() { - DeploymentCommand::TYPE => { - ensure!( - envelope.schema_id.as_deref() == Some(DEPLOYMENT_COMMAND_SCHEMA), - "Idunn control store contains an unsupported command" - ); - let value: DeploymentCommand = decode_record(&envelope)?; - value.validate()?; - ensure!( - envelope.key == value.command_id, - "deployment command key differs from its identity" - ); - snapshot.commands.push(Stored { envelope, value }); - } - DeploymentTransaction::TYPE => { - ensure!( - envelope.schema_id.as_deref() == Some(DEPLOYMENT_TRANSACTION_SCHEMA), - "Idunn control store contains an unsupported transaction" - ); - let value: DeploymentTransaction = decode_record(&envelope)?; - value.validate()?; - ensure!( - envelope.key == value.transaction_id, - "deployment transaction key differs from its identity" - ); - snapshot.transactions.push(Stored { envelope, value }); - } - AdmittedGeneration::TYPE => { - ensure!( - envelope.schema_id.as_deref() == Some(ADMITTED_GENERATION_SCHEMA), - "Idunn control store contains an unsupported admitted generation" - ); - let value: AdmittedGeneration = decode_record(&envelope)?; - value.validate()?; - ensure!( - envelope.key == value.target, - "admitted generation key is not its target" - ); - snapshot.admitted.push(Stored { envelope, value }); - } - _ => bail!("Idunn control store contains a foreign document"), - } - } - snapshot.validate_relations()?; - Ok(snapshot) - } - - fn validate_relations(&self) -> Result<()> { - let command_ids = self - .commands - .iter() - .map(|stored| stored.value.command_id.as_str()) - .collect::>(); - ensure!( - command_ids.len() == self.commands.len(), - "Idunn control store contains duplicate commands" - ); - let transaction_ids = self - .transactions - .iter() - .map(|stored| stored.value.transaction_id.as_str()) - .collect::>(); - ensure!( - transaction_ids.len() == self.transactions.len(), - "Idunn control store contains duplicate transactions" - ); - let admitted_targets = self - .admitted - .iter() - .map(|stored| stored.value.target.as_str()) - .collect::>(); - ensure!( - admitted_targets.len() == self.admitted.len(), - "Idunn control store contains duplicate current generations" - ); - for transaction in &self.transactions { - let command = self - .commands - .iter() - .find(|candidate| candidate.value.command_id == transaction.value.command_id) - .context("deployment transaction has no immutable command")?; - ensure!( - command.value.kind == transaction.value.command_kind, - "transaction kind differs from its immutable command" - ); - } - let mut live_targets = BTreeSet::new(); - for transaction in self - .transactions - .iter() - .filter(|stored| stored.value.owns_target_authority()) - { - ensure!( - live_targets.insert(transaction.value.target.as_str()), - "multiple transactions claim current-incarnation authority for one target" - ); - if let Some(fencing) = transaction - .value - .fencing - .as_ref() - .filter(|_| transaction.value.phase < DeploymentPhase::Complete) - { - let incumbent = self.admitted_for(&transaction.value.target); - let incumbent_matches = - match (&transaction.value.incumbent_generation_id, incumbent) { - (None, None) => true, - (Some(expected), Some(current)) => current.value.generation_id == *expected, - _ => false, - }; - ensure!( - incumbent_matches, - "fenced transaction incumbent differs from current admission" - ); - let incumbent_lease_sha256 = incumbent - .and_then(|stored| stored.value.leasing.lease()) - .map(IdunnProcessWriteLeaseRecord::canonical_sha256) - .transpose()?; - match fencing { - FencingEvidence::SkippedStateless => ensure!( - incumbent_lease_sha256.is_none(), - "stateless fencing omitted the admitted incumbent lease" - ), - FencingEvidence::Revoked { - incumbent_lease_sha256: recorded, - .. - } => { - ensure!( - recorded == &incumbent_lease_sha256, - "fencing evidence names another incumbent lease" - ); - ensure!( - incumbent_lease_sha256.is_some() - || transaction - .value - .expected - .as_ref() - .is_some_and(|expected| expected.write_lease_required), - "stateless transaction did not use its explicit fencing skip" - ); - } - } - } - } - let mut authorizations = BTreeSet::new(); - for authorization in self - .transactions - .iter() - .filter_map(|stored| stored.value.deployment_authorization.as_ref()) - { - ensure!( - authorizations.insert(authorization.authorization_id.as_str()), - "deployment authorization was consumed more than once" - ); - } - Ok(()) - } - - fn admitted_for(&self, target: &str) -> Option<&Stored> { - self.admitted - .iter() - .find(|stored| stored.value.target == target) - } - - fn transaction_for_command(&self, command_id: &str) -> Vec<&DeploymentTransaction> { - let mut values = self - .transactions - .iter() - .filter(|stored| stored.value.command_id == command_id) - .map(|stored| &stored.value) - .collect::>(); - values.sort_by_key(|value| value.ordinal); - values - } - - fn has_earlier_authority_sibling(&self, transaction: &DeploymentTransaction) -> bool { - self.transactions.iter().any(|stored| { - stored.value.owns_target_authority() - && stored.value.command_id == transaction.command_id - && stored.value.ordinal < transaction.ordinal - }) - } - - fn max_odin_sequence(&self, target: &str, signer_identity_id: &str) -> u64 { - let transaction_max = self - .transactions - .iter() - .filter_map(|stored| { - stored - .value - .latest_odin_observation - .as_ref() - .filter(|evidence| { - stored.value.target == target - && evidence.signer_identity_id == signer_identity_id - }) - .map(|evidence| evidence.publisher_sequence) - }) - .max() - .unwrap_or(0); - let admitted_max = self - .admitted - .iter() - .filter(|stored| { - stored.value.target == target - && stored.value.odin_authority.signer_identity_id == signer_identity_id - }) - .map(|stored| stored.value.odin_publisher_sequence_cursor) - .max() - .unwrap_or(0); - transaction_max.max(admitted_max) - } -} - -fn decode_record(envelope: &CultCacheEnvelope) -> Result -where - T: for<'de> Deserialize<'de> + Serialize, -{ - let value: T = rmp_serde::from_slice(&envelope.payload)?; - ensure!( - rmp_serde::to_vec(&value)? == envelope.payload, - "Idunn control store contains a noncanonical record" - ); - Ok(value) -} - -fn command_envelope(value: &DeploymentCommand, now: u64) -> Result { - value.validate()?; - typed_envelope( - &value.command_id, - DeploymentCommand::TYPE, - DEPLOYMENT_COMMAND_SCHEMA, - value, - now, - ) -} - -fn transaction_envelope(value: &DeploymentTransaction, now: u64) -> Result { - value.validate()?; - typed_envelope( - &value.transaction_id, - DeploymentTransaction::TYPE, - DEPLOYMENT_TRANSACTION_SCHEMA, - value, - now, - ) -} - -fn admitted_envelope(value: &AdmittedGeneration, now: u64) -> Result { - value.validate()?; - typed_envelope( - &value.target, - AdmittedGeneration::TYPE, - ADMITTED_GENERATION_SCHEMA, - value, - now, - ) -} - -fn typed_envelope( - key: &str, - record_type: &str, - schema: &str, - value: &T, - now: u64, -) -> Result { - Ok(CultCacheEnvelope { - key: key.into(), - r#type: record_type.into(), - payload: rmp_serde::to_vec(value)?, - stored_at: rfc3339_millis(now)?, - schema_id: Some(schema.into()), - }) -} - -fn replace_transaction( - store_path: &Path, - current: &Stored, - next: &DeploymentTransaction, -) -> Result<()> { - next.validate()?; - ensure!( - current.value.transaction_id == next.transaction_id, - "transaction replacement changes identity" - ); - ensure!( - SingleFileMessagePackBackingStore::new(store_path).compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: DeploymentTransaction::TYPE.into(), - key: current.value.transaction_id.clone(), - current: Some(current.envelope.clone()), - }], - &[transaction_envelope(next, next.updated_at_unix_millis)?], - )?, - "deployment transaction changed before its compare-exchange" - ); - Ok(()) -} - -#[derive(Clone)] -struct LoadedBinding { - binding: OperatorBinding, - bytes: Vec, -} - -fn load_bindings(directory: &Path) -> Result> { - let mut paths = fs::read_dir(directory) - .with_context(|| format!("reading Idunn binding directory {}", directory.display()))? - .map(|entry| entry.map(|entry| entry.path())) - .collect::>>()?; - paths.retain(|path| path.extension() == Some(std::ffi::OsStr::new("toml"))); - paths.sort(); - let mut bindings = BTreeMap::new(); - for path in paths { - let bytes = fs::read(&path) - .with_context(|| format!("reading operator binding {}", path.display()))?; - let text = std::str::from_utf8(&bytes) - .with_context(|| format!("operator binding {} is not UTF-8", path.display()))?; - let binding = OperatorBinding::parse(text) - .with_context(|| format!("validating operator binding {}", path.display()))?; - let target = binding.target.clone(); - ensure!( - bindings - .insert(target.clone(), LoadedBinding { binding, bytes }) - .is_none(), - "operator binding target {target} is duplicated" - ); - } - ensure!(!bindings.is_empty(), "Idunn binding directory is empty"); - validate_route_bindings(&bindings)?; - Ok(bindings) -} - -fn validate_route_bindings(bindings: &BTreeMap) -> Result<()> { - let routes = bindings - .iter() - .filter_map(|(target, loaded)| { - loaded - .binding - .route - .as_ref() - .map(|route| (target.as_str(), route)) - }) - .collect::>(); - validate_route_binding_set(&routes) -} - -fn validate_route_binding_set(routes: &[(&str, &RouteBinding)]) -> Result<()> { - for (index, (target, route)) in routes.iter().enumerate() { - let (stable_host, stable_port) = route.stable_socket()?; - let private_host = route - .private_host - .parse::() - .context("validated route private host stopped being an IP address")?; - ensure!( - stable_host != private_host - || !(route.private_port_start..=route.private_port_end).contains(&stable_port), - "route {target} stable socket overlaps its candidate port range" - ); - - for (other_target, other) in &routes[index + 1..] { - ensure!( - route.route_id != other.route_id, - "route id {} is shared by targets {target} and {other_target}", - route.route_id - ); - ensure!( - route.config_path != other.config_path, - "route fragment {} is shared by targets {target} and {other_target}", - route.config_path.display() - ); - let other_stable = other.stable_socket()?; - ensure!( - route.driver != other.driver || (stable_host, stable_port) != other_stable, - "stable route socket {}:{} is shared by targets {target} and {other_target}", - stable_host, - stable_port - ); - if route.driver != other.driver { - continue; - } - let other_private_host = other - .private_host - .parse::() - .context("validated route private host stopped being an IP address")?; - let ranges_overlap = route.private_host == other.private_host - && route.private_port_start <= other.private_port_end - && other.private_port_start <= route.private_port_end; - ensure!( - !ranges_overlap, - "candidate port ranges overlap for targets {target} and {other_target}" - ); - ensure!( - stable_host != other_private_host - || !(other.private_port_start..=other.private_port_end).contains(&stable_port), - "stable route socket for {target} overlaps {other_target}'s candidate range" - ); - ensure!( - other_stable.0 != private_host - || !(route.private_port_start..=route.private_port_end) - .contains(&other_stable.1), - "stable route socket for {other_target} overlaps {target}'s candidate range" - ); - } - } - Ok(()) -} - -fn resolve_selector( - bindings: &BTreeMap, - selector: &str, -) -> Result> { - let mut targets = if let Some(profile) = selector.strip_prefix("profile:") { - bindings - .values() - .filter(|binding| binding.binding.profiles.contains(profile)) - .map(|binding| binding.binding.target.clone()) - .collect::>() - } else { - ensure!( - bindings.contains_key(selector), - "unknown deployment target {selector}" - ); - vec![selector.to_owned()] - }; - ensure!( - !targets.is_empty(), - "unknown or empty deployment profile {selector}" - ); - targets.sort_by(|left, right| { - (left != "odin") - .cmp(&(right != "odin")) - .then_with(|| left.cmp(right)) - }); - Ok(targets) -} - -fn submit( - store_path: &Path, - selector: &str, - requested_by: &str, - wait: bool, - timeout_seconds: u64, -) -> Result<()> { - if let Some(parent) = store_path.parent() { - fs::create_dir_all(parent)?; - } - let now = now_millis()?; - let command = DeploymentCommand { - schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), - command_id: format!("up-{}", Uuid::new_v4()), - kind: CommandKind::Deploy, - selector: selector.into(), - requested_by: requested_by.into(), - requested_at_unix_millis: now, - }; - command.validate()?; - ensure!( - SingleFileMessagePackBackingStore::new(store_path).compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: DeploymentCommand::TYPE.into(), - key: command.command_id.clone(), - current: None, - }], - &[command_envelope(&command, now)?], - )?, - "deployment command id collided" - ); - println!("{}", command.command_id); - if !wait { - return Ok(()); - } - let deadline = now.saturating_add(timeout_seconds.saturating_mul(1000)); - loop { - let snapshot = ControlSnapshot::read(store_path)?; - ensure!( - snapshot - .commands - .iter() - .any(|stored| stored.value.command_id == command.command_id), - "submitted deployment command disappeared" - ); - let transactions = snapshot.transaction_for_command(&command.command_id); - if !transactions.is_empty() && transactions.iter().all(|value| value.is_terminal()) { - if let Some(error) = - transactions - .iter() - .find_map(|transaction| match &transaction.completion { - Some(TransactionCompletion::FailedBeforeFencing { error }) => { - Some(error.as_str()) - } - _ => None, - }) - { - bail!("deployment failed: {error}") - } - println!("succeeded {} target(s)", transactions.len()); - return Ok(()); - } - if now_millis()? >= deadline { - bail!("deployment command timed out") - } - thread::sleep(Duration::from_millis(250)); - } -} - -fn status(store_path: &Path, command_id: Option<&str>) -> Result<()> { - let snapshot = ControlSnapshot::read(store_path)?; - let mut commands = snapshot.commands.iter().collect::>(); - commands.sort_by_key(|stored| stored.value.requested_at_unix_millis); - if let Some(command_id) = command_id { - commands.retain(|stored| stored.value.command_id == command_id); - ensure!(!commands.is_empty(), "deployment command is unknown"); - } - for stored in commands { - let command = &stored.value; - let transactions = snapshot.transaction_for_command(&command.command_id); - let (state, detail) = derived_command_status(&transactions); - println!( - "{} {} {} {}", - command.command_id, command.selector, state, detail - ); - } - Ok(()) -} - -fn derived_command_status(transactions: &[&DeploymentTransaction]) -> (&'static str, String) { - if transactions.is_empty() { - return ("queued", String::new()); - } - if let Some(error) = transactions - .iter() - .find_map(|transaction| match &transaction.completion { - Some(TransactionCompletion::FailedBeforeFencing { error }) => Some(error.clone()), - _ => None, - }) - { - return ("failed", error); - } - if transactions.iter().all(|transaction| { - transaction.is_terminal() - && matches!( - transaction.completion, - Some(TransactionCompletion::Admitted { .. }) - ) - }) { - return ( - "succeeded", - transactions - .iter() - .map(|transaction| transaction.target.as_str()) - .collect::>() - .join(","), - ); - } - let current = transactions - .iter() - .filter(|transaction| !transaction.is_terminal()) - .map(|transaction| format!("{}:{:?}", transaction.target, transaction.phase)) - .collect::>() - .join(","); - ("running", current) -} - -struct ProcessLock { - file: File, - #[cfg(not(unix))] - path: PathBuf, -} - -impl ProcessLock { - fn acquire(store_path: &Path) -> Result { - let path = sibling_path(store_path, ".daemon.lock"); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - #[cfg(unix)] - { - use std::os::fd::AsRawFd; - let file = OpenOptions::new() - .create(true) - .read(true) - .write(true) - .open(&path) - .with_context(|| format!("opening Idunn daemon lock {}", path.display()))?; - let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; - ensure!(result == 0, "another Idunn daemon owns this control store"); - Ok(Self { file }) - } - #[cfg(not(unix))] - { - let file = OpenOptions::new() - .create_new(true) - .read(true) - .write(true) - .open(&path) - .with_context(|| format!("another Idunn daemon owns {}", path.display()))?; - Ok(Self { file, path }) - } - } -} - -impl Drop for ProcessLock { - fn drop(&mut self) { - #[cfg(unix)] - { - use std::os::fd::AsRawFd; - let _ = unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) }; - } - #[cfg(not(unix))] - { - let _ = fs::remove_file(&self.path); - } - } -} - -struct Engine { - options: RuntimeOptions, - idunn_signer: ServiceIdentitySigner, - idunn_anchor: ServiceIdentityTrustAnchor, - bootstrap_odin_authority: AdmittedOdinAuthority, - source: GitSourceDriver, - runner: DockerRunnerDriver, - workload: SystemdTransientWorkloadDriver, -} - -impl Engine { - fn open(options: RuntimeOptions) -> Result { - let idunn_signer = - open_service_identity_at::(&options.idunn_identity_store) - .context("opening Idunn activation identity")?; - let idunn_anchor = idunn_signer.trust_anchor()?; - let odin_anchor = read_trust_anchor::(&options.odin_trust_anchor) - .context("reading bootstrap Odin topology anchor")?; - let bootstrap_odin_authority = AdmittedOdinAuthority::from_anchor(&odin_anchor)?; - let source = GitSourceDriver::new( - &options.source_root, - options.staging_root.join("frozen-sources"), - options.source_identity, - ); - Ok(Self { - options, - idunn_signer, - idunn_anchor, - bootstrap_odin_authority, - source, - runner: DockerRunnerDriver::default(), - workload: SystemdTransientWorkloadDriver::default(), - }) - } - - fn topology(&self) -> CultCacheTopologyDriver { - CultCacheTopologyDriver { - projection_store: self.options.topology_store.clone(), - correlation_store: self.options.odin_correlation_store.clone(), - } - } - - fn current_odin_authority(&self, snapshot: &ControlSnapshot) -> Result { - let authority = snapshot - .admitted_for("odin") - .map(|stored| stored.value.odin_authority.clone()) - .unwrap_or_else(|| self.bootstrap_odin_authority.clone()); - authority.validate()?; - Ok(authority) - } - - fn trusted_topology_context(&self, now: u64) -> OdinTopologyAuthenticationContext { - OdinTopologyAuthenticationContext { - trusted_received_at_unix_millis: now, - maximum_age_millis: self.options.topology_maximum_age_millis, - maximum_future_skew_millis: self.options.topology_maximum_future_skew_millis, - } - } - - fn validate_durable_authority(&self, snapshot: &ControlSnapshot) -> Result<()> { - let operator_anchor = read_trust_anchor::( - &self.options.deployment_brake_operator_anchor, - )?; - for stored in &snapshot.transactions { - let transaction = &stored.value; - if let Some(authorization) = &transaction.deployment_authorization { - authorization.validate_shape()?; - let record: IdunnDeploymentBrakeRecord = - rmp_serde::from_slice(&authorization.canonical_brake_bytes)?; - verify_idunn_deployment_brake_authorization(&record, &operator_anchor)?; - let expected = required(&transaction.expected, "authorized Expected projection")?; - ensure!( - record.authorized_release_id.as_deref() - == Some(expected.sealed_release_id.as_str()) - && record.authorized_deployment_id.as_deref() - == Some(transaction.transaction_id.as_str()) - && record.runtime_id == expected.runtime_id, - "durable deployment authorization names another release or transaction" - ); - } - let lease = transaction - .leasing - .as_ref() - .and_then(LeasingEvidence::lease_sha256); - if let Some(evidence) = &transaction.latest_odin_observation { - let authenticated = self.authenticate_topology_bytes( - snapshot, - transaction, - &evidence.canonical_bytes, - lease, - evidence.admitted_at_unix_millis, - )?; - validate_authenticated_evidence(evidence, &authenticated)?; - } - if let Some(evidence) = &transaction.warming { - match evidence { - WarmingEvidence::OdinTopology { evidence } => { - let authenticated = self.authenticate_topology_bytes( - snapshot, - transaction, - &evidence.canonical_bytes, - None, - evidence.admitted_at_unix_millis, - )?; - validate_authenticated_evidence(evidence, &authenticated)?; - let incumbent_lease_sha256 = - self.incumbent_lease_sha256_for_warming(snapshot, transaction)?; - ensure!( - is_semantic_warming( - required(&transaction.expected, "Warming Expected projection",)?, - required(&transaction.activation, "Warming activation")?, - incumbent_lease_sha256.as_deref(), - &authenticated, - )?, - "durable Warming gate is not supported by current runtime evidence" - ); - } - WarmingEvidence::FirstOdinDirect { evidence } => { - self.authenticate_first_odin_warming_presence( - transaction, - &evidence.message_id, - evidence.challenged_at_unix_millis, - evidence.admitted_at_unix_millis, - &evidence.canonical_bytes, - )?; - } - } - } - if let Some(evidence) = &transaction.ready { - let authenticated = self.authenticate_topology_bytes( - snapshot, - transaction, - &evidence.canonical_bytes, - lease, - evidence.admitted_at_unix_millis, - )?; - validate_authenticated_evidence(evidence, &authenticated)?; - ensure!( - is_semantic_ready(&authenticated), - "durable Ready label is not exact semantic Ready" - ); - } - } - let odin_authority = self.current_odin_authority(snapshot)?; - for stored in &snapshot.admitted { - let generation = &stored.value; - let authority = self.runtime_authority_parts( - &generation.plan, - &generation.expected, - &generation.activation, - )?; - let latest = authenticate_odin_runtime_topology_correlation( - &generation.latest_odin_observation.canonical_bytes, - &authority, - generation.leasing.lease_sha256(), - &odin_authority.signer_public_key, - self.trusted_topology_context( - generation.latest_odin_observation.admitted_at_unix_millis, - ), - )?; - validate_authenticated_evidence(&generation.latest_odin_observation, &latest)?; - let ready = authenticate_odin_runtime_topology_correlation( - &generation.ready.canonical_bytes, - &authority, - generation.leasing.lease_sha256(), - &odin_authority.signer_public_key, - self.trusted_topology_context(generation.ready.admitted_at_unix_millis), - )?; - validate_authenticated_evidence(&generation.ready, &ready)?; - ensure!( - is_semantic_ready(&ready), - "admitted generation Ready label is not exact semantic Ready" - ); - } - Ok(()) - } -} - -fn serve(options: RuntimeOptions) -> Result<()> { - for path in [ - &options.state_store, - &options.topology_store, - &options.staging_root, - ] { - let directory = if path.extension().is_some() { - path.parent() - .context("configured Idunn path has no parent")? - } else { - path.as_path() - }; - fs::create_dir_all(directory) - .with_context(|| format!("creating Idunn directory {}", directory.display()))?; - } - let _lock = ProcessLock::acquire(&options.state_store)?; - ControlSnapshot::read(&options.state_store).context("validating all Idunn records")?; - let engine = Engine::open(options)?; - engine.validate_durable_authority(&ControlSnapshot::read(&engine.options.state_store)?)?; - - loop { - let transaction_progress = engine.resume_one_transaction()?; - let continuity_progress = engine.supervise_one_admitted_generation()?; - if !transaction_progress && !continuity_progress && engine.freeze_one_queued_command()? { - continue; - } - thread::sleep(Duration::from_millis(engine.options.poll_millis)); - } -} - -impl Engine { - /// Startup and every later loop use the same order: unfinished ownership - /// work first, admitted-body continuity second, new commands last. A - /// waiting transaction yields without relaxing ordinal order inside its - /// own command, so one target brake cannot suspend unrelated continuity. - fn resume_one_transaction(&self) -> Result { - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let mut progressed = false; - let mut candidates = snapshot - .transactions - .iter() - .filter(|stored| !stored.value.is_terminal()) - .collect::>(); - candidates.sort_by_key(|stored| { - ( - stored.value.created_at_unix_millis, - stored.value.ordinal, - stored.value.transaction_id.as_str(), - ) - }); - for current in candidates { - if snapshot.has_earlier_authority_sibling(¤t.value) { - continue; - } - if let Err(error) = self.advance_transaction(current) { - let latest_snapshot = ControlSnapshot::read(&self.options.state_store)?; - let latest = latest_snapshot - .transactions - .iter() - .find(|stored| stored.value.transaction_id == current.value.transaction_id) - .context("transaction disappeared while recording an execution error")?; - if latest.value.is_terminal() { - progressed = true; - } else if latest.value.phase < DeploymentPhase::Fencing - && latest.value.pre_fencing_abort.is_none() - { - self.begin_pre_fencing_abort(latest, error)?; - } else { - self.record_resumable_error(latest, &error)?; - } - } - let after = ControlSnapshot::read(&self.options.state_store)?; - let live = after - .transactions - .iter() - .find(|stored| stored.value.transaction_id == current.value.transaction_id) - .context("transaction disappeared while checking scheduler progress")?; - if live.envelope != current.envelope { - progressed = true; - } - } - Ok(progressed) - } - - fn freeze_one_queued_command(&self) -> Result { - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let transaction_commands = snapshot - .transactions - .iter() - .map(|stored| stored.value.command_id.as_str()) - .collect::>(); - let mut queued = snapshot - .commands - .iter() - .filter(|stored| { - stored.value.kind == CommandKind::Deploy - && !transaction_commands.contains(stored.value.command_id.as_str()) - }) - .collect::>(); - queued.sort_by_key(|stored| stored.value.requested_at_unix_millis); - let Some(command) = queued.first() else { - return Ok(false); - }; - let bindings = match load_bindings(&self.options.bindings_dir) { - Ok(bindings) => bindings, - Err(error) => { - eprintln!( - "Idunn left command {} queued because operator bindings are invalid: {error:#}", - command.value.command_id - ); - return Ok(false); - } - }; - let targets = match resolve_selector(&bindings, &command.value.selector) { - Ok(targets) => targets, - Err(error) => { - let now = now_millis()?; - let rejected = DeploymentTransaction::rejected(&command.value, error, now)?; - ensure!( - SingleFileMessagePackBackingStore::new(&self.options.state_store) - .compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: DeploymentTransaction::TYPE.into(), - key: rejected.transaction_id.clone(), - current: None, - }], - &[transaction_envelope(&rejected, now)?], - )?, - "bad selector changed before refusal was recorded" - ); - return Ok(true); - } - }; - let busy = snapshot - .transactions - .iter() - .filter(|stored| stored.value.blocks_new_target_mutation()) - .map(|stored| stored.value.target.as_str()) - .collect::>(); - if targets.iter().any(|target| busy.contains(target.as_str())) { - return Ok(false); - } - let now = now_millis()?; - let transactions = targets - .into_iter() - .enumerate() - .map(|(ordinal, target)| { - DeploymentTransaction::new( - &command.value, - target.clone(), - u32::try_from(ordinal)?, - snapshot.admitted_for(&target).map(|stored| &stored.value), - now, - ) - }) - .collect::>>()?; - let expected = transactions - .iter() - .map(|transaction| CultCacheExpectedEnvelope { - r#type: DeploymentTransaction::TYPE.into(), - key: transaction.transaction_id.clone(), - current: None, - }) - .collect::>(); - let next = transactions - .iter() - .map(|transaction| transaction_envelope(transaction, now)) - .collect::>>()?; - ensure!( - SingleFileMessagePackBackingStore::new(&self.options.state_store) - .compare_exchange(&expected, &next)?, - "queued command lost its ordered transaction creation CAS" - ); - Ok(true) - } - - fn supervise_one_admitted_generation(&self) -> Result { - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let mut progressed = false; - let mut admitted = snapshot.admitted.iter().collect::>(); - admitted.sort_by_key(|stored| stored.value.target.as_str()); - for current in admitted { - let blocker = snapshot.transactions.iter().find(|stored| { - stored.value.target == current.value.target - && stored.value.blocks_new_target_mutation() - }); - if blocker.is_some_and(|stored| { - stored.value.phase >= DeploymentPhase::Fencing - && stored.value.phase < DeploymentPhase::Complete - }) { - continue; - } - match self.supervise_admitted_route(current) { - Ok(true) => { - progressed = true; - continue; - } - Ok(false) => {} - Err(error) => eprintln!( - "Idunn rejected admitted {} route continuity: {error:#}", - current.value.target - ), - } - match self.refresh_admitted_topology(&snapshot, current) { - Ok(true) => { - progressed = true; - continue; - } - Ok(false) => {} - Err(error) => eprintln!( - "Idunn preserved admitted {} after rejecting topology observation: {error:#}", - current.value.target - ), - } - let mut operational_error = None; - let observation = match self.workload.observe( - ¤t.value.expected, - ¤t.value.activation, - ¤t.value.workload, - ) { - Ok(observation) => { - let lease_is_missing = if let Some(lease) = current.value.leasing.lease() { - let lease_health = (|| -> Result { - let lease_path = current - .value - .plan - .parsed_inputs()? - .1 - .process_write_lease - .context("admitted lease has no operator binding")? - .record_path; - let driver = - CultCacheWriteLeaseDriver::new(¤t.value.target, lease_path); - if driver.observe_exact(lease)? { - return Ok(true); - } - if driver.observe_empty()? { - return Ok(false); - } - bail!("write-lease store contains unexpected authority") - })(); - match lease_health { - Ok(true) => false, - Ok(false) => { - operational_error = - Some(anyhow!("admitted physical write lease is missing")); - true - } - Err(error) => { - eprintln!( - "Idunn preserved admitted {} after refusing an unsafe write-lease mutation: {error:#}", - current.value.target - ); - continue; - } - } - } else { - false - }; - if lease_is_missing { - None - } else { - Some(observation) - } - } - Err(error) => { - operational_error = Some(error); - None - } - }; - if let Some(observation) = observation { - if blocker.is_none() - || blocker.is_some_and(|stored| stored.value.phase == DeploymentPhase::Complete) - { - let repair = (|| -> Result<()> { - let topology = self.topology(); - let provider_anchor = self.provider_anchor_for_plan(¤t.value.plan)?; - if !topology.admitted_runtime_projection_is_exact( - ¤t.value.expected, - &provider_anchor, - ¤t.value.activation, - current.value.leasing.lease(), - )? { - ensure!( - topology - .publish_expected(¤t.value.expected, &provider_anchor,)? - == current.value.expected.canonical_sha256()?, - "admitted Expected projection repair differs" - ); - ensure!( - topology.publish_observed_activation( - ¤t.value.expected, - ¤t.value.activation, - &observation, - )? == current.value.activation.canonical_sha256()?, - "admitted activation projection repair differs" - ); - if let Some(lease) = current.value.leasing.lease() { - ensure!( - topology.publish_process_write_lease( - ¤t.value.expected, - ¤t.value.activation, - lease, - )? == lease.canonical_sha256()?, - "admitted write-lease projection repair differs" - ); - } - } - Ok(()) - })(); - if let Err(error) = repair { - eprintln!( - "Idunn preserved admitted {} after refusing topology projection repair: {error:#}", - current.value.target - ); - } - } - continue; - } - let workload_error = operational_error - .context("admitted operational state has neither observation nor error")?; - if let Some(blocker) = blocker { - if blocker.value.phase < DeploymentPhase::Fencing - && blocker.value.pre_fencing_abort.is_none() - { - self.begin_pre_fencing_abort( - blocker, - anyhow!( - "admitted incumbent failed before candidate fencing; deployment yielded to continuity: {workload_error:#}" - ), - )?; - progressed = true; - } - continue; - } - let now = now_millis()?; - let command = DeploymentCommand { - schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), - command_id: format!("continuity-{}", Uuid::new_v4()), - kind: CommandKind::Continuity, - selector: current.value.target.clone(), - requested_by: "idunn-continuity".into(), - requested_at_unix_millis: now, - }; - command.validate()?; - let transaction = - DeploymentTransaction::from_continuity(&command, ¤t.value, now)?; - ensure!( - SingleFileMessagePackBackingStore::new(&self.options.state_store) - .compare_exchange( - &[ - CultCacheExpectedEnvelope { - r#type: DeploymentCommand::TYPE.into(), - key: command.command_id.clone(), - current: None, - }, - CultCacheExpectedEnvelope { - r#type: DeploymentTransaction::TYPE.into(), - key: transaction.transaction_id.clone(), - current: None, - }, - ], - &[ - command_envelope(&command, now)?, - transaction_envelope(&transaction, now)?, - ], - )?, - "continuity scheduling lost its command/transaction CAS" - ); - progressed = true; - } - Ok(progressed) - } - - fn supervise_admitted_route(&self, current: &Stored) -> Result { - let Some(expected_route) = current.value.expected.route.as_ref() else { - ensure!( - matches!(¤t.value.routing, RoutingEvidence::SkippedUnrouted) - && current.value.route_repair_started_at_unix_millis.is_none(), - "unrouted admitted generation carries route authority" - ); - return Ok(false); - }; - let RoutingEvidence::Promoted { - observation, - promoted_at_unix_millis, - } = ¤t.value.routing - else { - bail!("routed admitted generation has no promoted route receipt") - }; - ensure!( - observation.route_id == expected_route.route_id - && observation.runtime_instance_id == current.value.activation.runtime_instance_id, - "admitted route receipt names another incarnation" - ); - let binding = current.value.plan.parsed_inputs()?.1; - let lease_driver = if let Some(lease) = current.value.leasing.lease() { - let lease_path = &binding - .process_write_lease - .as_ref() - .context("stateful admitted generation has no write-lease binding")? - .record_path; - let driver = CultCacheWriteLeaseDriver::new(¤t.value.target, lease_path); - ensure!( - driver.observe_exact(lease)?, - "admitted process write lease is no longer exact" - ); - Some(driver) - } else { - None - }; - let route_binding = binding - .route - .context("routed admitted generation has no operator route binding")?; - let driver = NginxRouteDriver::new(route_binding); - - let membership_is_exact = - driver.observe_membership(¤t.value.expected, &observation.membership_sha256)?; - let now = now_millis()?; - if membership_is_exact - && route_observation_is_current( - observation.observed_at_unix_millis, - now, - self.options.topology_maximum_age_millis, - self.options.topology_maximum_future_skew_millis, - ) - && current.value.route_repair_started_at_unix_millis.is_none() - { - return Ok(false); - } - if current.value.route_repair_started_at_unix_millis.is_none() { - let mut next = current.value.clone(); - next.route_repair_started_at_unix_millis = Some(now); - next.validate()?; - ensure!( - SingleFileMessagePackBackingStore::new(&self.options.state_store) - .compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: AdmittedGeneration::TYPE.into(), - key: current.value.target.clone(), - current: Some(current.envelope.clone()), - }], - &[admitted_envelope(&next, now)?], - )?, - "admitted generation changed before route repair intent CAS" - ); - return Ok(true); - } - driver - .restore_admitted_membership(¤t.value.expected, &observation.membership_sha256)?; - let authority = self.runtime_authority_parts( - ¤t.value.plan, - ¤t.value.expected, - ¤t.value.activation, - )?; - let refreshed = self.prove_stable_route_against( - ¤t.value.expected, - ¤t.value.activation, - &authority, - current.value.leasing.lease_sha256(), - &driver, - observation.membership_sha256.clone(), - )?; - ensure!( - driver.observe_membership(¤t.value.expected, &refreshed.membership_sha256)?, - "admitted route membership changed during its continuity challenge" - ); - if let (Some(lease_driver), Some(lease)) = (&lease_driver, current.value.leasing.lease()) { - ensure!( - lease_driver.observe_exact(lease)?, - "admitted process write lease changed during its continuity challenge" - ); - } - let mut next = current.value.clone(); - next.routing = RoutingEvidence::Promoted { - observation: refreshed, - promoted_at_unix_millis: *promoted_at_unix_millis, - }; - next.route_repair_started_at_unix_millis = None; - next.validate()?; - ensure!( - SingleFileMessagePackBackingStore::new(&self.options.state_store).compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: AdmittedGeneration::TYPE.into(), - key: current.value.target.clone(), - current: Some(current.envelope.clone()), - }], - &[admitted_envelope(&next, now)?], - )?, - "admitted generation changed before route continuity receipt CAS" - ); - Ok(true) - } - - fn refresh_admitted_topology( - &self, - snapshot: &ControlSnapshot, - current: &Stored, - ) -> Result { - let Some(received) = self.topology().receive(¤t.value.target)? else { - return Ok(false); - }; - ensure!( - received.target == current.value.target, - "topology transport substituted admitted target" - ); - let now = now_millis()?; - let authority = self.runtime_authority_parts( - ¤t.value.plan, - ¤t.value.expected, - ¤t.value.activation, - )?; - let odin_authority = self.current_odin_authority(snapshot)?; - let authenticated = authenticate_odin_runtime_topology_correlation( - &received.canonical_bytes, - &authority, - current.value.leasing.lease_sha256(), - &odin_authority.signer_public_key, - self.trusted_topology_context(now), - )?; - let evidence = TopologyEvidence::from_authenticated(&authenticated, now)?; - if !sequence_requires_admission( - Some(¤t.value.latest_odin_observation), - snapshot.max_odin_sequence(¤t.value.target, &evidence.signer_identity_id), - &evidence, - )? { - return Ok(false); - } - let mut next = current.value.clone(); - next.latest_odin_observation = evidence.clone(); - next.odin_publisher_sequence_cursor = evidence.publisher_sequence; - if is_semantic_ready(&authenticated) { - next.ready = evidence; - } - next.validate()?; - ensure!( - SingleFileMessagePackBackingStore::new(&self.options.state_store).compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: AdmittedGeneration::TYPE.into(), - key: current.value.target.clone(), - current: Some(current.envelope.clone()), - }], - &[admitted_envelope(&next, now)?], - )?, - "admitted generation changed before topology sequence CAS" - ); - Ok(true) - } - - fn advance_transaction(&self, current: &Stored) -> Result<()> { - if current.value.pre_fencing_abort.is_some() && current.value.completion.is_none() { - return self.advance_pre_fencing_abort(current); - } - match current.value.phase { - DeploymentPhase::Sealing => self.advance_sealing(current), - DeploymentPhase::Starting => self.advance_starting(current), - DeploymentPhase::Warming => self.advance_warming(current), - DeploymentPhase::Fencing => self.advance_fencing(current), - DeploymentPhase::Leasing => self.advance_leasing(current), - DeploymentPhase::AwaitingReady => self.advance_awaiting_ready(current), - DeploymentPhase::Routing => self.advance_routing(current), - DeploymentPhase::Committing => self.advance_committing(current), - DeploymentPhase::Complete => self.advance_post_commit_cleanup(current), - } - } - - fn advance_sealing(&self, current: &Stored) -> Result<()> { - if current.value.plan.is_none() { - ensure!( - current.value.command_kind == CommandKind::Deploy, - "continuity transaction lost its admitted plan" - ); - let bindings = load_bindings(&self.options.bindings_dir)?; - let loaded = bindings - .get(¤t.value.target) - .context("operator binding disappeared before sealing")?; - let now = now_millis()?; - let resolved = - self.source - .resolve(&loaded.binding, ¤t.value.transaction_id, now)?; - let providers = self.current_ready_provider_tokens( - &ControlSnapshot::read(&self.options.state_store)?, - now, - )?; - let candidate_port = self.select_candidate_port(&loaded.binding)?; - let plan = compile_deployment_plan( - &resolved.recipe_bytes, - &loaded.bytes, - resolved.facts, - format!("incarnation-{}", current.value.transaction_id), - candidate_port, - now, - &providers, - )?; - return self.persist_same_phase(current, |next| { - next.plan = Some(plan); - next.updated_at_unix_millis = now; - next.last_error = None; - Ok(()) - }); - } - - if current.value.command_kind == CommandKind::Deploy - && current.value.frozen_source.is_none() - { - let now = now_millis()?; - let plan = required(¤t.value.plan, "transaction plan")?; - let receipt = self.source.freeze(¤t.value.transaction_id, plan)?; - return self.persist_same_phase(current, |next| { - next.frozen_source = Some(receipt); - next.updated_at_unix_millis = now; - next.last_error = None; - Ok(()) - }); - } - - if current.value.sealed_release.is_none() - || current.value.installed_release.is_none() - || current.value.expected.is_none() - { - ensure!( - current.value.command_kind == CommandKind::Deploy, - "continuity transaction lost its admitted release evidence" - ); - let now = now_millis()?; - let plan = required(¤t.value.plan, "transaction plan")?; - let frozen_receipt = required(¤t.value.frozen_source, "frozen source")?; - let frozen = self.source.observe_frozen(plan, frozen_receipt)?; - let materialized = - self.runner - .materialize(&frozen, plan, &self.options.staging_root, now)?; - let installed = self.workload.install(plan, &materialized)?; - let expected = materialized.release.expected_projection(plan)?; - return self.persist_same_phase(current, |next| { - next.sealed_release = Some(materialized.release); - next.installed_release = Some(installed); - next.expected = Some(expected); - next.updated_at_unix_millis = now; - next.last_error = None; - Ok(()) - }); - } - - if current.value.expected_publication_sha256.is_none() { - let now = now_millis()?; - let plan = required(¤t.value.plan, "transaction plan")?; - let expected = required(¤t.value.expected, "Expected projection")?; - let provider_anchor = self.provider_anchor_for_plan(plan)?; - let digest = self - .topology() - .publish_expected(expected, &provider_anchor)?; - return self.persist_same_phase(current, |next| { - next.expected_publication_sha256 = Some(digest); - next.updated_at_unix_millis = now; - next.last_error = None; - Ok(()) - }); - } - - let now = now_millis()?; - let mut next = current.value.clone(); - match current.value.command_kind { - CommandKind::Deploy => { - let Some(authorization) = self.deployment_authorization(current, now)? else { - return self.record_gate_wait( - current, - "deployment brake has not released this exact transaction", - ); - }; - next.deployment_authorization = Some(authorization); - } - CommandKind::Continuity => { - if !self.lifecycle_allows(current, now)? { - return self - .record_gate_wait(current, "lifecycle brake denies continuity restart"); - } - next.lifecycle_authorized_at_unix_millis = Some(now); - } - } - validate_live_providers_for_deploy(current.value.command_kind, || { - self.validate_selected_providers_current( - required(¤t.value.plan, "transaction plan")?, - now, - ) - })?; - next.phase = DeploymentPhase::Starting; - next.updated_at_unix_millis = now; - next.last_error = None; - replace_transaction(&self.options.state_store, current, &next) - } - - fn advance_starting(&self, current: &Stored) -> Result<()> { - let expected = required(¤t.value.expected, "Expected projection")?; - let plan = required(¤t.value.plan, "transaction plan")?; - let release = required(¤t.value.sealed_release, "sealed release")?; - let installed = required(¤t.value.installed_release, "installed release")?; - if current.value.activation.is_none() { - validate_live_providers_for_deploy(current.value.command_kind, || { - self.validate_selected_providers_current(plan, now_millis()?) - })?; - let now = now_millis()?; - let runtime_instance_id = runtime_instance_id(¤t.value.transaction_id)?; - let launch = IdunnRuntimeActivationLaunch::issue( - expected, - runtime_instance_id, - now, - &self.idunn_signer, - )?; - let activation = self.workload.prepare_activation(plan, expected, launch)?; - return self.persist_same_phase(current, |next| { - next.activation = Some(activation); - next.updated_at_unix_millis = now; - next.last_error = None; - Ok(()) - }); - } - if current.value.workload.is_none() { - let now = now_millis()?; - let activation = required(¤t.value.activation, "activation")?; - let observation = self - .workload - .start_prepared(plan, release, installed, expected, activation)?; - return self.persist_same_phase(current, |next| { - next.workload = Some(observation); - next.updated_at_unix_millis = now; - next.last_error = None; - Ok(()) - }); - } - if current.value.activation_publication_sha256.is_none() { - let now = now_millis()?; - let activation = required(¤t.value.activation, "activation")?; - let workload = required(¤t.value.workload, "workload")?; - self.workload.observe(expected, activation, workload)?; - let digest = self - .topology() - .publish_observed_activation(expected, activation, workload)?; - return self.persist_same_phase(current, |next| { - next.activation_publication_sha256 = Some(digest); - next.updated_at_unix_millis = now; - next.last_error = None; - Ok(()) - }); - } - let mut next = current.value.clone(); - next.phase = DeploymentPhase::Warming; - next.updated_at_unix_millis = now_millis()?; - next.last_error = None; - replace_transaction(&self.options.state_store, current, &next) - } - - fn advance_warming(&self, current: &Stored) -> Result<()> { - let expected = required(¤t.value.expected, "Expected projection")?; - let activation = required(¤t.value.activation, "activation")?; - let workload = required(¤t.value.workload, "workload")?; - self.workload.observe(expected, activation, workload)?; - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let incumbent_lease_sha256 = - self.incumbent_lease_sha256_for_warming(&snapshot, ¤t.value)?; - if current.value.warming.is_none() { - if current.value.target == "odin" && snapshot.admitted_for("odin").is_none() { - ensure!( - current.value.incumbent_generation_id.is_none() - && expected.write_lease_required, - "first Odin bootstrap must be a stateful first incarnation" - ); - let (evidence, present) = self.observe_first_odin_warming(¤t.value)?; - let _token = SequenceAdmittedWarming::from_first_odin_presence( - current.value.transaction_id.clone(), - evidence.clone(), - present, - )?; - return self.persist_same_phase(current, |next| { - next.warming = Some(WarmingEvidence::FirstOdinDirect { evidence }); - Ok(()) - }); - } - let Some((admitted, authenticated)) = self.admit_latest_topology(current, None)? else { - return Ok(()); - }; - if admitted.envelope != current.envelope { - return Ok(()); - } - let semantic_warming = is_semantic_warming( - expected, - activation, - incumbent_lease_sha256.as_deref(), - &authenticated, - )?; - let latest = required( - &admitted.value.latest_odin_observation, - "sequence-admitted warming evidence", - )?; - if semantic_warming { - let evidence = latest.clone(); - let _token = SequenceAdmittedWarming::from_topology( - admitted.value.transaction_id.clone(), - evidence.clone(), - authenticated, - )?; - return self.persist_same_phase(&admitted, |next| { - next.warming = Some(WarmingEvidence::OdinTopology { evidence }); - Ok(()) - }); - } else { - return Ok(()); - } - } - let warming = self.rehydrate_warming_token(¤t.value, now_millis()?, false)?; - ensure!( - warming.transaction_id() == current.value.transaction_id - && warming.runtime_instance_id() == activation.runtime_instance_id.as_str(), - "durable Warming evidence belongs to another candidate" - ); - - if expected.route.is_some() && current.value.route_preflight.is_none() { - let now = now_millis()?; - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let incumbent = self.exact_incumbent(&snapshot, ¤t.value)?; - let incumbent_route = - incumbent.and_then(|generation| generation.value.routing.observation().cloned()); - let binding = current.value.plan.as_ref().unwrap().parsed_inputs()?.1; - let route_binding = binding - .route - .context("routed Expected lost route binding")?; - let driver = NginxRouteDriver::new(route_binding); - let receipt = driver.preflight( - expected, - &activation.runtime_instance_id, - incumbent_route.as_ref(), - )?; - return self.persist_same_phase(current, |next| { - next.route_preflight = Some(receipt); - next.updated_at_unix_millis = now; - Ok(()) - }); - } - - if current.value.isolation.is_none() { - let now = now_millis()?; - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let incumbent = self.exact_incumbent(&snapshot, ¤t.value)?; - let isolation = - prove_isolation(workload, incumbent.map(|value| &value.value.workload))?; - return self.persist_same_phase(current, |next| { - next.isolation = Some(isolation); - next.updated_at_unix_millis = now; - Ok(()) - }); - } - - self.transition(current, DeploymentPhase::Fencing) - } - - fn advance_fencing(&self, current: &Stored) -> Result<()> { - if current.value.fencing.is_none() { - let now = now_millis()?; - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let incumbent = self.exact_incumbent(&snapshot, ¤t.value)?; - let incumbent_lease = incumbent.and_then(|generation| generation.value.leasing.lease()); - let expected = required(¤t.value.expected, "Expected projection")?; - let evidence = if expected.write_lease_required || incumbent_lease.is_some() { - let incumbent_lease_path = incumbent_lease - .map(|_| -> Result { - Ok(incumbent - .context("incumbent lease has no admitted generation")? - .value - .plan - .parsed_inputs()? - .1 - .process_write_lease - .context("incumbent lease has no admitted binding")? - .record_path) - }) - .transpose()?; - if let (Some(lease), Some(path)) = (incumbent_lease, &incumbent_lease_path) { - let incumbent = incumbent.context("incumbent lease lost its generation")?; - self.workload - .stop(&incumbent.value.workload) - .context("stopping the exact incumbent before revoking its lifetime-held write lease")?; - let driver = CultCacheWriteLeaseDriver::new(¤t.value.target, path); - driver.revoke_exact(Some(lease))?; - ensure!( - driver.observe_empty()?, - "incumbent write lease remained after exact fencing" - ); - self.topology().withdraw_process_write_lease( - &incumbent.value.expected, - &incumbent.value.activation, - Some(lease), - )?; - } - let candidate_lease_path = if expected.write_lease_required { - Some( - current - .value - .plan - .as_ref() - .unwrap() - .parsed_inputs()? - .1 - .process_write_lease - .context("stateful candidate has no write-lease binding")? - .record_path, - ) - } else { - None - }; - if let Some(path) = &candidate_lease_path { - if incumbent_lease_path.as_ref() != Some(path) { - let driver = CultCacheWriteLeaseDriver::new(¤t.value.target, path); - driver.revoke_exact(None)?; - ensure!( - driver.observe_empty()?, - "candidate write-lease path was not empty before grant" - ); - } - } - self.topology().withdraw_process_write_lease( - expected, - required(¤t.value.activation, "candidate activation")?, - None, - )?; - FencingEvidence::Revoked { - incumbent_lease_sha256: incumbent_lease - .map(IdunnProcessWriteLeaseRecord::canonical_sha256) - .transpose()?, - candidate_lease_path_verified_empty: candidate_lease_path.is_some(), - } - } else { - FencingEvidence::SkippedStateless - }; - return self.persist_same_phase(current, |next| { - next.fencing = Some(evidence); - next.updated_at_unix_millis = now; - Ok(()) - }); - } - self.transition(current, DeploymentPhase::Leasing) - } - - fn advance_leasing(&self, current: &Stored) -> Result<()> { - let expected = required(¤t.value.expected, "Expected projection")?; - if !expected.write_lease_required { - if current.value.leasing.is_none() { - let now = now_millis()?; - return self.persist_same_phase(current, |next| { - next.leasing = Some(LeasingEvidence::SkippedStateless); - next.updated_at_unix_millis = now; - Ok(()) - }); - } - return self.transition(current, DeploymentPhase::AwaitingReady); - } - - let binding = current.value.plan.as_ref().unwrap().parsed_inputs()?.1; - let lease_path = binding - .process_write_lease - .context("stateful target has no write-lease binding")? - .record_path; - let driver = CultCacheWriteLeaseDriver::new(¤t.value.target, lease_path); - - if matches!( - current.value.leasing.as_ref(), - Some(LeasingEvidence::Granted { .. }) - ) { - let activation = required(¤t.value.activation, "activation")?; - let warming = self.rehydrate_warming_token(¤t.value, now_millis()?, false)?; - let lease = current - .value - .leasing - .as_ref() - .and_then(LeasingEvidence::lease) - .context("granted Leasing evidence has no write lease")?; - let recorded_sha256 = current - .value - .leasing - .as_ref() - .and_then(LeasingEvidence::lease_sha256) - .context("granted Leasing evidence has no lease digest")?; - ensure!( - driver.observe_exact(lease)?, - "physical write lease disappeared after Granted became durable" - ); - self.workload.observe( - expected, - activation, - required(¤t.value.workload, "candidate workload")?, - )?; - ensure!( - driver.grant(expected, activation, &warming, lease)? == recorded_sha256, - "replayed physical write lease differs from Granted evidence" - ); - ensure!( - self.topology() - .publish_process_write_lease(expected, activation, lease)? - == recorded_sha256, - "replayed write-lease projection differs from Granted evidence" - ); - return self.transition(current, DeploymentPhase::AwaitingReady); - } - - if let Some((lease, prepared_sha256)) = current - .value - .leasing - .as_ref() - .and_then(LeasingEvidence::prepared_lease) - { - let now = now_millis()?; - let activation = required(¤t.value.activation, "activation")?; - let historical_warming = self.rehydrate_warming_token(¤t.value, now, false)?; - let physical_is_exact = driver.observe_exact(lease)?; - let warming = if physical_is_exact { - historical_warming - } else { - ensure!( - driver.observe_empty()?, - "candidate write-lease store contains authority other than its durable prepared lease" - ); - match self.rehydrate_warming_token(¤t.value, now, true) { - Ok(warming) => warming, - Err(_) => { - let Some((admitted, fresh_evidence, fresh_warming)) = - self.fresh_warming_for_lease(current, now)? - else { - return Ok(()); - }; - let replacement = self.prepare_candidate_write_lease( - &admitted.value, - &fresh_warming, - now, - )?; - let replacement_sha256 = replacement.canonical_sha256()?; - return self.persist_same_phase(&admitted, |next| { - next.warming = Some(fresh_evidence); - next.leasing = Some(LeasingEvidence::Prepared { - lease: replacement, - lease_sha256: replacement_sha256, - }); - next.updated_at_unix_millis = now; - Ok(()) - }); - } - } - }; - self.workload.observe( - expected, - activation, - required(¤t.value.workload, "candidate workload")?, - )?; - if !physical_is_exact { - ensure!( - driver.observe_empty()?, - "candidate write-lease store changed before physical grant" - ); - } - let granted_sha256 = driver.grant(expected, activation, &warming, lease)?; - ensure!( - granted_sha256 == prepared_sha256, - "granted write lease differs from the durable prepared lease" - ); - let projected_sha256 = self - .topology() - .publish_process_write_lease(expected, activation, lease)?; - ensure!( - projected_sha256 == granted_sha256, - "projected write lease differs from the granted process authority" - ); - let lease = lease.clone(); - return self.persist_same_phase(current, |next| { - next.leasing = Some(LeasingEvidence::Granted { - lease, - lease_sha256: projected_sha256, - }); - next.updated_at_unix_millis = now; - Ok(()) - }); - } - - ensure!( - current.value.leasing.is_none(), - "stateful Leasing phase carries invalid lease evidence" - ); - ensure!( - driver.observe_empty()?, - "candidate write-lease store contains authority before lease preparation" - ); - let now = now_millis()?; - let Some((admitted, fresh_evidence, fresh_warming)) = - self.fresh_warming_for_lease(current, now)? - else { - return Ok(()); - }; - let lease = self.prepare_candidate_write_lease(&admitted.value, &fresh_warming, now)?; - let lease_sha256 = lease.canonical_sha256()?; - self.persist_same_phase(&admitted, |next| { - next.warming = Some(fresh_evidence); - next.leasing = Some(LeasingEvidence::Prepared { - lease, - lease_sha256, - }); - next.updated_at_unix_millis = now; - Ok(()) - }) - } - - fn advance_awaiting_ready(&self, current: &Stored) -> Result<()> { - let now = now_millis()?; - let expected = required(¤t.value.expected, "Expected projection")?; - if expected.write_lease_required { - let activation = required(¤t.value.activation, "activation")?; - let warming = self.rehydrate_warming_token(¤t.value, now, false)?; - let lease = current - .value - .leasing - .as_ref() - .and_then(LeasingEvidence::lease) - .context("stateful transaction has no process write lease")?; - let binding = current.value.plan.as_ref().unwrap().parsed_inputs()?.1; - let path = binding - .process_write_lease - .context("stateful target has no write-lease binding")? - .record_path; - ensure!( - CultCacheWriteLeaseDriver::new(¤t.value.target, path) - .observe(expected, activation, &warming, lease)?, - "candidate process write lease is no longer exact" - ); - } - { - let current_lease = current - .value - .leasing - .as_ref() - .and_then(LeasingEvidence::lease_sha256); - let Some((admitted, authenticated)) = - self.admit_latest_topology(current, current_lease)? - else { - return Ok(()); - }; - if admitted.envelope != current.envelope { - return Ok(()); - } - let semantic_ready = is_semantic_ready(&authenticated); - let latest = required( - &admitted.value.latest_odin_observation, - "sequence-admitted Ready evidence", - )?; - if current.value.ready.as_ref() == Some(latest) { - ensure!(semantic_ready, "stored Ready receipt changed meaning"); - } else if semantic_ready { - let evidence = latest.clone(); - let _token = SequenceAdmittedReady { - transaction_id: admitted.value.transaction_id.clone(), - evidence: evidence.clone(), - expected: expected.clone(), - authenticated, - }; - return self.persist_same_phase(&admitted, |next| { - next.ready = Some(evidence); - Ok(()) - }); - } else { - return Ok(()); - } - } - self.transition(current, DeploymentPhase::Routing) - } - - fn advance_routing(&self, current: &Stored) -> Result<()> { - let expected = required(¤t.value.expected, "Expected projection")?; - let activation = required(¤t.value.activation, "activation")?; - if current.value.routing.is_none() { - let current_lease = current - .value - .leasing - .as_ref() - .and_then(LeasingEvidence::lease_sha256); - let Some((admitted, authenticated)) = - self.admit_latest_topology(current, current_lease)? - else { - return Ok(()); - }; - if admitted.envelope != current.envelope { - return Ok(()); - } - ensure!( - is_semantic_ready(&authenticated), - "latest Odin observation is not Ready at route admission" - ); - let latest = required( - &admitted.value.latest_odin_observation, - "current route-admission topology evidence", - )?; - if admitted.value.ready.as_ref() != Some(latest) { - let latest = latest.clone(); - return self.persist_same_phase(&admitted, |next| { - next.ready = Some(latest); - Ok(()) - }); - } - let ready = self.rehydrate_ready_token(&admitted.value, now_millis()?, true)?; - ensure!( - ready.transaction_id() == admitted.value.transaction_id, - "Ready token belongs to another transaction" - ); - validate_live_providers_for_deploy(admitted.value.command_kind, || { - self.validate_selected_providers_current( - required(&admitted.value.plan, "transaction plan")?, - now_millis()?, - ) - })?; - self.ensure_transaction_write_lease_current(&admitted.value, now_millis()?)?; - let evidence = if expected.route.is_some() { - let binding = admitted.value.plan.as_ref().unwrap().parsed_inputs()?.1; - let route_binding = binding.route.context("routed plan has no route binding")?; - let preflight = required(&admitted.value.route_preflight, "route preflight")?; - let driver = NginxRouteDriver::new(route_binding); - ensure!( - preflight.candidate_runtime_instance_id == activation.runtime_instance_id, - "route preflight belongs to another runtime instance" - ); - let rollback_allowed = may_rollback_route_after_failed_proof(required( - &admitted.value.fencing, - "route fencing evidence", - )?); - let membership_sha256 = driver.install( - expected, - &activation.runtime_instance_id, - preflight, - rollback_allowed, - )?; - let observation = match self.prove_stable_route( - &admitted.value, - &driver, - membership_sha256, - ) { - Ok(observation) => observation, - Err(proof_error) if !rollback_allowed => { - return Err(proof_error).context( - "incumbent authority was fenced; candidate route remains installed for fail-closed retry", - ); - } - Err(proof_error) => { - return match driver.rollback( - expected, - &activation.runtime_instance_id, - preflight, - ) { - Ok(()) => Err(proof_error) - .context("candidate did not answer its stable route challenge"), - Err(rollback_error) => Err(proof_error).context(format!( - "candidate did not answer its stable route challenge; exact route rollback also failed: {rollback_error:#}" - )), - }; - } - }; - ensure!( - driver.observe_membership(expected, &observation.membership_sha256)?, - "route membership changed during its signed stable-listener observation" - ); - self.ensure_transaction_write_lease_current(&admitted.value, now_millis()?)?; - let promoted_at_unix_millis = observation.observed_at_unix_millis; - RoutingEvidence::Promoted { - observation, - promoted_at_unix_millis, - } - } else { - RoutingEvidence::SkippedUnrouted - }; - let now = now_millis()?; - return self.persist_same_phase(&admitted, |next| { - next.routing = Some(evidence); - next.updated_at_unix_millis = now; - Ok(()) - }); - } - self.transition(current, DeploymentPhase::Committing) - } - - fn advance_committing(&self, current: &Stored) -> Result<()> { - let current_lease_sha256 = current - .value - .leasing - .as_ref() - .and_then(LeasingEvidence::lease_sha256) - .map(str::to_owned); - let Some((ready_current, authenticated)) = - self.admit_latest_topology(current, current_lease_sha256.as_deref())? - else { - return Ok(()); - }; - if ready_current.envelope != current.envelope { - return Ok(()); - } - ensure!( - is_semantic_ready(&authenticated), - "latest Odin observation is not Ready at admission commit" - ); - ensure!( - ready_current.value.latest_odin_observation.as_ref() - == ready_current.value.ready.as_ref(), - "latest Odin observation differs from the durable Ready receipt at admission commit" - ); - self.rehydrate_ready_token(&ready_current.value, now_millis()?, true)?; - validate_live_providers_for_deploy(ready_current.value.command_kind, || { - self.validate_selected_providers_current( - required(&ready_current.value.plan, "transaction plan")?, - now_millis()?, - ) - })?; - - let expected = required(&ready_current.value.expected, "Expected projection")?; - let activation = required(&ready_current.value.activation, "activation")?; - let workload = required(&ready_current.value.workload, "workload")?; - self.workload.observe(expected, activation, workload)?; - self.ensure_transaction_write_lease_current(&ready_current.value, now_millis()?)?; - if let Some(route) = ready_current - .value - .routing - .as_ref() - .and_then(RoutingEvidence::observation) - { - let binding = ready_current - .value - .plan - .as_ref() - .unwrap() - .parsed_inputs()? - .1; - let driver = - NginxRouteDriver::new(binding.route.context("routed plan has no route binding")?); - ensure!( - driver.observe_membership(expected, &route.membership_sha256)?, - "route membership changed before admission commit" - ); - let current_route = self.prove_stable_route( - &ready_current.value, - &driver, - route.membership_sha256.clone(), - )?; - ensure!( - current_route.route_id == route.route_id - && current_route.runtime_instance_id == route.runtime_instance_id, - "stable route changed incarnation before admission commit" - ); - ensure!( - driver.observe_membership(expected, &route.membership_sha256)?, - "route membership changed during the final signed admission challenge" - ); - self.ensure_transaction_write_lease_current(&ready_current.value, now_millis()?)?; - } - - let current_lease_sha256 = ready_current - .value - .leasing - .as_ref() - .and_then(LeasingEvidence::lease_sha256) - .map(str::to_owned); - let Some((commit_current, authenticated)) = - self.admit_latest_topology(&ready_current, current_lease_sha256.as_deref())? - else { - return Ok(()); - }; - if commit_current.envelope != ready_current.envelope { - return Ok(()); - } - ensure!( - is_semantic_ready(&authenticated), - "latest Odin observation is not Ready after the final admission challenge" - ); - ensure!( - commit_current.value.latest_odin_observation.as_ref() - == commit_current.value.ready.as_ref(), - "latest Odin observation differs from the durable Ready receipt after the final admission challenge" - ); - let now = now_millis()?; - self.rehydrate_ready_token(&commit_current.value, now, true)?; - validate_live_providers_for_deploy(commit_current.value.command_kind, || { - self.validate_selected_providers_current( - required(&commit_current.value.plan, "transaction plan")?, - now, - ) - })?; - self.workload.observe( - required(&commit_current.value.expected, "Expected projection")?, - required(&commit_current.value.activation, "activation")?, - required(&commit_current.value.workload, "workload")?, - )?; - self.ensure_transaction_write_lease_current(&commit_current.value, now)?; - - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let incumbent = self.exact_incumbent(&snapshot, &commit_current.value)?; - let odin_authority = self.current_odin_authority(&snapshot)?; - let generation = - AdmittedGeneration::from_transaction(&commit_current.value, odin_authority, now)?; - let post_commit_cleanup = PostCommitCleanup { - incumbent: match incumbent { - Some(incumbent) - if incumbent_was_stopped_during_fencing(required( - &commit_current.value.fencing, - "commit fencing evidence", - )?) => - { - IncumbentCleanupEvidence::Complete { - generation_id: incumbent.value.generation_id.clone(), - } - } - Some(incumbent) => IncumbentCleanupEvidence::Pending { - generation_id: incumbent.value.generation_id.clone(), - workload: incumbent.value.workload.clone(), - }, - None => IncumbentCleanupEvidence::SkippedNoIncumbent, - }, - source: match commit_current.value.command_kind { - CommandKind::Deploy => SourceCleanupEvidence::Pending, - CommandKind::Continuity => SourceCleanupEvidence::SkippedContinuity, - }, - }; - let mut complete = commit_current.value.clone(); - complete.phase = DeploymentPhase::Complete; - complete.updated_at_unix_millis = now; - complete.last_error = None; - complete.completion = Some(TransactionCompletion::Admitted { - generation_id: generation.generation_id.clone(), - }); - complete.post_commit_cleanup = Some(post_commit_cleanup); - complete.validate()?; - - let admitted_expected = CultCacheExpectedEnvelope { - r#type: AdmittedGeneration::TYPE.into(), - key: generation.target.clone(), - current: incumbent.map(|stored| stored.envelope.clone()), - }; - ensure!( - SingleFileMessagePackBackingStore::new(&self.options.state_store).compare_exchange( - &[ - CultCacheExpectedEnvelope { - r#type: DeploymentTransaction::TYPE.into(), - key: commit_current.value.transaction_id.clone(), - current: Some(commit_current.envelope.clone()), - }, - admitted_expected, - ], - &[ - transaction_envelope(&complete, now)?, - admitted_envelope(&generation, now)?, - ], - )?, - "incumbent or transaction changed before atomic admission commit" - ); - Ok(()) - } - - fn exact_incumbent<'a>( - &self, - snapshot: &'a ControlSnapshot, - transaction: &DeploymentTransaction, - ) -> Result>> { - let current = snapshot.admitted_for(&transaction.target); - match (&transaction.incumbent_generation_id, current) { - (None, None) => Ok(None), - (Some(expected), Some(current)) if current.value.generation_id == *expected => { - Ok(Some(current)) - } - _ => bail!("target incumbent changed after transaction creation"), - } - } - - fn incumbent_lease_sha256_for_warming( - &self, - snapshot: &ControlSnapshot, - transaction: &DeploymentTransaction, - ) -> Result> { - if let Some(fencing) = &transaction.fencing { - return match fencing { - FencingEvidence::SkippedStateless => Ok(None), - FencingEvidence::Revoked { - incumbent_lease_sha256, - .. - } => Ok(incumbent_lease_sha256.clone()), - }; - } - self.exact_incumbent(snapshot, transaction)? - .and_then(|incumbent| incumbent.value.leasing.lease()) - .map(IdunnProcessWriteLeaseRecord::canonical_sha256) - .transpose() - } - - fn fresh_warming_for_lease( - &self, - current: &Stored, - now: u64, - ) -> Result< - Option<( - Stored, - WarmingEvidence, - SequenceAdmittedWarming, - )>, - > { - let prior = self.rehydrate_warming_token(¤t.value, now, false)?; - match required(¤t.value.warming, "pre-fence Warming evidence")?.clone() { - WarmingEvidence::FirstOdinDirect { .. } => { - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - ensure!( - snapshot.admitted_for("odin").is_none() - && self.exact_incumbent(&snapshot, ¤t.value)?.is_none(), - "direct first-Odin Warming refresh found an admitted Odin" - ); - let (evidence, present) = self.observe_first_odin_warming(¤t.value)?; - let token = SequenceAdmittedWarming::from_first_odin_presence( - current.value.transaction_id.clone(), - evidence.clone(), - present, - )?; - ensure!( - token.signed_presence_sha256() != prior.signed_presence_sha256(), - "first Odin replayed its pre-fence Warming presence" - ); - Ok(Some(( - current.clone(), - WarmingEvidence::FirstOdinDirect { evidence }, - token, - ))) - } - WarmingEvidence::OdinTopology { - evidence: prior_evidence, - } => { - let Some((admitted, authenticated)) = self.admit_latest_topology(current, None)? - else { - return Ok(None); - }; - let fresh_evidence = required( - &admitted.value.latest_odin_observation, - "post-fence Odin Warming observation", - )? - .clone(); - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let incumbent_lease_sha256 = - self.incumbent_lease_sha256_for_warming(&snapshot, &admitted.value)?; - if !is_semantic_warming( - required(&admitted.value.expected, "Warming Expected projection")?, - required(&admitted.value.activation, "Warming activation")?, - incumbent_lease_sha256.as_deref(), - &authenticated, - )? { - return Ok(None); - } - let token = SequenceAdmittedWarming::from_topology( - admitted.value.transaction_id.clone(), - fresh_evidence.clone(), - authenticated, - )?; - if !provider_warming_advanced( - prior_evidence.publisher_sequence, - prior.signed_presence_sha256(), - fresh_evidence.publisher_sequence, - token.signed_presence_sha256(), - ) { - return Ok(None); - } - Ok(Some(( - admitted, - WarmingEvidence::OdinTopology { - evidence: fresh_evidence, - }, - token, - ))) - } - } - } - - fn prepare_candidate_write_lease( - &self, - transaction: &DeploymentTransaction, - warming: &SequenceAdmittedWarming, - now: u64, - ) -> Result { - let expected = required(&transaction.expected, "Expected projection")?; - let activation = required(&transaction.activation, "activation")?; - ensure!( - expected.write_lease_required - && warming.transaction_id() == transaction.transaction_id - && warming.runtime_instance_id() == activation.runtime_instance_id, - "fresh Warming token does not own this stateful candidate" - ); - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let epoch = self - .exact_incumbent(&snapshot, transaction)? - .and_then(|generation| generation.value.leasing.lease()) - .map_or(1, |lease| lease.lease_epoch.saturating_add(1)); - let lease = IdunnProcessWriteLeaseRecord { - schema_version: IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into(), - target: expected.target.clone(), - expected_projection_sha256: expected.canonical_sha256()?, - plan_id: expected.plan_id.clone(), - incarnation_id: expected.incarnation_id.clone(), - sealed_release_id: expected.sealed_release_id.clone(), - activation_witness_sha256: activation.canonical_sha256()?, - state_schema_generation: expected - .state_schema_generation - .clone() - .context("stateful Expected has no schema generation")?, - state_contract_sha256: expected - .state_contract_sha256 - .clone() - .context("stateful Expected has no state contract")?, - runtime_id: expected.runtime_id.clone(), - runtime_instance_id: activation.runtime_instance_id.clone(), - warming_presence_sha256: warming.signed_presence_sha256().to_owned(), - lease_epoch: epoch, - issued_at_unix_millis: now, - }; - lease.validate()?; - Ok(lease) - } - - fn ensure_transaction_write_lease_current( - &self, - transaction: &DeploymentTransaction, - now: u64, - ) -> Result<()> { - let expected = required(&transaction.expected, "Expected projection")?; - let lease = transaction - .leasing - .as_ref() - .and_then(LeasingEvidence::lease); - ensure!( - expected.write_lease_required == lease.is_some(), - "transaction write-lease disposition differs from Expected" - ); - let Some(lease) = lease else { - return Ok(()); - }; - let activation = required(&transaction.activation, "activation")?; - let warming = self.rehydrate_warming_token(transaction, now, false)?; - let lease_path = required(&transaction.plan, "transaction plan")? - .parsed_inputs()? - .1 - .process_write_lease - .context("stateful target has no write-lease binding")? - .record_path; - ensure!( - CultCacheWriteLeaseDriver::new(&transaction.target, lease_path) - .observe(expected, activation, &warming, lease,)?, - "process write lease changed across the authority boundary" - ); - Ok(()) - } - - fn select_candidate_port(&self, binding: &OperatorBinding) -> Result> { - let Some(route) = &binding.route else { - return Ok(None); - }; - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let mut used = BTreeSet::new(); - for plan in snapshot - .admitted - .iter() - .map(|stored| &stored.value.plan) - .chain( - snapshot - .transactions - .iter() - .filter(|stored| stored.value.blocks_new_target_mutation()) - .filter_map(|stored| stored.value.plan.as_ref()), - ) - { - if let Some(port) = plan.candidate_port { - used.insert(port); - } - } - (route.private_port_start..=route.private_port_end) - .find(|port| !used.contains(port)) - .map(Some) - .context("no private candidate port remains in the operator range") - } - - fn deployment_authorization( - &self, - current: &Stored, - now: u64, - ) -> Result> { - let expected = required(¤t.value.expected, "Expected projection")?; - let plan = required(¤t.value.plan, "transaction plan")?; - let binding = plan.parsed_inputs()?.1; - let Some((record, canonical_bytes)) = - read_deployment_brake(&binding.brakes.deployment_store)? - else { - return Ok(None); - }; - let anchor = read_trust_anchor::( - &self.options.deployment_brake_operator_anchor, - )?; - if evaluate_idunn_deployment_brake( - IdunnDeploymentBrakeObservation::Present(&record), - &anchor, - &expected.runtime_id, - &expected.sealed_release_id, - ¤t.value.transaction_id, - now, - ) - .is_err() - { - return Ok(None); - } - let authorization_id = record - .authorization_id - .clone() - .context("released brake has no authorization id")?; - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - ensure!( - !snapshot.transactions.iter().any(|stored| { - stored - .value - .deployment_authorization - .as_ref() - .is_some_and(|used| used.authorization_id == authorization_id) - }), - "deployment authorization was already consumed" - ); - Ok(Some(DeploymentAuthorization { - authorization_id, - brake_sha256: sha256_id(&canonical_bytes), - canonical_brake_bytes: canonical_bytes, - authorized_at_unix_millis: now, - })) - } - - fn lifecycle_allows(&self, current: &Stored, now: u64) -> Result { - let plan = required(¤t.value.plan, "continuity plan")?; - let binding = plan.parsed_inputs()?.1; - let expected = required(¤t.value.expected, "continuity Expected")?; - match read_lifecycle_brake(&binding.brakes.lifecycle_store) { - Ok(Some(record)) => Ok(evaluate_idunn_continuity_restart( - IdunnLifecycleBrakeObservation::Present(&record), - &expected.runtime_id, - ¤t.value.target, - now, - ) - .is_ok()), - Ok(None) => Ok(evaluate_idunn_continuity_restart( - IdunnLifecycleBrakeObservation::Missing, - &expected.runtime_id, - ¤t.value.target, - now, - ) - .is_ok()), - Err(_) => Ok(false), - } - } - - fn record_gate_wait( - &self, - current: &Stored, - detail: &str, - ) -> Result<()> { - if current.value.last_error.as_deref() == Some(detail) { - return Ok(()); - } - let mut next = current.value.clone(); - next.last_error = Some(detail.into()); - next.updated_at_unix_millis = now_millis()?; - replace_transaction(&self.options.state_store, current, &next) - } - - fn runtime_authority( - &self, - transaction: &DeploymentTransaction, - ) -> Result { - self.runtime_authority_parts( - required(&transaction.plan, "transaction plan")?, - required(&transaction.expected, "Expected projection")?, - required(&transaction.activation, "activation")?, - ) - } - - fn authenticate_routed_presence( - &self, - authority: &cultnet_rs::VerifiedRuntimeAuthority, - current_write_lease_sha256: Option<&str>, - message_id: &str, - challenged_at_unix_millis: u64, - received_at_unix_millis: u64, - canonical_presence: &[u8], - ) -> Result<(String, u64)> { - ensure!( - received_at_unix_millis >= challenged_at_unix_millis, - "route observation predates its challenge" - ); - let authenticated = authenticate_runtime_presence_claim( - canonical_presence, - authority, - RuntimePresenceAuthenticationContext { - trusted_received_at_unix_millis: received_at_unix_millis, - maximum_age_millis: self.options.topology_maximum_age_millis, - maximum_future_skew_millis: self.options.topology_maximum_future_skew_millis, - }, - )?; - let signed_presence_sha256 = authenticated.signed_presence_sha256().to_owned(); - let correlation = correlate_runtime_presence_claim(authenticated, authority)?; - ensure!( - correlation.disagreements().is_empty(), - "stable route answered with a runtime that disagrees with current authority" - ); - let present = correlation.into_undisputed_present()?; - let presence = present.record(); - ensure!( - presence.observed_at_unix_millis >= challenged_at_unix_millis, - "stable route returned a presence minted before the route challenge" - ); - ensure!( - presence.state == "active", - "stable route runtime is not Active" - ); - ensure!( - presence.detail == format!("route-observation:{message_id}"), - "stable route response is not bound to the exact challenge" - ); - ensure!( - presence.write_lease_sha256.as_deref() == current_write_lease_sha256, - "stable route runtime does not hold the exact current process write lease" - ); - Ok((signed_presence_sha256, received_at_unix_millis)) - } - - fn authenticate_first_odin_warming_presence( - &self, - transaction: &DeploymentTransaction, - message_id: &str, - challenged_at_unix_millis: u64, - received_at_unix_millis: u64, - canonical_presence: &[u8], - ) -> Result { - ensure!( - transaction.target == "odin" - && transaction.incumbent_generation_id.is_none() - && required(&transaction.expected, "first Odin Expected")?.write_lease_required, - "direct Warming presence is reserved for stateful first Odin bootstrap" - ); - ensure!( - received_at_unix_millis >= challenged_at_unix_millis, - "first Odin Warming observation predates its challenge" - ); - let authority = self.runtime_authority(transaction)?; - let authenticated = authenticate_runtime_presence_claim( - canonical_presence, - &authority, - RuntimePresenceAuthenticationContext { - trusted_received_at_unix_millis: received_at_unix_millis, - maximum_age_millis: self.options.topology_maximum_age_millis, - maximum_future_skew_millis: self.options.topology_maximum_future_skew_millis, - }, - )?; - let correlation = correlate_runtime_presence_claim(authenticated, &authority)?; - ensure!( - correlation.disagreements().is_empty(), - "first Odin Warming presence disagrees with its Expected activation" - ); - let present = correlation.into_undisputed_present()?; - let presence = present.record(); - ensure!( - presence.observed_at_unix_millis >= challenged_at_unix_millis - && presence.state == "warming" - && presence.write_lease_sha256.is_none() - && presence.detail == format!("idunn-warming:{message_id}"), - "first Odin candidate did not return exact fresh pre-lease Warming evidence" - ); - Ok(present) - } - - fn observe_first_odin_warming( - &self, - transaction: &DeploymentTransaction, - ) -> Result<(RuntimePresenceEvidence, cultnet_rs::VerifiedRuntimePresence)> { - let expected = required(&transaction.expected, "first Odin Expected")?; - let binding = required(&transaction.plan, "first Odin plan")? - .parsed_inputs()? - .1; - let driver = NginxRouteDriver::new( - binding - .route - .context("first Odin bootstrap has no candidate route binding")?, - ); - let message_id = format!("warming-{}", Uuid::new_v4().simple()); - let challenged_at_unix_millis = now_millis()?; - let response = driver.request_candidate_runtime_presence(expected, &message_id)?; - ensure!( - response.message_id == message_id, - "first Odin candidate transport substituted its challenge identity" - ); - let admitted_at_unix_millis = now_millis()?; - let present = self.authenticate_first_odin_warming_presence( - transaction, - &message_id, - challenged_at_unix_millis, - admitted_at_unix_millis, - &response.canonical_presence, - )?; - let evidence = RuntimePresenceEvidence::from_present( - &present, - message_id, - challenged_at_unix_millis, - admitted_at_unix_millis, - )?; - Ok((evidence, present)) - } - - fn prove_stable_route( - &self, - transaction: &DeploymentTransaction, - driver: &NginxRouteDriver, - membership_sha256: String, - ) -> Result { - let expected = required(&transaction.expected, "route Expected projection")?; - let activation = required(&transaction.activation, "route activation")?; - let authority = self.runtime_authority(transaction)?; - let current_write_lease_sha256 = transaction - .leasing - .as_ref() - .and_then(LeasingEvidence::lease_sha256); - self.prove_stable_route_against( - expected, - activation, - &authority, - current_write_lease_sha256, - driver, - membership_sha256, - ) - } - - fn prove_stable_route_against( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - authority: &cultnet_rs::VerifiedRuntimeAuthority, - current_write_lease_sha256: Option<&str>, - driver: &NginxRouteDriver, - membership_sha256: String, - ) -> Result { - let message_id = format!("route-{}", Uuid::new_v4().simple()); - let challenged_at_unix_millis = now_millis()?; - let response = driver.request_runtime_presence(expected, &message_id)?; - ensure!( - response.message_id == message_id, - "route transport substituted its challenge identity" - ); - let received_at_unix_millis = now_millis()?; - let (signed_presence_sha256, observed_at_unix_millis) = self.authenticate_routed_presence( - authority, - current_write_lease_sha256, - &message_id, - challenged_at_unix_millis, - received_at_unix_millis, - &response.canonical_presence, - )?; - let observation = RouteObservation { - route_id: driver.binding.route_id.clone(), - runtime_instance_id: activation.runtime_instance_id.clone(), - membership_sha256, - signed_presence_sha256, - observed_at_unix_millis, - }; - observation.validate()?; - Ok(observation) - } - - fn runtime_authority_parts( - &self, - plan: &CompiledDeploymentPlan, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result { - let provider_anchor = self.provider_anchor_for_plan(plan)?; - verify_runtime_authority( - expected, - activation, - &self.idunn_anchor, - &provider_anchor.public_key, - ) - } - - fn provider_anchor_for_plan( - &self, - plan: &CompiledDeploymentPlan, - ) -> Result { - let binding = plan.parsed_inputs()?.1; - let provider_anchor = read_trust_anchor::( - &binding.runtime_identity.trust_anchor_store, - )?; - ensure!( - provider_anchor.schema_version - == ::TRUST_ANCHOR_SCHEMA, - "provider runtime presence trust anchor schema is unsupported" - ); - Ok(provider_anchor) - } - - fn authenticate_topology_bytes( - &self, - snapshot: &ControlSnapshot, - transaction: &DeploymentTransaction, - canonical_bytes: &[u8], - current_write_lease_sha256: Option<&str>, - trusted_received_at: u64, - ) -> Result { - let authority = self.runtime_authority(transaction)?; - let odin_authority = self.current_odin_authority(snapshot)?; - authenticate_odin_runtime_topology_correlation( - canonical_bytes, - &authority, - current_write_lease_sha256, - &odin_authority.signer_public_key, - self.trusted_topology_context(trusted_received_at), - ) - } - - /// Persist every newly authenticated publisher sequence before deciding - /// whether it means Warming, Ready, degraded, or disagreement. - fn admit_latest_topology( - &self, - current: &Stored, - current_write_lease_sha256: Option<&str>, - ) -> Result< - Option<( - Stored, - AuthenticatedOdinRuntimeTopologyCorrelation, - )>, - > { - let Some(received) = self.topology().receive(¤t.value.target)? else { - return Ok(None); - }; - ensure!( - received.target == current.value.target, - "topology transport substituted target" - ); - let now = now_millis()?; - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let live = snapshot - .transactions - .iter() - .find(|stored| stored.value.transaction_id == current.value.transaction_id) - .context("transaction disappeared before topology admission")?; - ensure!( - live.envelope == current.envelope, - "transaction changed before topology admission" - ); - let authenticated = self.authenticate_topology_bytes( - &snapshot, - &live.value, - &received.canonical_bytes, - current_write_lease_sha256, - now, - )?; - let evidence = TopologyEvidence::from_authenticated(&authenticated, now)?; - if !sequence_requires_admission( - live.value.latest_odin_observation.as_ref(), - snapshot.max_odin_sequence(&live.value.target, &evidence.signer_identity_id), - &evidence, - )? { - return Ok(Some((live.clone(), authenticated))); - } - let mut next = live.value.clone(); - next.latest_odin_observation = Some(evidence.clone()); - next.odin_publisher_sequence_cursor = evidence.publisher_sequence; - next.updated_at_unix_millis = now; - next.last_error = None; - replace_transaction(&self.options.state_store, live, &next)?; - let admitted = ControlSnapshot::read(&self.options.state_store)? - .transactions - .into_iter() - .find(|stored| stored.value.transaction_id == next.transaction_id) - .context("sequence-admitted transaction disappeared")?; - ensure!( - admitted.value.latest_odin_observation.as_ref() == Some(&evidence) - && admitted.value.odin_publisher_sequence_cursor == evidence.publisher_sequence, - "topology sequence was not durably admitted" - ); - Ok(Some((admitted, authenticated))) - } - - fn rehydrate_warming_token( - &self, - transaction: &DeploymentTransaction, - now: u64, - require_current: bool, - ) -> Result { - let evidence = required(&transaction.warming, "durable warming evidence")?.clone(); - match evidence { - WarmingEvidence::OdinTopology { evidence } => { - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let authenticated = self.authenticate_topology_bytes( - &snapshot, - transaction, - &evidence.canonical_bytes, - None, - if require_current { - now - } else { - evidence.admitted_at_unix_millis - }, - )?; - validate_authenticated_evidence(&evidence, &authenticated)?; - let incumbent_lease_sha256 = - self.incumbent_lease_sha256_for_warming(&snapshot, transaction)?; - ensure!( - is_semantic_warming( - required(&transaction.expected, "Warming Expected projection")?, - required(&transaction.activation, "Warming activation")?, - incumbent_lease_sha256.as_deref(), - &authenticated, - )?, - "durable warming evidence no longer satisfies the Warming gate" - ); - SequenceAdmittedWarming::from_topology( - transaction.transaction_id.clone(), - evidence, - authenticated, - ) - } - WarmingEvidence::FirstOdinDirect { evidence } => { - let present = self.authenticate_first_odin_warming_presence( - transaction, - &evidence.message_id, - evidence.challenged_at_unix_millis, - if require_current { - now - } else { - evidence.admitted_at_unix_millis - }, - &evidence.canonical_bytes, - )?; - SequenceAdmittedWarming::from_first_odin_presence( - transaction.transaction_id.clone(), - evidence, - present, - ) - } - } - } - - fn rehydrate_ready_token( - &self, - transaction: &DeploymentTransaction, - now: u64, - require_current: bool, - ) -> Result { - let evidence = required(&transaction.ready, "durable Ready evidence")?.clone(); - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let current_lease = transaction - .leasing - .as_ref() - .and_then(LeasingEvidence::lease_sha256); - let authenticated = self.authenticate_topology_bytes( - &snapshot, - transaction, - &evidence.canonical_bytes, - current_lease, - if require_current { - now - } else { - evidence.admitted_at_unix_millis - }, - )?; - validate_authenticated_evidence(&evidence, &authenticated)?; - ensure!( - is_semantic_ready(&authenticated), - "durable Ready evidence no longer authenticates as Ready" - ); - Ok(SequenceAdmittedReady { - transaction_id: transaction.transaction_id.clone(), - evidence, - expected: required(&transaction.expected, "Expected projection")?.clone(), - authenticated, - }) - } - - fn current_ready_provider_tokens( - &self, - snapshot: &ControlSnapshot, - now: u64, - ) -> Result> { - let mut providers = Vec::new(); - for stored in &snapshot.admitted { - if stored.value.latest_odin_observation != stored.value.ready { - continue; - } - match self.rehydrate_admitted_ready(snapshot, &stored.value, now) { - Ok(provider) => providers.push(provider), - Err(error) => eprintln!( - "Idunn excluded non-current provider {}: {error:#}", - stored.value.target - ), - } - } - Ok(providers) - } - - fn rehydrate_admitted_ready( - &self, - snapshot: &ControlSnapshot, - generation: &AdmittedGeneration, - now: u64, - ) -> Result { - ensure!( - generation.latest_odin_observation == generation.ready, - "admitted provider latest topology is not Ready" - ); - let authority = self.runtime_authority_parts( - &generation.plan, - &generation.expected, - &generation.activation, - )?; - let odin_authority = self.current_odin_authority(snapshot)?; - let current_lease = generation.leasing.lease_sha256(); - let authenticated = authenticate_odin_runtime_topology_correlation( - &generation.ready.canonical_bytes, - &authority, - current_lease, - &odin_authority.signer_public_key, - self.trusted_topology_context(now), - )?; - validate_authenticated_evidence(&generation.ready, &authenticated)?; - ensure!( - is_semantic_ready(&authenticated), - "admitted provider no longer has current exact Ready evidence" - ); - Ok(SequenceAdmittedReady { - transaction_id: generation.transaction_id.clone(), - evidence: generation.ready.clone(), - expected: generation.expected.clone(), - authenticated, - }) - } - - fn validate_selected_providers_current( - &self, - plan: &CompiledDeploymentPlan, - now: u64, - ) -> Result<()> { - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - for selection in &plan.dependencies { - let Some(provider) = &selection.provider else { - ensure!( - selection.requirement.kind == DependencyKind::Optional, - "required dependency has no provider" - ); - continue; - }; - let DependencyProviderAuthority::ManagedReady { - target, - incarnation_id, - plan_id, - sealed_release_id, - expected_projection_sha256, - odin_topology_correlation_sha256, - odin_topology_publisher_sequence, - } = &provider.authority - else { - continue; - }; - let admitted = snapshot - .admitted_for(target) - .context("selected managed dependency is no longer admitted")?; - let token = self.rehydrate_admitted_ready(&snapshot, &admitted.value, now)?; - ensure!( - admitted.value.expected.incarnation_id == *incarnation_id - && admitted.value.plan.plan_id == *plan_id - && admitted.value.sealed_release.sealed_release_id == *sealed_release_id - && admitted.value.expected.canonical_sha256()? == *expected_projection_sha256 - && token.publisher_sequence() >= *odin_topology_publisher_sequence, - "selected dependency authority changed before actuation" - ); - ensure!( - token.publisher_sequence() != *odin_topology_publisher_sequence - || token.evidence_sha256() == odin_topology_correlation_sha256, - "selected dependency Odin sequence changed evidence" - ); - ensure!( - token - .authenticated() - .record() - .observed_capabilities - .iter() - .any(|capability| { - capability_compatible( - &selection.requirement.capability, - &selection.requirement.schema, - &selection.requirement.compatibility, - &capability.capability, - &capability.schema, - &capability.compatibility, - ) && capability.capacity >= selection.requirement.minimum_capacity - }), - "selected dependency no longer provides its required capability" - ); - } - Ok(()) - } - - fn persist_same_phase( - &self, - current: &Stored, - mutation: F, - ) -> Result<()> - where - F: FnOnce(&mut DeploymentTransaction) -> Result<()>, - { - let mut next = current.value.clone(); - mutation(&mut next)?; - ensure!( - next.phase == current.value.phase, - "same-phase evidence update changed phase" - ); - next.updated_at_unix_millis = now_millis()?; - next.last_error = None; - replace_transaction(&self.options.state_store, current, &next) - } - - fn transition( - &self, - current: &Stored, - next_phase: DeploymentPhase, - ) -> Result<()> { - ensure!( - next_phase as u8 == current.value.phase as u8 + 1, - "deployment phase transition is not adjacent" - ); - let mut next = current.value.clone(); - next.phase = next_phase; - next.updated_at_unix_millis = now_millis()?; - next.last_error = None; - replace_transaction(&self.options.state_store, current, &next) - } - - fn record_resumable_error( - &self, - current: &Stored, - error: &anyhow::Error, - ) -> Result<()> { - let detail = truncate(&format!("{error:#}"), 2048); - if current.value.last_error.as_deref() == Some(detail.as_str()) { - return Ok(()); - } - let mut next = current.value.clone(); - next.last_error = Some(detail); - next.updated_at_unix_millis = now_millis()?; - replace_transaction(&self.options.state_store, current, &next) - } - - fn begin_pre_fencing_abort( - &self, - current: &Stored, - error: anyhow::Error, - ) -> Result<()> { - ensure!( - current.value.phase < DeploymentPhase::Fencing, - "post-fence transaction cannot terminal-fail" - ); - ensure!( - current.value.pre_fencing_abort.is_none(), - "pre-fencing abort intent is already durable" - ); - let abort = PreFencingAbort { - error: truncate(&format!("{error:#}"), 2048), - candidate_cleanup: candidate_cleanup_requirement( - current.value.activation.is_some(), - current.value.workload.is_some(), - ), - topology_reconciliation: if current.value.command_kind == CommandKind::Deploy - && current.value.expected_publication_sha256.is_some() - { - CleanupEvidence::Pending - } else { - CleanupEvidence::Skipped - }, - source_cleanup: if current.value.command_kind == CommandKind::Deploy { - CleanupEvidence::Pending - } else { - CleanupEvidence::Skipped - }, - }; - self.persist_same_phase(current, |next| { - next.pre_fencing_abort = Some(abort); - Ok(()) - }) - } - - fn advance_pre_fencing_abort(&self, current: &Stored) -> Result<()> { - ensure!( - current.value.phase < DeploymentPhase::Fencing, - "pre-fencing abort crossed the fencing boundary" - ); - let abort = required(¤t.value.pre_fencing_abort, "pre-fencing abort intent")?; - if abort.candidate_cleanup == CleanupEvidence::Pending { - if let Some(workload) = ¤t.value.workload { - self.workload - .stop(workload) - .context("stopping exact pre-fence candidate")?; - } - self.workload - .discard_prepared( - required(¤t.value.plan, "pre-fencing candidate plan")?, - required(¤t.value.expected, "pre-fencing Expected projection")?, - required(¤t.value.activation, "pre-fencing activation")?, - ) - .context("discarding exact pre-fence activation material")?; - return self.persist_same_phase(current, |next| { - next.pre_fencing_abort.as_mut().unwrap().candidate_cleanup = - CleanupEvidence::Complete; - Ok(()) - }); - } - if abort.topology_reconciliation == CleanupEvidence::Pending { - let expected = required(¤t.value.expected, "failed Expected projection")?; - let snapshot = ControlSnapshot::read(&self.options.state_store)?; - if let Some(incumbent) = self.exact_incumbent(&snapshot, ¤t.value)? { - let topology = self.topology(); - let failed_provider_anchor = self.provider_anchor_for_plan(required( - ¤t.value.plan, - "failed transaction plan", - )?)?; - let admitted_provider_anchor = - self.provider_anchor_for_plan(&incumbent.value.plan)?; - let expected_sha256 = topology.restore_admitted_expected_only( - expected, - &failed_provider_anchor, - current.value.activation.as_ref(), - &incumbent.value.expected, - &admitted_provider_anchor, - &incumbent.value.activation, - incumbent.value.leasing.lease(), - )?; - ensure!( - expected_sha256 == incumbent.value.expected.canonical_sha256()?, - "restored incumbent Expected receipt differs" - ); - } else { - let plan = required(¤t.value.plan, "failed transaction plan")?; - let provider_anchor = self.provider_anchor_for_plan(plan)?; - self.topology() - .withdraw_expected( - expected, - &provider_anchor, - current.value.activation.as_ref(), - None, - ) - .context("withdrawing exact failed Expected projection")?; - } - return self.persist_same_phase(current, |next| { - next.pre_fencing_abort - .as_mut() - .unwrap() - .topology_reconciliation = CleanupEvidence::Complete; - Ok(()) - }); - } - if abort.source_cleanup == CleanupEvidence::Pending { - self.source - .cleanup( - ¤t.value.transaction_id, - current.value.frozen_source.as_ref(), - ) - .context("cleaning failed pre-fence source")?; - return self.persist_same_phase(current, |next| { - next.pre_fencing_abort.as_mut().unwrap().source_cleanup = CleanupEvidence::Complete; - Ok(()) - }); - } - ensure!( - abort.is_complete(), - "pre-fencing abort cleanup is incomplete" - ); - let mut next = current.value.clone(); - next.phase = DeploymentPhase::Complete; - next.updated_at_unix_millis = now_millis()?; - next.last_error = Some(abort.error.clone()); - next.completion = Some(TransactionCompletion::FailedBeforeFencing { - error: abort.error.clone(), - }); - replace_transaction(&self.options.state_store, current, &next) - } - - fn advance_post_commit_cleanup(&self, current: &Stored) -> Result<()> { - let cleanup = required( - ¤t.value.post_commit_cleanup, - "post-commit cleanup evidence", - )?; - if let IncumbentCleanupEvidence::Pending { - generation_id, - workload, - } = &cleanup.incumbent - { - let binding = required(¤t.value.plan, "committed transaction plan")? - .parsed_inputs()? - .1; - if let Some(promoted_at_unix_millis) = required( - ¤t.value.routing, - "committed transaction routing evidence", - )? - .promoted_at_unix_millis() - { - let retire_not_before = - route_drain_deadline(promoted_at_unix_millis, binding.rollout.drain_seconds)?; - if now_millis()? < retire_not_before { - return Ok(()); - } - } - self.workload - .stop(workload) - .with_context(|| format!("retiring admitted incumbent {generation_id}"))?; - let generation_id = generation_id.clone(); - return self.persist_same_phase(current, |next| { - next.post_commit_cleanup.as_mut().unwrap().incumbent = - IncumbentCleanupEvidence::Complete { generation_id }; - Ok(()) - }); - } - if cleanup.source == SourceCleanupEvidence::Pending { - self.source - .cleanup( - ¤t.value.transaction_id, - current.value.frozen_source.as_ref(), - ) - .context("cleaning committed deployment source")?; - return self.persist_same_phase(current, |next| { - next.post_commit_cleanup.as_mut().unwrap().source = SourceCleanupEvidence::Complete; - Ok(()) - }); - } - ensure!(cleanup.is_complete(), "post-commit cleanup is incomplete"); - Ok(()) - } -} - -fn route_drain_deadline(promoted_at_unix_millis: u64, drain_seconds: u32) -> Result { - promoted_at_unix_millis - .checked_add( - u64::from(drain_seconds) - .checked_mul(1_000) - .context("route drain duration overflows milliseconds")?, - ) - .context("route drain deadline overflows Unix milliseconds") -} - -fn route_observation_is_current( - observed_at_unix_millis: u64, - now_unix_millis: u64, - maximum_age_millis: u64, - maximum_future_skew_millis: u64, -) -> bool { - observed_at_unix_millis <= now_unix_millis.saturating_add(maximum_future_skew_millis) - && now_unix_millis.saturating_sub(observed_at_unix_millis) <= maximum_age_millis -} - -fn provider_warming_advanced( - prior_odin_sequence: u64, - prior_signed_presence_sha256: &str, - candidate_odin_sequence: u64, - candidate_signed_presence_sha256: &str, -) -> bool { - candidate_odin_sequence > prior_odin_sequence - && candidate_signed_presence_sha256 != prior_signed_presence_sha256 -} - -fn may_rollback_route_after_failed_proof(fencing: &FencingEvidence) -> bool { - matches!(fencing, FencingEvidence::SkippedStateless) -} - -fn incumbent_was_stopped_during_fencing(fencing: &FencingEvidence) -> bool { - matches!( - fencing, - FencingEvidence::Revoked { - incumbent_lease_sha256: Some(_), - .. - } - ) -} - -fn candidate_cleanup_requirement( - has_prepared_activation: bool, - has_workload_observation: bool, -) -> CleanupEvidence { - if has_prepared_activation || has_workload_observation { - CleanupEvidence::Pending - } else { - CleanupEvidence::Skipped - } -} - -fn prove_isolation( - candidate: &WorkloadObservation, - incumbent: Option<&WorkloadObservation>, -) -> Result { - ensure!( - candidate.dynamic_user - && candidate.private_pids - && candidate.private_mounts - && candidate.process_uids[0] > 0 - && candidate.pid_namespace_id > 0 - && candidate.mount_namespace_id > 0, - "candidate lacks dynamic identity or private namespaces" - ); - let evidence = if let Some(incumbent) = incumbent { - ensure!( - incumbent.dynamic_user - && incumbent.private_pids - && incumbent.private_mounts - && incumbent.process_uids[0] > 0 - && incumbent.pid_namespace_id > 0 - && incumbent.mount_namespace_id > 0, - "incumbent lacks admitted dynamic identity or private namespaces" - ); - ensure!( - candidate.process_uids[0] != incumbent.process_uids[0] - && candidate.pid_namespace_id != incumbent.pid_namespace_id - && candidate.mount_namespace_id != incumbent.mount_namespace_id, - "candidate and incumbent are not distinct by UID, PID namespace, and mount namespace" - ); - IsolationEvidence { - candidate_uid: candidate.process_uids[0], - candidate_pid_namespace_id: candidate.pid_namespace_id, - candidate_mount_namespace_id: candidate.mount_namespace_id, - incumbent_uid: Some(incumbent.process_uids[0]), - incumbent_pid_namespace_id: Some(incumbent.pid_namespace_id), - incumbent_mount_namespace_id: Some(incumbent.mount_namespace_id), - } - } else { - IsolationEvidence { - candidate_uid: candidate.process_uids[0], - candidate_pid_namespace_id: candidate.pid_namespace_id, - candidate_mount_namespace_id: candidate.mount_namespace_id, - incumbent_uid: None, - incumbent_pid_namespace_id: None, - incumbent_mount_namespace_id: None, - } - }; - Ok(evidence) -} - -fn sequence_requires_admission( - latest: Option<&TopologyEvidence>, - maximum_admitted_sequence: u64, - candidate: &TopologyEvidence, -) -> Result { - candidate.validate_shape()?; - if latest.is_some_and(|existing| { - existing.canonical_bytes == candidate.canonical_bytes - && existing.canonical_sha256 == candidate.canonical_sha256 - && existing.signer_identity_id == candidate.signer_identity_id - && existing.publisher_sequence == candidate.publisher_sequence - }) { - return Ok(false); - } - ensure!( - candidate.publisher_sequence > maximum_admitted_sequence, - "Odin topology publisher sequence was replayed or reordered" - ); - Ok(true) -} - -fn validate_live_providers_for_deploy(command_kind: CommandKind, validation: F) -> Result<()> -where - F: FnOnce() -> Result<()>, -{ - match command_kind { - CommandKind::Deploy => validation(), - CommandKind::Continuity => Ok(()), - } -} - -fn validate_authenticated_evidence( - evidence: &TopologyEvidence, - authenticated: &AuthenticatedOdinRuntimeTopologyCorrelation, -) -> Result<()> { - let record = authenticated.record(); - ensure!( - authenticated.canonical_bytes() == evidence.canonical_bytes.as_slice() - && sha256_id(authenticated.canonical_bytes()) == evidence.canonical_sha256 - && record.signer_identity_id == evidence.signer_identity_id - && record.publisher_sequence == evidence.publisher_sequence, - "durable topology evidence differs from its authenticated receipt" - ); - Ok(()) -} - -fn is_semantic_warming( - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - incumbent_lease_sha256: Option<&str>, - authenticated: &AuthenticatedOdinRuntimeTopologyCorrelation, -) -> Result { - let record = authenticated.record(); - if !record.present || record.observed_write_lease_sha256.is_some() { - return Ok(false); - } - let expected_projection_detail = format!( - "expected:{};activation:{}", - expected.canonical_sha256()?, - activation.canonical_sha256()? - ); - if !warming_disagreements_match_incumbent( - &expected_projection_detail, - incumbent_lease_sha256, - &record.disagreements, - ) { - return Ok(false); - } - Ok(if expected.write_lease_required { - !record.ready && record.observed_presence_state.as_deref() == Some("warming") - } else { - matches!( - record.observed_presence_state.as_deref(), - Some("warming" | "active") - ) - }) -} - -fn warming_disagreements_match_incumbent( - expected_projection_detail: &str, - incumbent_lease_sha256: Option<&str>, - disagreements: &[OdinTopologyDisagreement], -) -> bool { - if disagreements.is_empty() { - true - } else if let (Some(incumbent_lease_sha256), [disagreement]) = - (incumbent_lease_sha256, disagreements) - { - disagreement.code == "projected-write-lease" - && disagreement.expected.as_deref() == Some(expected_projection_detail) - && disagreement.observed.as_deref() == Some(incumbent_lease_sha256) - } else { - false - } -} - -fn is_semantic_ready(authenticated: &AuthenticatedOdinRuntimeTopologyCorrelation) -> bool { - let record = authenticated.record(); - record.present - && record.ready - && record.observed_presence_state.as_deref() == Some("active") - && record.disagreements.is_empty() -} - -fn read_deployment_brake(path: &Path) -> Result)>> { - let Some(envelope) = read_single_envelope(path)? else { - return Ok(None); - }; - ensure!( - envelope.r#type == IdunnDeploymentBrakeRecord::TYPE - && envelope.schema_id.as_deref() == Some(IDUNN_DEPLOYMENT_BRAKE_SCHEMA), - "deployment brake store contains a foreign record" - ); - let record: IdunnDeploymentBrakeRecord = rmp_serde::from_slice(&envelope.payload)?; - record.validate()?; - ensure!( - rmp_serde::to_vec(&record)? == envelope.payload && envelope.key == record.brake_id, - "deployment brake is noncanonical or keyed by another authority" - ); - Ok(Some((record, envelope.payload))) -} - -fn read_lifecycle_brake(path: &Path) -> Result> { - let Some(envelope) = read_single_envelope(path)? else { - return Ok(None); - }; - ensure!( - envelope.r#type == IdunnLifecycleBrakeRecord::TYPE - && envelope.schema_id.as_deref() == Some(IDUNN_LIFECYCLE_BRAKE_SCHEMA), - "lifecycle brake store contains a foreign record" - ); - IdunnLifecycleBrakeRecord::decode_canonical(&envelope.payload).map(Some) -} - -fn read_single_envelope(path: &Path) -> Result> { - if !path.exists() { - return Ok(None); - } - let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; - match entries.as_slice() { - [] => Ok(None), - [entry] => Ok(Some(entry.clone())), - _ => bail!("single-record authority store is ambiguous"), - } -} - -fn read_trust_anchor(path: &Path) -> Result { - let envelope = read_single_envelope(path)? - .with_context(|| format!("service identity trust anchor {} is absent", path.display()))?; - ensure!( - envelope.r#type == P::TRUST_ANCHOR_TYPE - && envelope.key == P::TRUST_ANCHOR_KEY - && envelope.schema_id.as_deref() == Some(P::TRUST_ANCHOR_SCHEMA), - "service identity trust anchor belongs to another profile" - ); - let anchor: ServiceIdentityTrustAnchor = rmp_serde::from_slice(&envelope.payload)?; - ensure!( - rmp_serde::to_vec(&anchor)? == envelope.payload - && derive_service_identity_id::

(&anchor.public_key)? == anchor.identity_id, - "service identity trust anchor is noncanonical or self-inconsistent" - ); - Ok(anchor) -} - -fn required<'a, T>(value: &'a Option, label: &str) -> Result<&'a T> { - value.as_ref().with_context(|| format!("{label} is absent")) -} - -fn now_millis() -> Result { - Ok(SystemTime::now() - .duration_since(UNIX_EPOCH) - .context("system clock predates Unix epoch")? - .as_millis() - .try_into()?) -} - -fn rfc3339_millis(millis: u64) -> Result { - chrono::DateTime::from_timestamp_millis(i64::try_from(millis)?) - .context("timestamp is out of range") - .map(|value| value.to_rfc3339()) -} - -fn sibling_path(path: &Path, suffix: &str) -> PathBuf { - let mut value = path.as_os_str().to_os_string(); - value.push(suffix); - PathBuf::from(value) -} - -fn string_value(args: &mut impl Iterator, name: &str) -> Result { - args.next() - .ok_or_else(|| anyhow!("{name} requires a value")) -} - -fn path_value(args: &mut impl Iterator, name: &str) -> Result { - Ok(PathBuf::from(string_value(args, name)?)) -} - -fn u32_value(args: &mut impl Iterator, name: &str) -> Result { - string_value(args, name)? - .parse() - .with_context(|| format!("{name} requires a u32")) -} - -fn u64_value(args: &mut impl Iterator, name: &str) -> Result { - string_value(args, name)? - .parse() - .with_context(|| format!("{name} requires a u64")) -} - -fn require_selector(value: &str) -> Result<()> { - let value = value.strip_prefix("profile:").unwrap_or(value); - require_id(value, "deployment selector") -} - -fn require_id(value: &str, label: &str) -> Result<()> { - ensure!( - !value.is_empty() - && value.len() <= 256 - && value.bytes().all(|byte| { - byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/') - }), - "{label} is invalid" - ); - Ok(()) -} - -fn require_value(value: &str, label: &str) -> Result<()> { - ensure!( - !value.trim().is_empty() - && value == value.trim() - && value.len() <= 1024 - && !value.contains('\0'), - "{label} is invalid" - ); - Ok(()) -} - -fn require_detail(value: &str, label: &str) -> Result<()> { - ensure!( - !value.is_empty() && value.len() <= 2048 && !value.contains('\0'), - "{label} is invalid" - ); - Ok(()) -} - -fn truncate(value: &str, length: usize) -> String { - value.chars().take(length).collect() -} - -fn sha256_id(bytes: &[u8]) -> String { - let digest = Sha256::digest(bytes); - let mut encoded = String::with_capacity(71); - encoded.push_str("sha256-"); - for byte in digest { - use std::fmt::Write as _; - write!(&mut encoded, "{byte:02x}").expect("writing to String cannot fail"); - } - encoded -} - -fn runtime_instance_id(transaction_id: &str) -> Result { - require_id(transaction_id, "runtime transaction id")?; - Ok(sha256_id( - format!("gamecult.idunn.runtime-instance.v1:{transaction_id}").as_bytes(), - )) -} - -fn usage() -> &'static str { - "Idunn deployment, admission, and continuity control plane\n\n\ - idunn serve [runtime options]\n\ - idunn up [--state-store PATH] [--no-wait]\n\ - idunn status [--state-store PATH] [--command ID]\n\n\ - Recipes describe capability and process requirements. Idunn seals exact\n\ - source and artifacts, admits one incarnation, and delegates execution to\n\ - systemd and routing mechanics to the configured proxy." -} - -#[cfg(test)] -mod tests { - use super::*; - - fn digest(byte: char) -> String { - byte.to_string().repeat(64) - } - - fn route_binding( - route_id: &str, - stable_port: u16, - private_port_start: u16, - private_port_end: u16, - ) -> RouteBinding { - RouteBinding { - driver: crate::deployment::RouteDriver::NginxStreamTcp, - route_id: route_id.into(), - stable_endpoint: format!("tcp://127.0.0.1:{stable_port}"), - private_host: "127.0.0.1".into(), - private_port_start, - private_port_end, - config_path: PathBuf::from(format!("/etc/nginx/idunn-stream-routes/{route_id}.conf")), - reload_unit: "nginx.service".into(), - } - } - - fn command(kind: CommandKind) -> DeploymentCommand { - DeploymentCommand { - schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), - command_id: match kind { - CommandKind::Deploy => "up-test".into(), - CommandKind::Continuity => "continuity-test".into(), - }, - kind, - selector: "ghostlight".into(), - requested_by: "operator".into(), - requested_at_unix_millis: 100, - } - } - - fn topology(sequence: u64, byte: u8) -> TopologyEvidence { - let canonical_bytes = vec![byte]; - TopologyEvidence { - canonical_sha256: sha256_id(&canonical_bytes), - canonical_bytes, - signer_identity_id: "odin-signer".into(), - publisher_sequence: sequence, - admitted_at_unix_millis: 100, - } - } - - fn workload(uid: u32, pid_namespace_id: u64, mount_namespace_id: u64) -> WorkloadObservation { - WorkloadObservation { - unit: format!("idunn-{uid}.service"), - unit_description: format!("Idunn test {uid}"), - invocation_id: format!("invocation-{uid}"), - exec_main_start_timestamp_monotonic: 1, - service_type: "exec".into(), - restart_policy: "always".into(), - kill_mode: "control-group".into(), - dynamic_user: true, - systemd_user: format!("u{uid}"), - systemd_group: format!("u{uid}"), - supplementary_groups: String::new(), - capability_bounding_set: String::new(), - ambient_capabilities: String::new(), - private_mounts: true, - private_pids: true, - protect_proc: "invisible".into(), - proc_subset: "pid".into(), - no_new_privileges: true, - umask: "0077".into(), - inaccessible_paths: String::new(), - load_credential: String::new(), - main_pid: uid, - process_start_time: 1, - process_uids: [uid; 4], - process_gids: [uid; 4], - process_groups: vec![uid], - process_cap_inheritable: 0, - process_cap_permitted: 0, - process_cap_effective: 0, - process_cap_bounding: 0, - process_cap_ambient: 0, - process_no_new_privileges: true, - process_namespace_pids: vec![1], - mount_namespace_id, - pid_namespace_id, - executable: PathBuf::from("/opt/test/bin/service"), - executable_device: 1, - executable_inode: 1, - executable_sha256: sha256_id(&[1]), - runtime_instance_id: sha256_id(&uid.to_be_bytes()), - working_directory: PathBuf::from("/opt/test"), - runtime_bundle: PathBuf::from("/run/test"), - command_line_sha256: sha256_id(&[2]), - environment_names: Vec::new(), - environment_contract_sha256: sha256_id(&[3]), - control_group: format!("/system.slice/idunn-{uid}.service"), - credentials_directory: None, - parent_only_file_descriptors: Vec::new(), - activation_signer_identity_id: "activation".into(), - activation_signer_public_key: vec![1; 32], - service_credentials: Vec::new(), - } - } - - fn write_lease() -> IdunnProcessWriteLeaseRecord { - IdunnProcessWriteLeaseRecord { - schema_version: IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into(), - target: "ghostlight".into(), - expected_projection_sha256: sha256_id(&[1]), - plan_id: sha256_id(&[2]), - incarnation_id: "incarnation-test".into(), - sealed_release_id: sha256_id(&[3]), - activation_witness_sha256: sha256_id(&[4]), - state_schema_generation: "ghostlight-state-v1".into(), - state_contract_sha256: sha256_id(&[5]), - runtime_id: "ghostlight".into(), - runtime_instance_id: sha256_id(&[6]), - warming_presence_sha256: sha256_id(&[7]), - lease_epoch: 1, - issued_at_unix_millis: 100, - } - } - - #[test] - fn cli_exposes_only_declarative_commands() { - for arguments in [ - vec!["up", "ghostlight", "--deploy-command", "sh -c bad"], - vec!["serve", "--swarm-profile", "yggdrasil-local"], - vec!["serve", "--restart-command", "bad"], - vec!["validate-runtime-admission"], - ] { - assert!(parse(arguments.into_iter().map(str::to_owned)).is_err()); - } - } - - #[test] - fn garden_path_accepts_service_and_profile_selectors() { - for selector in ["ghostlight", "profile:aetheria", "profile:full-gamecult"] { - let parsed = - parse(["up", selector, "--no-wait"].into_iter().map(str::to_owned)).unwrap(); - let Command::Up { - selector: actual, .. - } = parsed - else { - panic!("expected up command") - }; - assert_eq!(actual, selector); - } - } - - #[test] - fn route_bindings_are_one_global_socket_and_candidate_authority_map() { - let first = route_binding("first", 4103, 14103, 14111); - let second = route_binding("second", 8831, 18831, 18839); - validate_route_binding_set(&[("first", &first), ("second", &second)]).unwrap(); - - let mut duplicate_id = second.clone(); - duplicate_id.route_id = first.route_id.clone(); - assert!( - validate_route_binding_set(&[("first", &first), ("second", &duplicate_id)]).is_err() - ); - - let mut overlapping_candidates = second.clone(); - overlapping_candidates.private_port_start = 14111; - overlapping_candidates.private_port_end = 14120; - assert!( - validate_route_binding_set(&[("first", &first), ("second", &overlapping_candidates),]) - .is_err() - ); - - let mut stable_inside_other_range = second; - stable_inside_other_range.stable_endpoint = "tcp://127.0.0.1:14105".into(); - assert!( - validate_route_binding_set(&[ - ("first", &first), - ("second", &stable_inside_other_range), - ]) - .is_err() - ); - } - - #[test] - fn deployment_command_is_immutable_positional_fact() -> Result<()> { - let value = command(CommandKind::Deploy); - value.validate()?; - let encoded = rmp_serde::to_vec(&value)?; - assert_eq!(encoded[0], 0x96); - assert!(!encoded.windows(7).any(|window| window == b"running")); - assert!(!encoded.windows(5).any(|window| window == b"owner")); - Ok(()) - } - - #[test] - fn phases_are_one_exact_forward_chain() { - let phases = [ - DeploymentPhase::Sealing, - DeploymentPhase::Starting, - DeploymentPhase::Warming, - DeploymentPhase::Fencing, - DeploymentPhase::Leasing, - DeploymentPhase::AwaitingReady, - DeploymentPhase::Routing, - DeploymentPhase::Committing, - DeploymentPhase::Complete, - ]; - assert!( - phases - .windows(2) - .all(|pair| pair[1] as u8 == pair[0] as u8 + 1) - ); - } - - #[test] - fn every_new_odin_sequence_must_advance_and_exact_retry_is_idempotent() -> Result<()> { - let first = topology(7, 1); - assert!(sequence_requires_admission(None, 6, &first)?); - assert!(!sequence_requires_admission( - Some(&first), - 7, - &topology(7, 1) - )?); - assert!(sequence_requires_admission( - Some(&first), - 7, - &topology(8, 2) - )?); - assert!(sequence_requires_admission(Some(&first), 7, &topology(7, 2)).is_err()); - assert!(sequence_requires_admission(Some(&first), 7, &topology(6, 3)).is_err()); - Ok(()) - } - - #[test] - fn odin_sequence_cursors_are_scoped_by_target_and_signer() -> Result<()> { - let command = command(CommandKind::Deploy); - let mut ghostlight = - DeploymentTransaction::new(&command, "ghostlight".into(), 0, None, 100)?; - ghostlight.latest_odin_observation = Some(topology(7, 1)); - ghostlight.odin_publisher_sequence_cursor = 7; - let mut odin = DeploymentTransaction::new(&command, "odin".into(), 1, None, 100)?; - odin.latest_odin_observation = Some(topology(41, 2)); - odin.odin_publisher_sequence_cursor = 41; - let envelope = |key: &str| CultCacheEnvelope { - key: key.into(), - r#type: DeploymentTransaction::TYPE.into(), - payload: Vec::new(), - stored_at: "1970-01-01T00:00:00.100Z".into(), - schema_id: Some(DEPLOYMENT_TRANSACTION_SCHEMA.into()), - }; - let snapshot = ControlSnapshot { - commands: Vec::new(), - transactions: vec![ - Stored { - envelope: envelope("ghostlight"), - value: ghostlight, - }, - Stored { - envelope: envelope("odin"), - value: odin, - }, - ], - admitted: Vec::new(), - }; - - assert_eq!(snapshot.max_odin_sequence("ghostlight", "odin-signer"), 7); - assert_eq!(snapshot.max_odin_sequence("odin", "odin-signer"), 41); - assert_eq!(snapshot.max_odin_sequence("ghostlight", "other-signer"), 0); - Ok(()) - } - - #[test] - fn stale_odin_provider_receipt_cannot_gate_continuity_restart() -> Result<()> { - let touched = std::cell::Cell::new(false); - validate_live_providers_for_deploy(CommandKind::Continuity, || { - touched.set(true); - bail!("Odin provider receipt is stale") - })?; - assert!(!touched.get()); - assert!( - validate_live_providers_for_deploy(CommandKind::Deploy, || { - bail!("Odin provider receipt is stale") - }) - .is_err() - ); - Ok(()) - } - - #[test] - fn prepared_write_lease_is_durable_but_not_admitted_authority() -> Result<()> { - let lease = write_lease(); - lease.validate()?; - let prepared = LeasingEvidence::Prepared { - lease: lease.clone(), - lease_sha256: lease.canonical_sha256()?, - }; - let encoded = rmp_serde::to_vec(&prepared)?; - let decoded: LeasingEvidence = rmp_serde::from_slice(&encoded)?; - assert_eq!(decoded, prepared); - assert!(decoded.lease().is_none()); - assert!(decoded.lease_sha256().is_none()); - assert_eq!(decoded.prepared_lease().unwrap().0, &lease); - Ok(()) - } - - #[test] - fn runtime_instance_identity_is_stable_for_activation_prepare_replay() -> Result<()> { - let first = runtime_instance_id("tx-one")?; - assert_eq!(runtime_instance_id("tx-one")?, first); - assert_ne!(runtime_instance_id("tx-two")?, first); - Ok(()) - } - - #[test] - fn pre_fencing_abort_is_durable_before_cleanup_and_cannot_resume_as_success() -> Result<()> { - let command = command(CommandKind::Deploy); - let mut transaction = - DeploymentTransaction::new(&command, "ghostlight".into(), 0, None, 100)?; - transaction.pre_fencing_abort = Some(PreFencingAbort { - error: "sealed source was rejected".into(), - candidate_cleanup: CleanupEvidence::Skipped, - topology_reconciliation: CleanupEvidence::Skipped, - source_cleanup: CleanupEvidence::Pending, - }); - transaction.validate()?; - assert!(!transaction.is_terminal()); - - transaction - .pre_fencing_abort - .as_mut() - .unwrap() - .source_cleanup = CleanupEvidence::Complete; - transaction.phase = DeploymentPhase::Complete; - transaction.last_error = Some("sealed source was rejected".into()); - transaction.completion = Some(TransactionCompletion::FailedBeforeFencing { - error: "sealed source was rejected".into(), - }); - transaction.validate()?; - assert!(transaction.is_terminal()); - Ok(()) - } - - #[test] - fn activation_without_workload_still_requires_durable_candidate_cleanup() { - assert_eq!( - candidate_cleanup_requirement(true, false), - CleanupEvidence::Pending - ); - assert_eq!( - candidate_cleanup_requirement(true, true), - CleanupEvidence::Pending - ); - assert_eq!( - candidate_cleanup_requirement(false, false), - CleanupEvidence::Skipped - ); - } - - #[test] - fn bad_selector_becomes_one_terminal_refusal_record() -> Result<()> { - let command = command(CommandKind::Deploy); - let transaction = DeploymentTransaction::rejected( - &command, - anyhow!("deployment selector is unknown"), - 100, - )?; - assert!(transaction.is_terminal()); - assert_eq!(transaction.target, command.selector); - assert!(matches!( - transaction.completion, - Some(TransactionCompletion::FailedBeforeFencing { .. }) - )); - Ok(()) - } - - #[test] - fn post_commit_cleanup_keeps_exact_incumbent_work_owned_until_retired() -> Result<()> { - let incumbent = workload(1001, 40, 50); - let cleanup = PostCommitCleanup { - incumbent: IncumbentCleanupEvidence::Pending { - generation_id: "generation-old".into(), - workload: incumbent.clone(), - }, - source: SourceCleanupEvidence::Pending, - }; - let encoded = rmp_serde::to_vec(&cleanup)?; - let mut replayed: PostCommitCleanup = rmp_serde::from_slice(&encoded)?; - assert_eq!(replayed, cleanup); - assert!(!replayed.is_complete()); - replayed.incumbent = IncumbentCleanupEvidence::Complete { - generation_id: "generation-old".into(), - }; - assert!(!replayed.is_complete()); - replayed.source = SourceCleanupEvidence::Complete; - assert!(replayed.is_complete()); - Ok(()) - } - - #[test] - fn routed_incumbent_retirement_waits_for_the_declared_drain_deadline() -> Result<()> { - assert_eq!(route_drain_deadline(1_000, 30)?, 31_000); - assert!(route_drain_deadline(u64::MAX, 1).is_err()); - Ok(()) - } - - #[test] - fn admitted_route_receipt_refreshes_when_stale_or_implausibly_future_dated() { - assert!(route_observation_is_current(900, 1_000, 100, 10)); - assert!(route_observation_is_current(1_010, 1_000, 100, 10)); - assert!(!route_observation_is_current(899, 1_000, 100, 10)); - assert!(!route_observation_is_current(1_011, 1_000, 100, 10)); - } - - #[test] - fn lease_warming_requires_both_new_odin_and_new_provider_evidence() { - let old = digest('1'); - let fresh = digest('2'); - assert!(!provider_warming_advanced(7, &old, 7, &fresh)); - assert!(!provider_warming_advanced(7, &old, 8, &old)); - assert!(provider_warming_advanced(7, &old, 8, &fresh)); - } - - #[test] - fn failed_route_proof_never_restores_any_fenced_incumbent() { - assert!(!may_rollback_route_after_failed_proof( - &FencingEvidence::Revoked { - incumbent_lease_sha256: Some(digest('1')), - candidate_lease_path_verified_empty: false, - } - )); - assert!(!may_rollback_route_after_failed_proof( - &FencingEvidence::Revoked { - incumbent_lease_sha256: None, - candidate_lease_path_verified_empty: true, - } - )); - assert!(may_rollback_route_after_failed_proof( - &FencingEvidence::SkippedStateless - )); - } - - #[test] - fn fenced_writer_is_already_retired_before_post_commit_cleanup() { - assert!(incumbent_was_stopped_during_fencing( - &FencingEvidence::Revoked { - incumbent_lease_sha256: Some(digest('1')), - candidate_lease_path_verified_empty: false, - } - )); - assert!(!incumbent_was_stopped_during_fencing( - &FencingEvidence::Revoked { - incumbent_lease_sha256: None, - candidate_lease_path_verified_empty: true, - } - )); - assert!(!incumbent_was_stopped_during_fencing( - &FencingEvidence::SkippedStateless - )); - } - - #[test] - fn warming_accepts_only_the_exact_projected_incumbent_lease_disagreement() { - let expected_detail = format!("expected:{};activation:{}", digest('1'), digest('2')); - let incumbent = digest('3'); - let exact = OdinTopologyDisagreement { - code: "projected-write-lease".into(), - expected: Some(expected_detail.clone()), - observed: Some(incumbent.clone()), - }; - - assert!(warming_disagreements_match_incumbent( - &expected_detail, - Some(&incumbent), - &[exact.clone()], - )); - assert!(!warming_disagreements_match_incumbent( - &expected_detail, - None, - &[exact.clone()], - )); - - let mut substituted = exact.clone(); - substituted.observed = Some(digest('4')); - assert!(!warming_disagreements_match_incumbent( - &expected_detail, - Some(&incumbent), - &[substituted], - )); - assert!(!warming_disagreements_match_incumbent( - &expected_detail, - Some(&incumbent), - &[exact.clone(), exact], - )); - } - - #[test] - fn candidate_and_incumbent_must_differ_in_all_three_native_boundaries() { - let incumbent = workload(1001, 40, 50); - assert!(prove_isolation(&workload(1002, 41, 51), Some(&incumbent)).is_ok()); - assert!(prove_isolation(&workload(1001, 41, 51), Some(&incumbent)).is_err()); - assert!(prove_isolation(&workload(1002, 40, 51), Some(&incumbent)).is_err()); - assert!(prove_isolation(&workload(1002, 41, 50), Some(&incumbent)).is_err()); - } - - #[test] - fn exactly_one_inflight_transaction_may_own_a_target() -> Result<()> { - let command = command(CommandKind::Deploy); - let one = DeploymentTransaction::new(&command, "ghostlight".into(), 0, None, 100)?; - let two = DeploymentTransaction::new(&command, "ghostlight".into(), 1, None, 100)?; - let snapshot = ControlSnapshot { - commands: vec![Stored { - envelope: command_envelope(&command, 100)?, - value: command, - }], - transactions: vec![ - Stored { - envelope: transaction_envelope(&one, 100)?, - value: one, - }, - Stored { - envelope: transaction_envelope(&two, 100)?, - value: two, - }, - ], - admitted: Vec::new(), - }; - assert!(snapshot.validate_relations().is_err()); - Ok(()) - } - - #[test] - fn command_ordinals_do_not_turn_one_target_wait_into_a_global_brake() -> Result<()> { - let first_command = command(CommandKind::Deploy); - let first = DeploymentTransaction::new(&first_command, "odin".into(), 0, None, 100)?; - let second = DeploymentTransaction::new(&first_command, "ghostlight".into(), 1, None, 100)?; - let mut unrelated_command = command(CommandKind::Deploy); - unrelated_command.command_id = "up-unrelated".into(); - let unrelated = - DeploymentTransaction::new(&unrelated_command, "huginn".into(), 0, None, 101)?; - let snapshot = ControlSnapshot { - commands: Vec::new(), - transactions: [&first, &second, &unrelated] - .into_iter() - .map(|value| Stored { - envelope: transaction_envelope(value, 100).unwrap(), - value: value.clone(), - }) - .collect(), - admitted: Vec::new(), - }; - assert!(!snapshot.has_earlier_authority_sibling(&first)); - assert!(snapshot.has_earlier_authority_sibling(&second)); - assert!(!snapshot.has_earlier_authority_sibling(&unrelated)); - Ok(()) - } - - #[test] - fn complete_cleanup_remains_retryable_without_owning_the_current_incarnation() -> Result<()> { - let command = command(CommandKind::Deploy); - let mut transaction = - DeploymentTransaction::new(&command, "ghostlight".into(), 0, None, 100)?; - transaction.phase = DeploymentPhase::Complete; - transaction.completion = Some(TransactionCompletion::Admitted { - generation_id: format!("generation-{}", transaction.transaction_id), - }); - transaction.post_commit_cleanup = Some(PostCommitCleanup { - incumbent: IncumbentCleanupEvidence::SkippedNoIncumbent, - source: SourceCleanupEvidence::Pending, - }); - - assert!(!transaction.is_terminal()); - assert!(!transaction.owns_target_authority()); - assert!(transaction.blocks_new_target_mutation()); - Ok(()) - } - - #[test] - fn legacy_mutable_command_schema_is_rejected() -> Result<()> { - let temporary = tempfile::tempdir()?; - let path = temporary.path().join("control.cc"); - let legacy = CultCacheEnvelope { - key: "up-legacy".into(), - r#type: DeploymentCommand::TYPE.into(), - payload: rmp_serde::to_vec(&(DEPLOYMENT_COMMAND_SCHEMA, "up-legacy", "running"))?, - stored_at: rfc3339_millis(100)?, - schema_id: Some("idunn.deployment_command.v1".into()), - }; - assert!( - SingleFileMessagePackBackingStore::new(&path).compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: DeploymentCommand::TYPE.into(), - key: "up-legacy".into(), - current: None, - }], - &[legacy], - )? - ); - assert!(ControlSnapshot::read(&path).is_err()); - Ok(()) - } - - #[test] - fn loadcredential_era_control_schemas_are_rejected_before_rehydration() -> Result<()> { - for (record_type, key, schema) in [ - ( - DeploymentTransaction::TYPE, - "tx-legacy-workload-observation", - "idunn.deployment_transaction.v1", - ), - ( - AdmittedGeneration::TYPE, - "legacy-admitted-target", - "idunn.admitted_generation.v1", - ), - ] { - let temporary = tempfile::tempdir()?; - let path = temporary.path().join("control.cc"); - let legacy = CultCacheEnvelope { - key: key.into(), - r#type: record_type.into(), - payload: Vec::new(), - stored_at: rfc3339_millis(100)?, - schema_id: Some(schema.into()), - }; - assert!( - SingleFileMessagePackBackingStore::new(&path).compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: record_type.into(), - key: key.into(), - current: None, - }], - &[legacy], - )? - ); - assert!(ControlSnapshot::read(&path).is_err()); - } - Ok(()) - } - - #[test] - fn source_identity_is_explicit_and_atomic() { - let partial = parse( - ["serve", "--source-uid", "1001"] - .into_iter() - .map(str::to_owned), - ) - .unwrap_err() - .to_string(); - assert!(partial.contains("supplied together")); - let Command::Serve(options) = parse( - ["serve", "--source-uid", "1001", "--source-gid", "1002"] - .into_iter() - .map(str::to_owned), - ) - .unwrap() else { - panic!("expected serve") - }; - assert_eq!( - options.source_identity, - Some(ProcessIdentity { - uid: 1001, - gid: 1002 - }) - ); - } -} diff --git a/crates/idunn-daemon/src/deployment.rs b/crates/idunn-daemon/src/deployment.rs deleted file mode 100644 index bffd316..0000000 --- a/crates/idunn-daemon/src/deployment.rs +++ /dev/null @@ -1,2110 +0,0 @@ -use std::collections::{BTreeMap, BTreeSet}; -use std::net::IpAddr; -use std::path::{Component, Path, PathBuf}; - -use anyhow::{Context, Result, bail, ensure}; -use serde::{Deserialize, Serialize}; - -pub const TARGET_DECLARATION_SCHEMA: &str = "gamecult.idunn.target_declaration.v1"; -pub const OPERATOR_BINDING_SCHEMA: &str = "gamecult.idunn.operator_binding.v2"; -pub const IDUNN_RUNTIME_BUNDLE_ENVIRONMENT: &str = "GAMECULT_IDUNN_RUNTIME_BUNDLE"; -pub const IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT: &str = "GAMECULT_IDUNN_CANDIDATE_BIND"; -pub const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT: &str = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE"; -pub const RUNTIME_PRESENCE_IDENTITY_BINDING: &str = "GAMECULT_RUNTIME_PRESENCE_IDENTITY"; -pub const RUNTIME_PRESENCE_IDENTITY_FD_NAME: &str = "gamecult-runtime-presence-identity"; - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct TargetDeclaration { - pub schema: String, - pub target: String, - pub source_stamp_environment: String, - #[serde(default)] - pub required_gitlinks: BTreeSet, - #[serde(default)] - pub steps: Vec, - #[serde(default)] - pub external_inputs: Vec, - pub artifacts: Vec, - pub service: ServiceDeclaration, - #[serde(default)] - pub state: Option, - #[serde(default)] - pub provides: Vec, - #[serde(default)] - pub dependencies: Vec, - #[serde(default)] - pub conflicts: Vec, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum RunnerAffordance { - SourceRead, - ArtifactWrite, - BuildCache, - SecretRead, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RecipeStep { - pub id: String, - pub phase: RecipePhase, - pub runner: String, - pub argv: Vec, - #[serde(default = "default_working_directory")] - pub working_directory: PathBuf, - #[serde(default)] - pub required_environment: BTreeSet, -} - -fn default_working_directory() -> PathBuf { - PathBuf::from(".") -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum RecipePhase { - Prepare, - Test, - Build, - Acceptance, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ExternalInput { - pub id: String, - pub url: String, - pub sha256: String, - pub runner: String, - pub destination: PathBuf, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ArtifactOutput { - pub id: String, - pub source_kind: ArtifactSource, - pub runner: Option, - pub source: PathBuf, - pub destination: PathBuf, - #[serde(default)] - pub expected_sha256: Option, - #[serde(default)] - pub executable: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum ArtifactSource { - RunnerOutput, - WorktreeTree, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ServiceDeclaration { - pub executable_artifact: String, - #[serde(default)] - pub required_adjacent_artifacts: BTreeSet, - #[serde(default)] - pub arguments: Vec, - pub transport: ServiceTransport, - #[serde(default)] - pub route_required: bool, - pub health: HealthDeclaration, - #[serde(default)] - pub required_environment: BTreeSet, - #[serde(default)] - pub optional_environment: BTreeSet, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct HealthDeclaration { - pub contract: String, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum ServiceTransport { - Http, - Tcp, - Rudp, - Private, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] -pub enum LaunchArgument { - Literal { value: String }, - Binding { name: String }, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct StateDeclaration { - pub schema_generation: String, - pub slots: Vec, - pub migration: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct StateSlot { - pub id: String, - pub relative_path: PathBuf, - pub kind: StateKind, - pub schema: String, - pub writer: StateWriter, - pub recovery: StateRecovery, - pub startup: StateStartup, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct MigrationDeclaration { - pub executable_artifact: String, - pub from_generations: BTreeSet, - pub to_generation: String, - #[serde(default)] - pub arguments: Vec, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum StateKind { - CultcacheFile, - /// Process-owned state imposed by an external runtime contract. Idunn - /// preserves and fences the file but never interprets its payload. - ExternalFile, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum StateWriter { - ProcessBoundSingleWriter, - None, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum StateRecovery { - Preserve, - Rebuildable, - ExternalAuthority, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum StateStartup { - CreateOrOpenAfterWriteLease, - OpenAtStart, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ProvidedCapability { - pub capability: String, - pub schema: String, - pub compatibility: String, - #[serde(default = "one")] - pub capacity: u32, -} - -fn one() -> u32 { - 1 -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct CapabilityDependency { - pub kind: DependencyKind, - pub capability: String, - pub schema: String, - pub compatibility: String, - #[serde(default = "one")] - pub minimum_capacity: u32, - #[serde(default)] - pub startup: StartupOrder, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum DependencyKind { - Bootstrap, - Required, - Optional, - SharedInfrastructure, - Private, - ExternalOperatorBinding, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum StartupOrder { - #[default] - BeforePromotion, - BeforeStart, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct CapabilityConflict { - pub capability: String, - pub reason: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct OperatorBinding { - pub schema: String, - pub target: String, - pub repository: RepositoryBinding, - pub runners: BTreeMap, - pub workload: WorkloadBinding, - pub runtime_identity: RuntimeIdentityBinding, - pub route: Option, - #[serde(default)] - pub process_write_lease: Option, - pub brakes: BrakeBinding, - pub rollout: RolloutBinding, - pub placement: PlacementBinding, - #[serde(default)] - pub external_capabilities: Vec, - #[serde(default)] - pub profiles: BTreeSet, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RepositoryBinding { - pub origin: String, - pub admitted_ref: String, - pub minimum_revision: String, - pub selection: SourceSelectionPolicy, - pub pinned_revision: Option, - pub release_authority_store: Option, - pub checkout: PathBuf, - pub recipe_path: PathBuf, - #[serde(default)] - pub gitlinks: BTreeMap, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum SourceSelectionPolicy { - PinnedObject, - RefHead, - SignedRelease, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct GitlinkBinding { - pub origin: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RunnerBinding { - pub driver: RunnerDriver, - pub image: String, - pub user: String, - #[serde(default)] - pub affordances: BTreeSet, - pub cache_root: Option, - #[serde(default)] - pub allowed_programs: BTreeSet, - #[serde(default)] - pub environment: BTreeMap, - #[serde(default)] - pub secret_files: BTreeMap, - #[serde(default)] - pub network_profile: Option, - pub memory_mebibytes: u32, - pub cpu_quota_percent: u32, - pub pids_limit: u32, - pub tmpfs_mebibytes: u32, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum RunnerDriver { - Docker, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct WorkloadBinding { - pub driver: WorkloadDriver, - #[serde(default)] - pub state_group: Option, - pub unit_prefix: String, - pub release_root: PathBuf, - #[serde(default)] - pub state_root: Option, - pub runtime_root: PathBuf, - pub network: WorkloadNetwork, - pub hardening: WorkloadHardening, - #[serde(default)] - pub read_only_paths: BTreeSet, - #[serde(default)] - pub read_write_paths: BTreeSet, - #[serde(default)] - pub devices: BTreeSet, - pub memory_mebibytes: u32, - pub cpu_quota_percent: u32, - #[serde(default)] - pub environment: BTreeMap, - #[serde(default)] - pub secret_files: BTreeMap, - #[serde(default)] - pub argument_bindings: BTreeMap, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum WorkloadDriver { - SystemdTransient, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum WorkloadNetwork { - HostPrivate, - None, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum WorkloadHardening { - Strict, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RuntimeIdentityBinding { - pub runtime_id: String, - pub expected_signer_identity_id: String, - pub trust_anchor_store: PathBuf, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ProcessWriteLeaseBinding { - pub record_path: PathBuf, -} - -impl ProcessWriteLeaseBinding { - pub fn lock_path(&self) -> PathBuf { - let mut lock_path = self.record_path.as_os_str().to_os_string(); - lock_path.push(".lock"); - PathBuf::from(lock_path) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct BrakeBinding { - pub deployment_store: PathBuf, - pub lifecycle_store: PathBuf, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RouteBinding { - pub driver: RouteDriver, - pub route_id: String, - pub stable_endpoint: String, - pub private_host: String, - pub private_port_start: u16, - pub private_port_end: u16, - pub config_path: PathBuf, - pub reload_unit: String, -} - -impl RouteBinding { - pub(crate) fn stable_socket(&self) -> Result<(IpAddr, u16)> { - let authority = match self.driver { - RouteDriver::NginxStreamTcp => self - .stable_endpoint - .strip_prefix("http://") - .or_else(|| self.stable_endpoint.strip_prefix("tcp://")), - RouteDriver::NginxStreamUdp => self.stable_endpoint.strip_prefix("rudp://"), - } - .context("stable endpoint transport does not match its route driver")?; - ensure!( - !authority - .chars() - .any(|character| matches!(character, '/' | '?' | '#' | '@' | '[' | ']')), - "stable endpoint is not a plain IP address and port" - ); - let (host, port) = authority - .rsplit_once(':') - .context("stable endpoint has no port")?; - let host = host - .parse::() - .context("stable endpoint host is not an IP address")?; - ensure!( - matches!(host, IpAddr::V4(_)), - "route binding v2 stable endpoints use explicit IPv4 addresses" - ); - let port = port - .parse::() - .context("stable endpoint port is not a u16")?; - ensure!(port > 0, "stable endpoint port is zero"); - Ok((host, port)) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum RouteDriver { - NginxStreamTcp, - NginxStreamUdp, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RolloutBinding { - pub strategy: RolloutStrategy, - pub drain_seconds: u32, - pub retain_releases: u32, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum RolloutStrategy { - CandidateThenPromote, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct PlacementBinding { - pub desired_replicas: u32, - pub nodes: BTreeSet, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ExternalCapabilityBinding { - pub provider_id: String, - pub capability: String, - pub schema: String, - pub compatibility: String, - #[serde(default = "one")] - pub capacity: u32, - pub endpoint: String, -} - -impl TargetDeclaration { - pub fn parse(input: &str) -> Result { - let declaration: Self = - toml::from_str(input).context("decoding strict Idunn target declaration")?; - declaration.validate()?; - Ok(declaration) - } - - pub fn validate(&self) -> Result<()> { - ensure!( - self.schema == TARGET_DECLARATION_SCHEMA, - "unsupported target declaration schema" - ); - require_id(&self.target, "target")?; - require_environment_name(&self.source_stamp_environment)?; - for path in &self.required_gitlinks { - require_relative_path(path, "required gitlink", false)?; - } - ensure!(!self.steps.is_empty(), "no recipe steps declared"); - ensure!(!self.artifacts.is_empty(), "no artifact outputs declared"); - - let mut runner_ids = BTreeSet::new(); - unique_ids( - self.steps.iter().map(|step| step.id.as_str()), - "recipe step", - )?; - for step in &self.steps { - require_id(&step.runner, "runner class")?; - runner_ids.insert(step.runner.as_str()); - ensure!(!step.argv.is_empty(), "step {} has empty argv", step.id); - for argument in &step.argv { - require_value(argument, "step argv")?; - } - require_program(&step.argv[0], "step program")?; - require_relative_path(&step.working_directory, "step working directory", true)?; - for name in &step.required_environment { - require_environment_name(name)?; - } - } - - let mut artifact_ids = BTreeSet::new(); - let mut destinations = BTreeSet::new(); - for artifact in &self.artifacts { - require_id(&artifact.id, "artifact")?; - ensure!( - artifact_ids.insert(artifact.id.as_str()), - "artifact id {} is declared twice", - artifact.id - ); - require_relative_path(&artifact.source, "artifact source", false)?; - require_leaf_path(&artifact.destination, "artifact destination")?; - if let Some(expected_sha256) = &artifact.expected_sha256 { - require_sha256(expected_sha256, "expected artifact sha256")?; - } - ensure!( - destinations.insert(artifact.destination.as_path()), - "artifact destination {} is declared twice", - artifact.destination.display() - ); - match (artifact.source_kind, artifact.runner.as_deref()) { - (ArtifactSource::RunnerOutput, Some(runner)) => { - require_id(runner, "artifact runner class")?; - runner_ids.insert(runner); - } - (ArtifactSource::WorktreeTree, None) => {} - (ArtifactSource::RunnerOutput, None) => { - bail!("runner-output artifact {} has no runner class", artifact.id) - } - (ArtifactSource::WorktreeTree, Some(_)) => bail!( - "worktree-tree artifact {} cannot name a runner class", - artifact.id - ), - } - } - let mut external_input_ids = BTreeSet::new(); - let mut external_input_destinations = BTreeSet::new(); - for input in &self.external_inputs { - require_id(&input.id, "external input")?; - ensure!( - external_input_ids.insert(input.id.as_str()), - "external input id {} is declared twice", - input.id - ); - ensure!( - !artifact_ids.contains(input.id.as_str()), - "external input id {} collides with an artifact id", - input.id - ); - require_value(&input.url, "external input URL")?; - https_host(&input.url)?; - require_sha256(&input.sha256, "external input sha256")?; - require_id(&input.runner, "external input runner class")?; - runner_ids.insert(input.runner.as_str()); - require_relative_path(&input.destination, "external input destination", false)?; - ensure!( - external_input_destinations - .insert((input.runner.as_str(), input.destination.as_path())), - "external input destination {} is declared twice for runner {}", - input.destination.display(), - input.runner - ); - } - ensure!( - !runner_ids.is_empty(), - "target declaration uses no runner classes" - ); - - ensure!( - artifact_ids.contains(self.service.executable_artifact.as_str()), - "service executable artifact is not declared" - ); - for artifact in &self.service.required_adjacent_artifacts { - ensure!( - artifact_ids.contains(artifact.as_str()), - "adjacent service artifact {artifact} is not declared" - ); - } - for argument in &self.service.arguments { - validate_launch_argument(argument)?; - } - require_capability(&self.service.health.contract, "health contract")?; - for name in &self.service.required_environment { - require_environment_name(name)?; - } - ensure!( - self.service - .required_environment - .contains(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT), - "service does not require the standard Idunn runtime bundle" - ); - ensure!( - self.service - .required_environment - .contains(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT) - == self.service.route_required, - "routed services must require exactly one Idunn-owned candidate bind" - ); - ensure!( - self.service - .required_environment - .contains(IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT) - == self.write_lease_required(), - "state-writing services must require exactly one Idunn-owned process write lease" - ); - for name in &self.service.optional_environment { - require_environment_name(name)?; - ensure!( - !self.service.required_environment.contains(name), - "service environment {name} is both required and optional" - ); - } - - if let Some(state) = &self.state { - require_capability(&state.schema_generation, "state schema generation")?; - ensure!(!state.slots.is_empty(), "state contract has no slots"); - let slot_ids = unique_ids( - state.slots.iter().map(|slot| slot.id.as_str()), - "state slot", - )?; - let mut slot_paths = BTreeSet::::new(); - for slot in &state.slots { - require_relative_path(&slot.relative_path, "state slot path", false)?; - ensure!( - slot_paths - .iter() - .all(|other| !paths_overlap(other, &slot.relative_path)), - "state slot path {} overlaps another declared slot", - slot.relative_path.display() - ); - ensure!( - slot_paths.insert(slot.relative_path.clone()), - "state slot path {} is declared twice", - slot.relative_path.display() - ); - require_capability(&slot.schema, "state slot schema")?; - match slot.writer { - StateWriter::ProcessBoundSingleWriter => ensure!( - slot.startup == StateStartup::CreateOrOpenAfterWriteLease, - "writable state slot {} must open after its write lease", - slot.id - ), - StateWriter::None => ensure!( - slot.startup == StateStartup::OpenAtStart, - "non-writable state slot {} cannot wait for a write lease", - slot.id - ), - } - if slot.recovery == StateRecovery::ExternalAuthority { - ensure!( - slot.writer == StateWriter::None, - "externally authoritative state slot {} cannot name the service as writer", - slot.id - ); - } - } - if let Some(migration) = state.migration.as_ref() { - ensure!( - artifact_ids.contains(migration.executable_artifact.as_str()), - "migration executable artifact is not declared" - ); - ensure!( - !migration.from_generations.is_empty(), - "migration has no source generations" - ); - for generation in &migration.from_generations { - require_capability(generation, "migration source generation")?; - } - ensure!( - migration.to_generation == state.schema_generation, - "migration destination differs from state generation" - ); - for argument in &migration.arguments { - validate_launch_argument(argument)?; - } - } - ensure!(slot_ids.len() == state.slots.len(), "duplicate state slot"); - } - - let mut provided = BTreeSet::new(); - for capability in &self.provides { - require_capability_contract( - &capability.capability, - &capability.schema, - &capability.compatibility, - )?; - ensure!( - capability.capacity > 0, - "provided capability capacity must be positive" - ); - ensure!( - provided.insert(capability.capability.as_str()), - "capability {} is provided twice", - capability.capability - ); - } - let mut required = BTreeSet::new(); - for dependency in &self.dependencies { - require_capability_contract( - &dependency.capability, - &dependency.schema, - &dependency.compatibility, - )?; - ensure!( - dependency.minimum_capacity > 0, - "dependency capacity must be positive" - ); - if dependency.kind == DependencyKind::Bootstrap { - ensure!( - dependency.startup == StartupOrder::BeforeStart, - "bootstrap dependency {} must be available before start", - dependency.capability - ); - } - ensure!( - required.insert((dependency.kind, dependency.capability.as_str())), - "dependency {} is declared twice for the same kind", - dependency.capability - ); - } - for conflict in &self.conflicts { - require_capability(&conflict.capability, "conflicting capability")?; - require_value(&conflict.reason, "conflict reason")?; - } - Ok(()) - } - - pub fn write_lease_required(&self) -> bool { - self.state.as_ref().is_some_and(|state| { - state - .slots - .iter() - .any(|slot| slot.writer == StateWriter::ProcessBoundSingleWriter) - }) - } -} - -impl OperatorBinding { - pub fn parse(input: &str) -> Result { - let binding: Self = - toml::from_str(input).context("decoding strict Idunn operator binding")?; - binding.validate()?; - Ok(binding) - } - - pub fn validate(&self) -> Result<()> { - ensure!( - self.schema == OPERATOR_BINDING_SCHEMA, - "unsupported operator binding schema" - ); - require_id(&self.target, "target")?; - ensure!( - self.repository.origin.starts_with("https://"), - "repository origin must use HTTPS" - ); - ensure!( - self.repository.origin.ends_with(".git"), - "repository origin must name a Git repository" - ); - ensure!( - self.repository.admitted_ref.starts_with("refs/heads/"), - "admitted ref must be a full branch ref" - ); - require_sha1(&self.repository.minimum_revision, "minimum revision")?; - match self.repository.selection { - SourceSelectionPolicy::PinnedObject => { - let revision = self.repository.pinned_revision.as_deref().ok_or_else(|| { - anyhow::anyhow!("pinned-object selection has no pinned revision") - })?; - require_sha1(revision, "pinned revision")?; - ensure!( - self.repository.release_authority_store.is_none(), - "pinned-object selection cannot name a release-authority store" - ); - } - SourceSelectionPolicy::RefHead => { - ensure!( - self.repository.pinned_revision.is_none(), - "ref-head selection cannot name a pinned revision" - ); - ensure!( - self.repository.release_authority_store.is_none(), - "ref-head selection cannot name a release-authority store" - ); - } - SourceSelectionPolicy::SignedRelease => { - ensure!( - self.repository.pinned_revision.is_none(), - "signed-release selection cannot name a pinned revision" - ); - let store = self - .repository - .release_authority_store - .as_ref() - .ok_or_else(|| { - anyhow::anyhow!("signed-release selection has no authority store") - })?; - require_absolute_path(store, "release authority store")?; - } - } - require_absolute_path(&self.repository.checkout, "repository checkout")?; - require_relative_path(&self.repository.recipe_path, "recipe path", false)?; - for (path, gitlink) in &self.repository.gitlinks { - require_relative_path(path, "gitlink binding", false)?; - require_git_origin(&gitlink.origin, "gitlink origin")?; - } - ensure!(!self.runners.is_empty(), "operator binding has no runners"); - for (id, runner) in &self.runners { - require_id(id, "runner binding")?; - require_pinned_image(&runner.image)?; - require_container_identity(&runner.user)?; - ensure!( - runner.memory_mebibytes > 0, - "runner memory must be positive" - ); - ensure!( - (1..=100_000).contains(&runner.cpu_quota_percent), - "runner CPU quota is outside 1..=100000" - ); - ensure!( - runner.pids_limit > 0 && runner.tmpfs_mebibytes > 0, - "runner process or temporary-filesystem limit is zero" - ); - if let Some(cache_root) = runner.cache_root.as_ref() { - require_absolute_path(cache_root, "runner cache root")?; - } - for program in &runner.allowed_programs { - require_program(program, "allowed runner program")?; - } - ensure!( - !runner.allowed_programs.is_empty(), - "runner {id} has no allowed programs" - ); - if let Some(profile) = &runner.network_profile { - require_capability(profile, "runner network profile")?; - } - for name in runner.environment.keys().chain(runner.secret_files.keys()) { - require_environment_name(name)?; - } - for value in runner.environment.values() { - require_value(value, "runner environment value")?; - } - for path in runner.secret_files.values() { - require_absolute_path(path, "runner secret file")?; - } - if runner.affordances.contains(&RunnerAffordance::BuildCache) { - ensure!( - runner.cache_root.is_some(), - "build-cache runner {id} has no cache root" - ); - } - ensure!( - runner.affordances.contains(&RunnerAffordance::BuildCache) - == runner.cache_root.is_some(), - "runner {id} cache root and build-cache affordance disagree" - ); - ensure!( - runner.affordances.contains(&RunnerAffordance::SecretRead) - == !runner.secret_files.is_empty(), - "runner {id} secret files and secret-read affordance disagree" - ); - } - let needs_state_group = - self.workload.state_root.is_some() || !self.workload.read_write_paths.is_empty(); - ensure!( - self.workload.state_group.is_some() == needs_state_group, - "a fixed state group must exist exactly when the dynamic workload has writable paths" - ); - if let Some(group) = &self.workload.state_group { - require_identity(group, "workload state group")?; - ensure!( - !matches!(group.as_str(), "root" | "0"), - "ordinary Idunn workload state cannot use the root group" - ); - } - require_id(&self.workload.unit_prefix, "workload unit prefix")?; - require_id(&self.runtime_identity.runtime_id, "runtime id")?; - require_id( - &self.runtime_identity.expected_signer_identity_id, - "expected signer identity id", - )?; - require_absolute_path( - &self.runtime_identity.trust_anchor_store, - "trust anchor store", - )?; - for (label, path) in [ - ("release root", &self.workload.release_root), - ("runtime root", &self.workload.runtime_root), - ("deployment brake", &self.brakes.deployment_store), - ("lifecycle brake", &self.brakes.lifecycle_store), - ] { - require_absolute_path(path, label)?; - } - if let Some(state_root) = &self.workload.state_root { - require_absolute_path(state_root, "state root")?; - } - if let Some(write_lease) = &self.process_write_lease { - require_absolute_path(&write_lease.record_path, "process write-lease record")?; - require_absolute_path(&write_lease.lock_path(), "process write-lease lock")?; - } - ensure!( - self.brakes.deployment_store != self.brakes.lifecycle_store, - "deployment and lifecycle brakes are identical" - ); - ensure!( - self.workload.memory_mebibytes > 0, - "workload memory must be positive" - ); - ensure!( - (1..=100_000).contains(&self.workload.cpu_quota_percent), - "workload CPU quota is outside 1..=100000" - ); - for path in self - .workload - .read_only_paths - .iter() - .chain(self.workload.read_write_paths.iter()) - .chain(self.workload.devices.iter()) - { - require_absolute_path(path, "workload path")?; - } - for path in &self.workload.read_write_paths { - if let Some(state_root) = &self.workload.state_root { - ensure!( - !paths_overlap(path, state_root), - "workload read-write path {} overlaps the write-lease-controlled state root", - path.display() - ); - } - } - let mut authority_paths = vec![ - self.brakes.deployment_store.clone(), - self.brakes.lifecycle_store.clone(), - ]; - if let Some(write_lease) = &self.process_write_lease { - authority_paths.push(write_lease.record_path.clone()); - authority_paths.push(write_lease.lock_path()); - } - ensure!( - authority_paths.iter().enumerate().all(|(index, path)| { - authority_paths[index + 1..] - .iter() - .all(|other| !paths_overlap(path, other)) - }), - "Idunn authority paths overlap" - ); - let mut protected_paths = authority_paths; - protected_paths.extend([ - self.workload.release_root.clone(), - self.workload.runtime_root.clone(), - self.runtime_identity.trust_anchor_store.clone(), - ]); - if let Some(route) = &self.route { - protected_paths.push(route.config_path.clone()); - } - if let Some(release_authority) = &self.repository.release_authority_store { - protected_paths.push(release_authority.clone()); - } - for authority_path in protected_paths { - for writable_path in self - .workload - .read_write_paths - .iter() - .chain(self.workload.state_root.iter()) - { - ensure!( - !paths_overlap(&authority_path, writable_path), - "workload writable path {} overlaps Idunn authority {}", - writable_path.display(), - authority_path.display() - ); - } - } - for name in self - .workload - .environment - .keys() - .chain(self.workload.secret_files.keys()) - { - require_environment_name(name)?; - ensure!( - name != IDUNN_RUNTIME_BUNDLE_ENVIRONMENT - && name != IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, - "operator binding attempts to replace Idunn-owned workload environment" - ); - } - for value in self.workload.environment.values() { - require_value(value, "workload environment value")?; - } - for name in self.workload.argument_bindings.keys() { - require_id(name, "argument binding")?; - } - for value in self.workload.argument_bindings.values() { - require_value(value, "argument binding value")?; - } - for path in self.workload.secret_files.values() { - require_absolute_path(path, "secret file")?; - } - ensure!( - !self - .workload - .environment - .contains_key(RUNTIME_PRESENCE_IDENTITY_BINDING), - "runtime presence identity must be a parent-only secret source, not environment" - ); - let presence_identity = self - .workload - .secret_files - .get(RUNTIME_PRESENCE_IDENTITY_BINDING) - .context("workload has no parent-only runtime presence identity source")?; - ensure!( - self.workload - .secret_files - .iter() - .filter(|(_, path)| *path == presence_identity) - .count() - == 1, - "runtime presence identity source is duplicated under another secret binding" - ); - if let Some(route) = self.route.as_ref() { - require_id(&route.route_id, "route id")?; - require_value(&route.stable_endpoint, "stable endpoint")?; - require_host(&route.private_host)?; - let private_host: IpAddr = route - .private_host - .parse() - .context("route private host is not an IP address")?; - ensure!( - private_host.is_loopback(), - "systemd-transient candidate routes must use a loopback private host" - ); - ensure!( - route.private_port_start > 0, - "private port range starts at zero" - ); - ensure!( - route.private_port_start < route.private_port_end, - "candidate rollout requires at least two private ports" - ); - route.stable_socket()?; - require_absolute_path(&route.config_path, "route config")?; - require_unit(&route.reload_unit, "route reload unit")?; - } - ensure!( - self.rollout.retain_releases >= 2, - "candidate rollout must retain at least current and prior releases" - ); - ensure!( - self.placement.desired_replicas == 1, - "operator binding v2 admits exactly one replica" - ); - ensure!( - self.placement.nodes.len() == 1, - "operator binding v2 admits exactly one node" - ); - for node in &self.placement.nodes { - require_id(node, "placement node")?; - } - let mut external_contracts = BTreeSet::new(); - for capability in &self.external_capabilities { - require_id(&capability.provider_id, "external provider id")?; - require_capability_contract( - &capability.capability, - &capability.schema, - &capability.compatibility, - )?; - ensure!( - capability.capacity > 0, - "external capability capacity must be positive" - ); - require_value(&capability.endpoint, "external capability endpoint")?; - ensure!( - external_contracts.insert(( - capability.provider_id.as_str(), - capability.capability.as_str(), - capability.schema.as_str(), - capability.compatibility.as_str(), - )), - "external provider capability is declared twice" - ); - } - for profile in &self.profiles { - require_capability(profile, "profile")?; - } - Ok(()) - } - - pub fn admit(&self, declaration: &TargetDeclaration) -> Result<()> { - ensure!( - self.target == declaration.target, - "binding target does not match declaration" - ); - let bound_gitlinks: BTreeSet<_> = self.repository.gitlinks.keys().cloned().collect(); - ensure!( - bound_gitlinks == declaration.required_gitlinks, - "operator gitlink bindings do not exactly match required gitlinks" - ); - let declared_runners: BTreeSet<_> = declaration - .steps - .iter() - .map(|step| step.runner.as_str()) - .chain( - declaration - .external_inputs - .iter() - .map(|input| input.runner.as_str()), - ) - .chain( - declaration - .artifacts - .iter() - .filter_map(|artifact| artifact.runner.as_deref()), - ) - .collect(); - let bound_runners: BTreeSet<_> = self.runners.keys().map(String::as_str).collect(); - ensure!( - declared_runners == bound_runners, - "operator runner classes do not exactly match the target recipe" - ); - ensure!( - self.process_write_lease.is_some() == declaration.write_lease_required(), - "process write-lease binding must exist exactly when writable state requires it" - ); - ensure!( - self.workload.state_root.is_some() == declaration.state.is_some(), - "state root binding must exist exactly when the recipe declares state" - ); - for step in &declaration.steps { - let binding = &self.runners[&step.runner]; - ensure!( - !binding - .environment - .contains_key(&declaration.source_stamp_environment) - && !binding - .secret_files - .contains_key(&declaration.source_stamp_environment), - "runner cannot replace the Idunn source stamp" - ); - ensure!( - binding.affordances.contains(&RunnerAffordance::SourceRead), - "runner {} cannot read the frozen source", - step.runner - ); - ensure!( - binding.allowed_programs.contains(&step.argv[0]), - "runner {} does not admit program {}", - step.runner, - step.argv[0] - ); - let available: BTreeSet<_> = binding - .environment - .keys() - .chain(binding.secret_files.keys()) - .cloned() - .collect(); - ensure!( - step.required_environment.is_subset(&available), - "step {} lacks required runner environment", - step.id - ); - } - for artifact in declaration - .artifacts - .iter() - .filter(|artifact| artifact.source_kind == ArtifactSource::RunnerOutput) - { - let runner_id = artifact - .runner - .as_deref() - .expect("validated runner-output artifact"); - let binding = &self.runners[runner_id]; - ensure!( - binding - .affordances - .contains(&RunnerAffordance::ArtifactWrite), - "runner {runner_id} cannot publish artifact {}", - artifact.id - ); - } - for input in &declaration.external_inputs { - let binding = &self.runners[&input.runner]; - ensure!( - binding.affordances.contains(&RunnerAffordance::SourceRead), - "external input {} runner cannot read the frozen source", - input.id - ); - ensure!( - binding - .affordances - .contains(&RunnerAffordance::ArtifactWrite), - "external input {} runner cannot materialize inputs", - input.id - ); - ensure!( - binding.network_profile.is_some(), - "external input {} runner has no operator-bound network profile", - input.id - ); - } - ensure!( - !self - .workload - .environment - .contains_key(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT) - && !self - .workload - .secret_files - .contains_key(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT) - && !self - .workload - .environment - .contains_key(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT) - && !self - .workload - .secret_files - .contains_key(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT), - "operator binding cannot replace Idunn-owned launch environment" - ); - ensure!( - !self - .workload - .environment - .contains_key(IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT) - && !self - .workload - .secret_files - .contains_key(IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT), - "operator binding cannot replace the Idunn-owned process write lease" - ); - let mut available_environment: BTreeSet<_> = self - .workload - .environment - .keys() - .chain( - self.workload - .secret_files - .keys() - .filter(|name| name.as_str() != RUNTIME_PRESENCE_IDENTITY_BINDING), - ) - .cloned() - .collect(); - available_environment.insert(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT.into()); - if declaration.service.route_required { - available_environment.insert(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT.into()); - } - if declaration.write_lease_required() { - available_environment.insert(IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT.into()); - } - ensure!( - declaration - .service - .required_environment - .is_subset(&available_environment), - "operator service environment omits a required launch input" - ); - let declared_environment: BTreeSet<_> = declaration - .service - .required_environment - .union(&declaration.service.optional_environment) - .cloned() - .collect(); - ensure!( - !declared_environment.contains(RUNTIME_PRESENCE_IDENTITY_BINDING), - "runtime presence identity is a named parent-only descriptor, not service environment" - ); - ensure!( - available_environment.is_subset(&declared_environment), - "operator service environment contains an undeclared launch input" - ); - let required_arguments: BTreeSet<_> = declaration - .service - .arguments - .iter() - .filter_map(|argument| match argument { - LaunchArgument::Binding { name } => Some(name.clone()), - LaunchArgument::Literal { .. } => None, - }) - .collect(); - let bound_arguments: BTreeSet<_> = - self.workload.argument_bindings.keys().cloned().collect(); - match ( - self.workload.state_root.as_ref(), - self.workload.argument_bindings.get("state_root"), - ) { - (Some(state_root), Some(argument)) => ensure!( - Path::new(argument) == state_root.as_path(), - "state_root argument binding differs from the admitted workload state root" - ), - (Some(_), None) => bail!("stateful workload has no state_root argument binding"), - (None, Some(_)) => bail!("stateless workload carries a state_root argument binding"), - (None, None) => {} - } - ensure!( - required_arguments.contains("state_root") == self.workload.state_root.is_some(), - "recipe state_root argument must exist exactly when the workload has a state root" - ); - ensure!( - required_arguments == bound_arguments, - "operator argument bindings do not exactly match the launch contract" - ); - match ( - declaration.service.route_required, - declaration.service.transport, - self.route.as_ref(), - ) { - (true, ServiceTransport::Http, Some(route)) - if route.driver == RouteDriver::NginxStreamTcp => - { - ensure!( - route.stable_endpoint.starts_with("http://"), - "HTTP stable endpoint is not an HTTP URI" - ); - } - (true, ServiceTransport::Tcp, Some(route)) - if route.driver == RouteDriver::NginxStreamTcp => - { - ensure!( - route.stable_endpoint.starts_with("tcp://"), - "TCP stable endpoint is not a TCP URI" - ); - } - (true, ServiceTransport::Rudp, Some(route)) - if route.driver == RouteDriver::NginxStreamUdp => - { - ensure!( - route.stable_endpoint.starts_with("rudp://"), - "RUDP stable endpoint is not an RUDP URI" - ); - } - (false, _, None) => {} - _ => bail!("route binding does not match the launch contract"), - } - for dependency in declaration - .dependencies - .iter() - .filter(|dependency| dependency.kind == DependencyKind::ExternalOperatorBinding) - { - ensure!( - self.external_capabilities.iter().any(|binding| { - capability_compatible( - &dependency.capability, - &dependency.schema, - &dependency.compatibility, - &binding.capability, - &binding.schema, - &binding.compatibility, - ) && binding.capacity >= dependency.minimum_capacity - }), - "external capability {} has no compatible operator binding", - dependency.capability - ); - } - Ok(()) - } -} - -pub fn capability_compatible( - required_capability: &str, - required_schema: &str, - required_compatibility: &str, - provided_capability: &str, - provided_schema: &str, - provided_compatibility: &str, -) -> bool { - required_capability == provided_capability - && required_schema == provided_schema - && required_compatibility == provided_compatibility -} - -fn unique_ids<'a>(values: impl Iterator, label: &str) -> Result> { - let mut seen = BTreeSet::new(); - for value in values { - require_id(value, label)?; - ensure!(seen.insert(value), "duplicate {label} id {value}"); - } - Ok(seen) -} - -fn require_id(value: &str, label: &str) -> Result<()> { - ensure!(!value.is_empty(), "{label} is empty"); - ensure!(value.len() <= 96, "{label} is too long"); - ensure!( - value.bytes().all(|byte| byte.is_ascii_lowercase() - || byte.is_ascii_digit() - || matches!(byte, b'-' | b'_' | b'.' | b':')), - "{label} contains an invalid character" - ); - Ok(()) -} - -fn require_capability(value: &str, label: &str) -> Result<()> { - require_id(value, label) -} - -fn require_capability_contract(capability: &str, schema: &str, compatibility: &str) -> Result<()> { - require_capability(capability, "capability")?; - require_capability(schema, "capability schema")?; - require_capability(compatibility, "capability compatibility") -} - -fn require_value(value: &str, label: &str) -> Result<()> { - ensure!(!value.trim().is_empty(), "{label} is empty"); - ensure!( - !value.chars().any(char::is_control), - "{label} contains a control character" - ); - ensure!(value.len() <= 4_096, "{label} is too long"); - Ok(()) -} - -fn validate_launch_argument(argument: &LaunchArgument) -> Result<()> { - match argument { - LaunchArgument::Literal { value } => require_value(value, "literal launch argument"), - LaunchArgument::Binding { name } => require_id(name, "launch argument binding"), - } -} - -fn require_program(value: &str, label: &str) -> Result<()> { - require_value(value, label)?; - ensure!( - !value.contains('/') && !value.contains('\\') && !value.chars().any(char::is_whitespace), - "{label} must be one executable name" - ); - Ok(()) -} - -fn require_git_origin(value: &str, label: &str) -> Result<()> { - ensure!(value.starts_with("https://"), "{label} must use HTTPS"); - ensure!( - value.ends_with(".git"), - "{label} must name a Git repository" - ); - require_value(value, label) -} - -fn https_host(value: &str) -> Result<&str> { - let remainder = value - .strip_prefix("https://") - .ok_or_else(|| anyhow::anyhow!("artifact URL must use HTTPS"))?; - let authority = remainder.split('/').next().unwrap_or_default(); - ensure!(!authority.is_empty(), "artifact URL has no host"); - ensure!( - !authority.contains('@') - && !authority.contains(':') - && !authority.contains('?') - && !authority.contains('#'), - "artifact URL authority is not a bare host" - ); - require_host(authority)?; - Ok(authority) -} - -fn require_environment_name(value: &str) -> Result<()> { - ensure!( - !value.is_empty() && value.len() <= 128, - "environment name is empty or too long" - ); - ensure!( - value - .bytes() - .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_'), - "environment name contains an invalid character" - ); - Ok(()) -} - -fn require_relative_path(path: &Path, label: &str, allow_current: bool) -> Result<()> { - ensure!(!path.as_os_str().is_empty(), "{label} is empty"); - ensure!(!path.is_absolute(), "{label} must be relative"); - let mut saw_normal = false; - for component in path.components() { - match component { - Component::Normal(_) => saw_normal = true, - Component::CurDir if allow_current => {} - _ => bail!("{label} contains a forbidden path component"), - } - } - ensure!(allow_current || saw_normal, "{label} must name a path"); - Ok(()) -} - -fn require_leaf_path(path: &Path, label: &str) -> Result<()> { - require_relative_path(path, label, false)?; - ensure!( - path.components().count() == 1, - "{label} must be a single filename" - ); - Ok(()) -} - -fn require_absolute_path(path: &Path, label: &str) -> Result<()> { - ensure!(path.is_absolute(), "{label} must be absolute"); - ensure!( - path.components() - .all(|component| !matches!(component, Component::ParentDir)), - "{label} contains a parent traversal" - ); - Ok(()) -} - -fn paths_overlap(left: &Path, right: &Path) -> bool { - left.starts_with(right) || right.starts_with(left) -} - -fn require_sha1(value: &str, label: &str) -> Result<()> { - require_lower_hex(value, 40, label) -} - -fn require_sha256(value: &str, label: &str) -> Result<()> { - require_lower_hex(value, 64, label) -} - -fn require_lower_hex(value: &str, length: usize, label: &str) -> Result<()> { - ensure!(value.len() == length, "{label} has the wrong length"); - ensure!( - value - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)), - "{label} must be lowercase hexadecimal" - ); - Ok(()) -} - -fn require_pinned_image(value: &str) -> Result<()> { - let Some((name, digest)) = value.rsplit_once("@sha256:") else { - bail!("runner image is not pinned by sha256 digest"); - }; - require_value(name, "runner image name")?; - require_sha256(digest, "runner image digest") -} - -fn require_container_identity(value: &str) -> Result<()> { - let (uid, gid) = value - .split_once(':') - .context("runner user must be an explicit numeric UID:GID")?; - let uid: u32 = uid.parse().context("runner UID is not a u32")?; - let gid: u32 = gid.parse().context("runner GID is not a u32")?; - ensure!(uid > 0 && gid > 0, "runner identity must be unprivileged"); - Ok(()) -} - -fn require_identity(value: &str, label: &str) -> Result<()> { - require_id(value, label) -} - -fn require_unit(value: &str, label: &str) -> Result<()> { - require_value(value, label)?; - ensure!( - value.ends_with(".service"), - "{label} must be a systemd service unit" - ); - ensure!( - !value.contains('/') && !value.contains('\\'), - "{label} must not contain a path" - ); - Ok(()) -} - -fn require_host(value: &str) -> Result<()> { - require_value(value, "host")?; - ensure!( - !value.contains('/') && !value.contains('@'), - "host contains an invalid delimiter" - ); - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - const RECIPE: &str = r#" -schema = "gamecult.idunn.target_declaration.v1" -target = "test-service" -source_stamp_environment = "TEST_SERVICE_BUILD_COMMIT" - -[[steps]] -id = "test" -phase = "test" -runner = "rust" -argv = ["cargo", "test", "--locked", "-p", "test-service"] - -[[steps]] -id = "build" -phase = "build" -runner = "rust" -argv = ["cargo", "build", "--locked", "--release", "-p", "test-service"] - -[[external_inputs]] -id = "tool" -url = "https://registry.npmjs.org/tool.tgz" -sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -runner = "rust" -destination = "inputs/tool.tgz" - -[[artifacts]] -id = "daemon" -source_kind = "runner-output" -runner = "rust" -source = "target/release/test-service" -destination = "test-service" -expected_sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" -executable = true - -[service] -executable_artifact = "daemon" -required_adjacent_artifacts = [] -arguments = [ - { kind = "literal", value = "--state-root" }, - { kind = "binding", name = "state_root" }, -] -transport = "http" -route_required = true -required_environment = ["GAMECULT_IDUNN_CANDIDATE_BIND", "GAMECULT_IDUNN_PROCESS_WRITE_LEASE", "GAMECULT_IDUNN_RUNTIME_BUNDLE"] - -[service.health] -contract = "test-service.cultnet-service-health" - -[state] -schema_generation = "v1" - -[[state.slots]] -id = "world" -relative_path = "world.cc" -kind = "cultcache-file" -schema = "test-service.state.v1" -writer = "process-bound-single-writer" -recovery = "preserve" -startup = "create-or-open-after-write-lease" - -[[provides]] -capability = "test-service.runtime" -schema = "test-service.state.v1" -compatibility = "v1" - -[[dependencies]] -kind = "shared-infrastructure" -capability = "odin.verse-rendezvous" -schema = "odin.verse-topology.v1" -compatibility = "v1" -startup = "before-promotion" -"#; - - const BINDING: &str = r#" -schema = "gamecult.idunn.operator_binding.v2" -target = "test-service" -profiles = ["aetheria", "full-gamecult"] - -[repository] -origin = "https://github.com/GameCult/TestService.git" -admitted_ref = "refs/heads/main" -minimum_revision = "13d5136b69bcd3a52c400d66a940f94a47122e48" -selection = "ref-head" -checkout = "/srv/build/TestService" -recipe_path = "deployment/idunn/recipe.toml" - -[runners.rust] -driver = "docker" -image = "rust@sha256:4c2fd73ef19c5ef9d54bee03b06b2839a392604fbfcd578ed948b71b37c1d7fb" -user = "1000:1000" -affordances = ["source-read", "artifact-write", "build-cache"] -cache_root = "/srv/ghostlight/build-cache" -allowed_programs = ["cargo"] -network_profile = "build-dependency-egress" -memory_mebibytes = 8192 -cpu_quota_percent = 400 -pids_limit = 512 -tmpfs_mebibytes = 1024 - -[workload] -driver = "systemd-transient" -state_group = "test-service" -unit_prefix = "idunn-test-service" -release_root = "/srv/test-service/releases" -state_root = "/var/lib/gamecult/test-service" -runtime_root = "/etc/gamecult/test-service/runtime" -network = "host-private" -hardening = "strict" -memory_mebibytes = 2048 -cpu_quota_percent = 200 - -[workload.argument_bindings] -state_root = "/var/lib/gamecult/test-service" - -[workload.secret_files] -GAMECULT_RUNTIME_PRESENCE_IDENTITY = "/etc/gamecult/test-service/runtime-presence-identity.cc" - -[runtime_identity] -runtime_id = "test-service-yggdrasil" -expected_signer_identity_id = "test-service-runtime-signer" -trust_anchor_store = "/etc/gamecult/trust/test-service.cc" - -[route] -driver = "nginx-stream-tcp" -route_id = "test-service-public" -stable_endpoint = "http://127.0.0.1:18830" -private_host = "127.0.0.1" -private_port_start = 18831 -private_port_end = 18839 -config_path = "/etc/nginx/idunn-stream-routes/test-service.conf" -reload_unit = "nginx.service" - -[process_write_lease] -record_path = "/etc/gamecult/test-service/runtime/process-write-lease.cc" - -[brakes] -deployment_store = "/var/lib/gamecult/idunn-authority/test-service-deployment-brake.cc" -lifecycle_store = "/var/lib/gamecult/idunn-authority/test-service-lifecycle-brake.cc" - -[rollout] -strategy = "candidate-then-promote" -drain_seconds = 30 -retain_releases = 2 - -[placement] -desired_replicas = 1 -nodes = ["yggdrasil"] -"#; - - #[test] - fn strict_recipe_and_binding_admit_without_host_privilege_in_recipe() { - let recipe = TargetDeclaration::parse(RECIPE).unwrap(); - let binding = OperatorBinding::parse(BINDING).unwrap(); - binding.admit(&recipe).unwrap(); - assert_eq!(recipe.target, "test-service"); - assert_eq!(binding.route.as_ref().unwrap().private_port_start, 18831); - } - - #[test] - fn unknown_recipe_field_is_rejected() { - let input = RECIPE.replace( - "target = \"test-service\"", - "target = \"test-service\"\nroot = true", - ); - assert!(TargetDeclaration::parse(&input).is_err()); - } - - #[test] - fn operator_cannot_omit_an_affordance_derived_from_the_recipe() { - let recipe = TargetDeclaration::parse(RECIPE).unwrap(); - let input = BINDING.replace( - "affordances = [\"source-read\", \"artifact-write\", \"build-cache\"]", - "affordances = [\"source-read\", \"build-cache\"]", - ); - let binding = OperatorBinding::parse(&input).unwrap(); - assert!(binding.admit(&recipe).is_err()); - } - - #[test] - fn runner_mounts_require_their_exact_operator_affordance() { - let cache_without_affordance = BINDING.replace( - "affordances = [\"source-read\", \"artifact-write\", \"build-cache\"]", - "affordances = [\"source-read\", \"artifact-write\"]", - ); - assert!(OperatorBinding::parse(&cache_without_affordance).is_err()); - - let affordance_without_secret = BINDING.replace( - "affordances = [\"source-read\", \"artifact-write\", \"build-cache\"]", - "affordances = [\"source-read\", \"artifact-write\", \"build-cache\", \"secret-read\"]", - ); - assert!(OperatorBinding::parse(&affordance_without_secret).is_err()); - } - - #[test] - fn runner_cannot_replace_the_source_stamp() { - let recipe = TargetDeclaration::parse(RECIPE).unwrap(); - let forged = BINDING.replace( - "[workload]", - "[runners.rust.environment]\nTEST_SERVICE_BUILD_COMMIT = \"forged\"\n\n[workload]", - ); - let binding = OperatorBinding::parse(&forged).unwrap(); - assert!(binding.admit(&recipe).is_err()); - } - - #[test] - fn route_transport_mismatch_is_rejected() { - let recipe = TargetDeclaration::parse(RECIPE).unwrap(); - assert!( - OperatorBinding::parse(&BINDING.replace("nginx-stream-tcp", "nginx-stream-udp")) - .is_err() - ); - - assert!( - OperatorBinding::parse( - &BINDING.replace("http://127.0.0.1:18830", "tcp://yggdrasil.gamecult.org:443",), - ) - .is_err() - ); - assert!(recipe.service.route_required); - } - - #[test] - fn rudp_route_uses_the_udp_stream_driver() { - let recipe = TargetDeclaration::parse( - &RECIPE.replace("transport = \"http\"", "transport = \"rudp\""), - ) - .unwrap(); - let binding = OperatorBinding::parse( - &BINDING - .replace("nginx-stream-tcp", "nginx-stream-udp") - .replace("http://127.0.0.1:18830", "rudp://127.0.0.1:17872"), - ) - .unwrap(); - assert!(binding.admit(&recipe).is_ok()); - } - - #[test] - fn raw_unit_template_is_rejected() { - let input = RECIPE.replace( - "executable_artifact = \"daemon\"", - "executable_artifact = \"daemon\"\nunit_template = \"deployment/root.service\"", - ); - assert!(TargetDeclaration::parse(&input).is_err()); - } - - #[test] - fn extra_operator_environment_is_rejected() { - let recipe = TargetDeclaration::parse(RECIPE).unwrap(); - let input = BINDING.replace( - "[workload.argument_bindings]", - "[workload.environment]\nUNDECLARED = \"no\"\n\n[workload.argument_bindings]", - ); - let binding = OperatorBinding::parse(&input).unwrap(); - assert!(binding.admit(&recipe).is_err()); - } - - #[test] - fn runtime_presence_identity_is_exactly_one_parent_only_secret_source() { - let secret = "[workload.secret_files]\nGAMECULT_RUNTIME_PRESENCE_IDENTITY = \"/etc/gamecult/test-service/runtime-presence-identity.cc\"\n\n"; - assert!(OperatorBinding::parse(&BINDING.replace(secret, "")).is_err()); - assert!(OperatorBinding::parse(&BINDING.replace( - secret, - "[workload.environment]\nGAMECULT_RUNTIME_PRESENCE_IDENTITY = \"/etc/gamecult/test-service/runtime-presence-identity.cc\"\n\n", - )) - .is_err()); - assert!(OperatorBinding::parse(&BINDING.replace( - secret, - "[workload.secret_files]\nGAMECULT_RUNTIME_PRESENCE_IDENTITY = \"/etc/gamecult/test-service/runtime-presence-identity.cc\"\nDUPLICATE_IDENTITY = \"/etc/gamecult/test-service/runtime-presence-identity.cc\"\n\n", - )) - .is_err()); - - let recipe = TargetDeclaration::parse(&RECIPE.replace( - "required_environment = [", - "required_environment = [\"GAMECULT_RUNTIME_PRESENCE_IDENTITY\", ", - )) - .unwrap(); - let binding = OperatorBinding::parse(BINDING).unwrap(); - assert!(binding.admit(&recipe).is_err()); - } - - #[test] - fn operator_cannot_replace_idunn_owned_launch_inputs() { - let recipe = TargetDeclaration::parse(RECIPE).unwrap(); - for name in [ - IDUNN_RUNTIME_BUNDLE_ENVIRONMENT, - IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, - IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT, - ] { - let input = BINDING.replace( - "[workload.argument_bindings]", - &format!( - "[workload.environment]\n{name} = \"forged\"\n\n[workload.argument_bindings]" - ), - ); - let rejected = OperatorBinding::parse(&input) - .and_then(|binding| binding.admit(&recipe).map(|_| ())); - assert!(rejected.is_err()); - } - } - - #[test] - fn state_slot_path_cannot_escape_the_operator_owned_root() { - let input = RECIPE.replace( - "relative_path = \"world.cc\"", - "relative_path = \"../world.cc\"", - ); - assert!(TargetDeclaration::parse(&input).is_err()); - } - - #[test] - fn mismatched_state_root_argument_binding_is_rejected() { - let recipe = TargetDeclaration::parse(RECIPE).unwrap(); - let mismatched = BINDING.replace( - "[workload.argument_bindings]\nstate_root = \"/var/lib/gamecult/test-service\"", - "[workload.argument_bindings]\nstate_root = \"/var/lib/gamecult/another-service\"", - ); - let binding = OperatorBinding::parse(&mismatched).unwrap(); - assert!(binding.admit(&recipe).is_err()); - } - - #[test] - fn external_file_state_keeps_process_bound_writer_and_lease_semantics() { - let input = RECIPE.replace("kind = \"cultcache-file\"", "kind = \"external-file\""); - let declaration = TargetDeclaration::parse(&input).unwrap(); - let slot = &declaration.state.as_ref().unwrap().slots[0]; - assert_eq!(slot.kind, StateKind::ExternalFile); - assert_eq!(slot.writer, StateWriter::ProcessBoundSingleWriter); - assert_eq!(slot.startup, StateStartup::CreateOrOpenAfterWriteLease); - assert!(declaration.write_lease_required()); - } - - #[test] - fn state_slots_cannot_claim_overlapping_paths() { - let input = RECIPE.replace( - "startup = \"create-or-open-after-write-lease\"", - "startup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"nested\"\nrelative_path = \"world.cc/index.cc\"\nkind = \"cultcache-file\"\nschema = \"test-service.index.v1\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"", - ); - assert!(TargetDeclaration::parse(&input).is_err()); - } - - #[test] - fn workload_mount_cannot_bypass_write_lease_controlled_state() { - let input = BINDING.replace( - "cpu_quota_percent = 200\n\n[workload.argument_bindings]", - "cpu_quota_percent = 200\nread_write_paths = [\"/var/lib/gamecult/test-service/world\"]\n\n[workload.argument_bindings]", - ); - assert!(OperatorBinding::parse(&input).is_err()); - } - - #[test] - fn v2_binding_is_explicitly_singleton() { - assert!( - OperatorBinding::parse( - &BINDING.replace("desired_replicas = 1", "desired_replicas = 2") - ) - .is_err() - ); - assert!( - OperatorBinding::parse(&BINDING.replace( - "nodes = [\"yggdrasil\"]", - "nodes = [\"yggdrasil\", \"raven\"]" - )) - .is_err() - ); - } - - #[test] - fn legacy_static_workload_identity_has_no_authority_in_v2() { - assert!( - OperatorBinding::parse(&BINDING.replace( - "schema = \"gamecult.idunn.operator_binding.v2\"", - "schema = \"gamecult.idunn.operator_binding.v1\"", - ),) - .is_err() - ); - let with_static_identity = BINDING.replace( - "driver = \"systemd-transient\"", - "driver = \"systemd-transient\"\nuser = \"test-service\"\ngroup = \"test-service\"", - ); - assert!(OperatorBinding::parse(&with_static_identity).is_err()); - } - - #[test] - fn writable_state_requires_one_non_root_state_group() { - assert!( - OperatorBinding::parse(&BINDING.replace("state_group = \"test-service\"\n", ""),) - .is_err() - ); - assert!( - OperatorBinding::parse( - &BINDING.replace("state_group = \"test-service\"", "state_group = \"root\""), - ) - .is_err() - ); - } - - #[test] - fn external_input_uses_an_operator_bound_network_profile() { - let recipe = TargetDeclaration::parse(RECIPE).unwrap(); - let binding = OperatorBinding::parse(BINDING).unwrap(); - binding.admit(&recipe).unwrap(); - let isolated = BINDING.replace("network_profile = \"build-dependency-egress\"\n", ""); - let binding = OperatorBinding::parse(&isolated).unwrap(); - assert!(binding.admit(&recipe).is_err()); - } - - #[test] - fn process_write_lease_exists_exactly_for_process_writable_state() { - let recipe = TargetDeclaration::parse(RECIPE).unwrap(); - let without_lease = BINDING.replace( - "[process_write_lease]\nrecord_path = \"/etc/gamecult/test-service/runtime/process-write-lease.cc\"\n\n", - "", - ); - let binding = OperatorBinding::parse(&without_lease).unwrap(); - assert!(binding.admit(&recipe).is_err()); - - let read_only_recipe = TargetDeclaration::parse( - &RECIPE - .replace( - "writer = \"process-bound-single-writer\"", - "writer = \"none\"", - ) - .replace( - "startup = \"create-or-open-after-write-lease\"", - "startup = \"open-at-start\"", - ) - .replace("\"GAMECULT_IDUNN_PROCESS_WRITE_LEASE\", ", ""), - ) - .unwrap(); - binding.admit(&read_only_recipe).unwrap(); - - let binding = OperatorBinding::parse(BINDING).unwrap(); - assert_eq!( - binding.process_write_lease.as_ref().unwrap().lock_path(), - PathBuf::from("/etc/gamecult/test-service/runtime/process-write-lease.cc.lock") - ); - assert!(binding.admit(&read_only_recipe).is_err()); - } - - #[test] - fn stateless_target_has_no_state_binding_or_generation() { - let mut recipe_text = RECIPE.replace( - "arguments = [\n { kind = \"literal\", value = \"--state-root\" },\n { kind = \"binding\", name = \"state_root\" },\n]", - "arguments = []", - ); - recipe_text = recipe_text.replace("\"GAMECULT_IDUNN_PROCESS_WRITE_LEASE\", ", ""); - let state_start = recipe_text.find("\n[state]\n").unwrap(); - let state_end = recipe_text.find("\n[[provides]]\n").unwrap(); - recipe_text.replace_range(state_start..state_end, ""); - let recipe = TargetDeclaration::parse(&recipe_text).unwrap(); - assert!(recipe.state.is_none()); - - let binding_text = BINDING - .replace("state_group = \"test-service\"\n", "") - .replace("state_root = \"/var/lib/gamecult/test-service\"\n", "") - .replace( - "[workload.argument_bindings]\nstate_root = \"/var/lib/gamecult/test-service\"\n\n", - "", - ) - .replace( - "[process_write_lease]\nrecord_path = \"/etc/gamecult/test-service/runtime/process-write-lease.cc\"\n\n", - "", - ); - let binding = OperatorBinding::parse(&binding_text).unwrap(); - binding.admit(&recipe).unwrap(); - assert!(binding.workload.state_root.is_none()); - } - - #[test] - fn bootstrap_dependency_must_be_available_before_start() { - let invalid = RECIPE.replace("kind = \"shared-infrastructure\"", "kind = \"bootstrap\""); - assert!(TargetDeclaration::parse(&invalid).is_err()); - let valid = invalid.replace( - "startup = \"before-promotion\"", - "startup = \"before-start\"", - ); - TargetDeclaration::parse(&valid).unwrap(); - } - - #[test] - fn dependency_compatibility_requires_exact_typed_contract() { - assert!(capability_compatible( - "odin.verse-rendezvous", - "odin.verse-topology.v1", - "v1", - "odin.verse-rendezvous", - "odin.verse-topology.v1", - "v1", - )); - assert!(!capability_compatible( - "odin.verse-rendezvous", - "odin.verse-topology.v1", - "v1", - "odin.verse-rendezvous", - "odin.verse-topology.v2", - "v2", - )); - } -} diff --git a/crates/idunn-daemon/src/deployment_plan.rs b/crates/idunn-daemon/src/deployment_plan.rs deleted file mode 100644 index 9475701..0000000 --- a/crates/idunn-daemon/src/deployment_plan.rs +++ /dev/null @@ -1,1560 +0,0 @@ -use std::collections::{BTreeMap, BTreeSet}; -use std::path::PathBuf; - -use anyhow::{Context, Result, bail, ensure}; -pub use cultnet_rs::IdunnExpectedIncarnationRecord as ExpectedIncarnation; -use cultnet_rs::{ - IDUNN_EXPECTED_INCARNATION_SCHEMA, IdunnExpectedCapability, IdunnExpectedDependency, - IdunnExpectedRoute, -}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; - -use crate::control_plane::SequenceAdmittedReady; -use crate::deployment::{ - CapabilityDependency, DependencyKind, ExternalCapabilityBinding, OperatorBinding, - ServiceTransport, SourceSelectionPolicy, StartupOrder, StateDeclaration, TargetDeclaration, - capability_compatible, -}; - -pub const SOURCE_SELECTION_FACTS_SCHEMA: &str = "idunn.source_selection_facts.v1"; -pub const COMPILED_DEPLOYMENT_PLAN_SCHEMA: &str = "idunn.compiled_deployment_plan.v2"; -pub const SEALED_RELEASE_SCHEMA: &str = "idunn.sealed_release.v1"; - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct GitlinkTreeFact { - pub origin: String, - pub revision: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "policy", rename_all = "kebab-case", deny_unknown_fields)] -pub enum SourceSelection { - PinnedObject, - RefHead, - SignedRelease { release_authority_id: String }, -} - -/// Private facts emitted by the future narrow source driver. Structural -/// validation here does not prove Git ancestry, signatures, or object custody. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct SourceSelectionFacts { - pub schema: String, - pub origin: String, - pub admitted_ref: String, - pub admitted_ref_revision: String, - pub revision: String, - pub source_tree: String, - pub recipe_path: PathBuf, - pub recipe_blob_sha256: String, - pub gitlinks: BTreeMap, - pub selection: SourceSelection, - pub selected_at_unix_millis: u64, -} - -impl SourceSelectionFacts { - pub fn validate_against(&self, binding: &OperatorBinding) -> Result<()> { - binding.validate()?; - ensure!( - self.schema == SOURCE_SELECTION_FACTS_SCHEMA, - "unsupported source-selection facts schema" - ); - ensure!( - self.origin == binding.repository.origin, - "selected origin differs from binding" - ); - ensure!( - self.admitted_ref == binding.repository.admitted_ref, - "selected ref differs from binding" - ); - require_sha1( - &self.admitted_ref_revision, - "selected admitted-ref revision", - )?; - require_sha1(&self.revision, "selected revision")?; - require_sha1(&self.source_tree, "selected source tree")?; - ensure!( - self.recipe_path == binding.repository.recipe_path, - "selected recipe path differs from binding" - ); - require_sha256(&self.recipe_blob_sha256, "selected recipe blob")?; - ensure!( - self.selected_at_unix_millis > 0, - "source-selection facts have no time" - ); - - match (&binding.repository.selection, &self.selection) { - (SourceSelectionPolicy::PinnedObject, SourceSelection::PinnedObject) => { - let pinned_revision = binding - .repository - .pinned_revision - .as_deref() - .context("validated pinned binding has no revision")?; - ensure!( - self.revision == pinned_revision, - "selected source differs from the pinned revision" - ); - } - (SourceSelectionPolicy::RefHead, SourceSelection::RefHead) => ensure!( - self.revision == self.admitted_ref_revision, - "ref-head selection differs from the fetched admitted-ref revision" - ), - ( - SourceSelectionPolicy::SignedRelease, - SourceSelection::SignedRelease { - release_authority_id, - }, - ) => { - require_token(release_authority_id, "release authority id")?; - } - _ => bail!("source-selection facts do not match operator policy"), - } - - let expected_paths: BTreeSet<_> = binding.repository.gitlinks.keys().cloned().collect(); - let observed_paths: BTreeSet<_> = self.gitlinks.keys().cloned().collect(); - ensure!( - expected_paths == observed_paths, - "Gitlink tree facts differ from binding" - ); - for (path, receipt) in &self.gitlinks { - let expected = &binding.repository.gitlinks[path]; - ensure!( - receipt.origin == expected.origin, - "Gitlink {} origin differs from binding", - path.display() - ); - require_sha1(&receipt.revision, "Gitlink revision")?; - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] -pub enum DependencyProviderAuthority { - ManagedReady { - target: String, - incarnation_id: String, - plan_id: String, - sealed_release_id: String, - expected_projection_sha256: String, - odin_topology_correlation_sha256: String, - odin_topology_publisher_sequence: u64, - }, - ExternalOperatorBinding { - binding_target: String, - }, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct DependencyProviderRef { - pub provider_id: String, - pub authority: DependencyProviderAuthority, - pub capability: String, - pub schema: String, - pub compatibility: String, - pub capacity: u32, - pub endpoint: Option, -} - -impl DependencyProviderRef { - pub fn validate(&self) -> Result<()> { - require_token(&self.provider_id, "dependency provider id")?; - require_contract(&self.capability, &self.schema, &self.compatibility)?; - ensure!(self.capacity > 0, "dependency provider capacity is zero"); - if let Some(endpoint) = &self.endpoint { - require_value(endpoint, "dependency provider endpoint")?; - } - match &self.authority { - DependencyProviderAuthority::ManagedReady { - target, - incarnation_id, - plan_id, - sealed_release_id, - expected_projection_sha256, - odin_topology_correlation_sha256, - odin_topology_publisher_sequence, - } => { - require_token(target, "managed provider target")?; - require_token(incarnation_id, "managed provider incarnation")?; - require_sha256(plan_id, "managed provider plan")?; - require_sha256(sealed_release_id, "managed provider sealed release")?; - require_sha256(expected_projection_sha256, "managed expected projection")?; - require_sha256( - odin_topology_correlation_sha256, - "managed Odin topology correlation", - )?; - ensure!( - *odin_topology_publisher_sequence > 0, - "managed Odin topology sequence is zero" - ); - } - DependencyProviderAuthority::ExternalOperatorBinding { binding_target } => { - require_token(binding_target, "external binding target")?; - ensure!( - self.endpoint.is_some(), - "external binding has no configured endpoint" - ); - } - } - Ok(()) - } - - fn compatible_with(&self, dependency: &CapabilityDependency) -> bool { - capability_compatible( - &dependency.capability, - &dependency.schema, - &dependency.compatibility, - &self.capability, - &self.schema, - &self.compatibility, - ) && self.capacity >= dependency.minimum_capacity - } - - fn is_external_binding(&self) -> bool { - matches!( - &self.authority, - DependencyProviderAuthority::ExternalOperatorBinding { .. } - ) - } -} - -pub fn external_binding_provider_refs( - binding: &OperatorBinding, -) -> Result> { - binding.validate()?; - let providers = binding - .external_capabilities - .iter() - .map(|capability| expected_external_provider(&binding.target, capability)) - .collect::>(); - for provider in &providers { - provider.validate()?; - } - Ok(providers) -} - -fn expected_external_provider( - binding_target: &str, - capability: &ExternalCapabilityBinding, -) -> DependencyProviderRef { - DependencyProviderRef { - provider_id: capability.provider_id.clone(), - authority: DependencyProviderAuthority::ExternalOperatorBinding { - binding_target: binding_target.to_owned(), - }, - capability: capability.capability.clone(), - schema: capability.schema.clone(), - compatibility: capability.compatibility.clone(), - capacity: capability.capacity, - endpoint: Some(capability.endpoint.clone()), - } -} - -/// Projects one authenticated Ready correlation into dependency-selection -/// inputs. Authentication is not replay admission: the control-plane store -/// must atomically admit `publisher_sequence` before calling this function and -/// must re-check the selected receipt before promotion. -fn managed_ready_provider_refs( - admitted: &SequenceAdmittedReady, -) -> Result> { - let expected = admitted.expected(); - let topology = admitted.authenticated(); - expected.validate()?; - let expected_projection_sha256 = expected.canonical_sha256()?; - let observed = topology.record(); - ensure!( - observed.expected_projection_sha256 == expected_projection_sha256, - "Ready provider topology names a different Expected projection" - ); - ensure!( - observed.target == expected.target && observed.runtime_id == expected.runtime_id, - "Ready provider topology names a different target or runtime" - ); - ensure!( - observed.expected - && observed.present - && observed.ready - && observed.observed_presence_state.as_deref() == Some("active") - && observed.disagreements.is_empty(), - "managed provider topology is not Ready" - ); - let odin_topology_correlation_sha256 = admitted.evidence_sha256().to_owned(); - let endpoint = expected - .route - .as_ref() - .map(|route| route.stable_endpoint.clone()); - let mut providers = Vec::new(); - for capability in &observed.observed_capabilities { - providers.push(DependencyProviderRef { - provider_id: expected.target.clone(), - authority: DependencyProviderAuthority::ManagedReady { - target: expected.target.clone(), - incarnation_id: expected.incarnation_id.clone(), - plan_id: expected.plan_id.clone(), - sealed_release_id: expected.sealed_release_id.clone(), - expected_projection_sha256: expected_projection_sha256.clone(), - odin_topology_correlation_sha256: odin_topology_correlation_sha256.clone(), - odin_topology_publisher_sequence: admitted.publisher_sequence(), - }, - capability: capability.capability.clone(), - schema: capability.schema.clone(), - compatibility: capability.compatibility.clone(), - capacity: capability.capacity, - endpoint: endpoint.clone(), - }); - } - for provider in &providers { - provider.validate()?; - } - Ok(providers) -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct DependencySelection { - pub requirement: CapabilityDependency, - pub provider: Option, -} - -impl DependencySelection { - fn validate(&self) -> Result<()> { - require_contract( - &self.requirement.capability, - &self.requirement.schema, - &self.requirement.compatibility, - )?; - ensure!( - self.requirement.minimum_capacity > 0, - "dependency capacity is zero" - ); - if let Some(provider) = &self.provider { - provider.validate()?; - ensure!( - provider.compatible_with(&self.requirement), - "selected provider is incompatible" - ); - ensure!( - (self.requirement.kind == DependencyKind::ExternalOperatorBinding) - == provider.is_external_binding(), - "selected provider authority does not match dependency kind" - ); - } else { - ensure!( - self.requirement.kind == DependencyKind::Optional, - "required dependency is unresolved" - ); - } - Ok(()) - } - - fn expected_projection(&self) -> Result { - self.validate()?; - let ( - provider_id, - provider_authority, - provider_expected_projection_sha256, - provider_endpoint, - ) = match &self.provider { - None => (None, None, None, None), - Some(provider) => match &provider.authority { - DependencyProviderAuthority::ManagedReady { - expected_projection_sha256, - .. - } => ( - Some(provider.provider_id.clone()), - Some("managed-incarnation".into()), - Some(expected_projection_sha256.clone()), - provider.endpoint.clone(), - ), - DependencyProviderAuthority::ExternalOperatorBinding { .. } => ( - Some(provider.provider_id.clone()), - Some("external-operator-binding".into()), - None, - provider.endpoint.clone(), - ), - }, - }; - Ok(IdunnExpectedDependency { - kind: dependency_kind_name(self.requirement.kind).into(), - capability: self.requirement.capability.clone(), - schema: self.requirement.schema.clone(), - compatibility: self.requirement.compatibility.clone(), - minimum_capacity: self.requirement.minimum_capacity, - startup: startup_order_name(self.requirement.startup).into(), - provider_id, - provider_authority, - provider_expected_projection_sha256, - provider_endpoint, - }) - } -} - -pub fn select_dependencies( - declaration: &TargetDeclaration, - providers: &[DependencyProviderRef], -) -> Result> { - declaration.validate()?; - let mut unique_contracts = BTreeSet::new(); - for provider in providers { - provider.validate()?; - ensure!( - unique_contracts.insert(( - provider.provider_id.as_str(), - provider.capability.as_str(), - provider.schema.as_str(), - provider.compatibility.as_str(), - )), - "dependency provider contract is duplicated" - ); - } - for conflict in &declaration.conflicts { - if providers - .iter() - .any(|provider| provider.capability == conflict.capability) - { - bail!( - "capability conflict {}: {}", - conflict.capability, - conflict.reason - ); - } - } - declaration - .dependencies - .iter() - .map(|dependency| { - let mut candidates = providers - .iter() - .filter(|provider| provider.compatible_with(dependency)) - .filter(|provider| { - (dependency.kind == DependencyKind::ExternalOperatorBinding) - == provider.is_external_binding() - }) - .cloned() - .collect::>(); - candidates.sort_by(|left, right| { - left.provider_id - .cmp(&right.provider_id) - .then_with(|| left.endpoint.cmp(&right.endpoint)) - }); - let provider = candidates.into_iter().next(); - if provider.is_none() && dependency.kind != DependencyKind::Optional { - bail!( - "no expected provider satisfies {} {} {}", - dependency.capability, - dependency.schema, - dependency.compatibility - ); - } - let selection = DependencySelection { - requirement: dependency.clone(), - provider, - }; - selection.validate()?; - Ok(selection) - }) - .collect() -} - -/// Private Idunn control-plane state. This contains host binding details and is -/// never an Odin/CultMesh projection. The shared CultNet Expected incarnation -/// is the sanitized topology projection derived only after a release validates -/// against this plan. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct CompiledDeploymentPlan { - pub schema: String, - pub plan_id: String, - pub incarnation_id: String, - pub created_at_unix_millis: u64, - pub source: SourceSelectionFacts, - pub recipe_blob: Vec, - pub binding_blob: Vec, - pub dependencies: Vec, - pub candidate_port: Option, -} - -impl CompiledDeploymentPlan { - pub fn validate(&self) -> Result<()> { - ensure!( - self.schema == COMPILED_DEPLOYMENT_PLAN_SCHEMA, - "unsupported deployment-plan schema" - ); - require_sha256(&self.plan_id, "plan id")?; - require_token(&self.incarnation_id, "plan incarnation")?; - ensure!( - self.created_at_unix_millis >= self.source.selected_at_unix_millis, - "deployment plan predates source selection" - ); - let (declaration, binding) = self.parsed_inputs()?; - self.source.validate_against(&binding)?; - ensure!( - sha256_id(&self.recipe_blob) == self.source.recipe_blob_sha256, - "selected recipe blob differs from the exact plan recipe bytes" - ); - let declared_requirements: Vec<_> = declaration.dependencies.iter().collect(); - let selected_requirements: Vec<_> = self - .dependencies - .iter() - .map(|selection| &selection.requirement) - .collect(); - ensure!( - declared_requirements == selected_requirements, - "selected graph differs from recipe dependencies" - ); - for selection in &self.dependencies { - selection.validate()?; - } - match (&binding.route, self.candidate_port) { - (Some(bound), Some(port)) => { - ensure!( - (bound.private_port_start..=bound.private_port_end).contains(&port), - "candidate port is outside the operator range" - ); - } - (None, None) => {} - (Some(_), None) => bail!("routed deployment has no candidate port"), - (None, Some(_)) => bail!("private deployment selected a routed candidate port"), - } - ensure!( - self.plan_id == self.recomputed_plan_id()?, - "deployment plan digest is not canonical" - ); - Ok(()) - } - - pub(crate) fn parsed_inputs(&self) -> Result<(TargetDeclaration, OperatorBinding)> { - let recipe_text = std::str::from_utf8(&self.recipe_blob) - .context("stored deployment recipe is not UTF-8")?; - let binding_text = std::str::from_utf8(&self.binding_blob) - .context("stored operator binding is not UTF-8")?; - let declaration = TargetDeclaration::parse(recipe_text)?; - let binding = OperatorBinding::parse(binding_text)?; - binding.admit(&declaration)?; - Ok((declaration, binding)) - } - - fn recomputed_plan_id(&self) -> Result { - let mut unsigned = self.clone(); - unsigned.plan_id.clear(); - Ok(sha256_id( - &rmp_serde::to_vec(&unsigned).context("encoding deployment plan identity")?, - )) - } -} - -#[allow(clippy::too_many_arguments)] -pub(crate) fn compile_deployment_plan( - recipe_bytes: &[u8], - binding_bytes: &[u8], - source: SourceSelectionFacts, - incarnation_id: impl Into, - candidate_port: Option, - created_at_unix_millis: u64, - managed_ready_providers: &[SequenceAdmittedReady], -) -> Result { - let recipe_text = std::str::from_utf8(recipe_bytes).context("recipe is not UTF-8")?; - let binding_text = std::str::from_utf8(binding_bytes).context("binding is not UTF-8")?; - let declaration = TargetDeclaration::parse(recipe_text)?; - let binding = OperatorBinding::parse(binding_text)?; - binding.admit(&declaration)?; - source.validate_against(&binding)?; - ensure!( - sha256_id(recipe_bytes) == source.recipe_blob_sha256, - "selected recipe blob differs from compiled recipe bytes" - ); - let incarnation_id = incarnation_id.into(); - require_token(&incarnation_id, "deployment incarnation")?; - ensure!( - created_at_unix_millis >= source.selected_at_unix_millis, - "deployment plan predates source selection" - ); - let mut providers = Vec::new(); - for provider in managed_ready_providers { - providers.extend(managed_ready_provider_refs(provider)?); - } - providers.extend(external_binding_provider_refs(&binding)?); - let dependencies = select_dependencies(&declaration, &providers)?; - let mut plan = CompiledDeploymentPlan { - schema: COMPILED_DEPLOYMENT_PLAN_SCHEMA.into(), - plan_id: String::new(), - incarnation_id, - created_at_unix_millis, - source, - recipe_blob: recipe_bytes.to_vec(), - binding_blob: binding_bytes.to_vec(), - dependencies, - candidate_port, - }; - plan.plan_id = plan.recomputed_plan_id()?; - plan.validate()?; - Ok(plan) -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ArtifactReceipt { - pub artifact_id: String, - pub destination: PathBuf, - pub sha256: String, - pub size_bytes: u64, - pub executable: bool, -} - -impl ArtifactReceipt { - fn validate(&self, declaration: &TargetDeclaration) -> Result<()> { - require_token(&self.artifact_id, "artifact receipt id")?; - require_sha256(&self.sha256, "artifact digest")?; - ensure!(self.size_bytes > 0, "sealed artifact is empty"); - let declared = declaration - .artifacts - .iter() - .find(|artifact| artifact.id == self.artifact_id) - .with_context(|| format!("plan declares no artifact {}", self.artifact_id))?; - ensure!( - self.destination == declared.destination && self.executable == declared.executable, - "artifact receipt differs from declared output" - ); - if let Some(expected_sha256) = &declared.expected_sha256 { - ensure!( - self.sha256 == prefixed_sha256(expected_sha256), - "artifact receipt differs from the recipe-pinned digest" - ); - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ExternalInputMaterializationReceipt { - pub input_id: String, - pub url: String, - pub sha256: String, - pub runner: String, - pub destination: PathBuf, - pub size_bytes: u64, -} - -impl ExternalInputMaterializationReceipt { - fn validate(&self, declaration: &TargetDeclaration) -> Result<()> { - require_token(&self.input_id, "external input receipt id")?; - require_sha256(&self.sha256, "external input materialized digest")?; - ensure!(self.size_bytes > 0, "materialized external input is empty"); - let declared = declaration - .external_inputs - .iter() - .find(|input| input.id == self.input_id) - .with_context(|| format!("plan declares no external input {}", self.input_id))?; - ensure!( - self.url == declared.url - && self.sha256 == prefixed_sha256(&declared.sha256) - && self.runner == declared.runner - && self.destination == declared.destination, - "external input receipt differs from its pinned declaration" - ); - Ok(()) - } -} - -/// Private Idunn release state. The content address covers the exact plan ID, -/// sorted full artifact receipts, and sorted full external-input -/// materialization receipts. The plan remains a separate private record and is -/// supplied explicitly for validation. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct SealedRelease { - pub schema: String, - pub sealed_release_id: String, - pub plan_id: String, - pub artifacts: Vec, - pub external_inputs: Vec, - pub sealed_at_unix_millis: u64, -} - -impl SealedRelease { - pub fn new( - plan: &CompiledDeploymentPlan, - mut artifacts: Vec, - mut external_inputs: Vec, - sealed_at_unix_millis: u64, - ) -> Result { - plan.validate()?; - artifacts.sort_by(|left, right| left.artifact_id.cmp(&right.artifact_id)); - external_inputs.sort_by(|left, right| left.input_id.cmp(&right.input_id)); - let mut release = Self { - schema: SEALED_RELEASE_SCHEMA.into(), - sealed_release_id: String::new(), - plan_id: plan.plan_id.clone(), - artifacts, - external_inputs, - sealed_at_unix_millis, - }; - release.validate_contents(plan)?; - release.sealed_release_id = release.recomputed_release_id()?; - release.validate_against(plan)?; - Ok(release) - } - - pub fn validate_against(&self, plan: &CompiledDeploymentPlan) -> Result<()> { - require_sha256(&self.sealed_release_id, "sealed release id")?; - self.validate_contents(plan)?; - ensure!( - self.sealed_release_id == self.recomputed_release_id()?, - "sealed release content address is wrong" - ); - Ok(()) - } - - pub fn expected_projection( - &self, - plan: &CompiledDeploymentPlan, - ) -> Result { - self.validate_against(plan)?; - let (declaration, binding) = plan.parsed_inputs()?; - let route = match (&binding.route, plan.candidate_port) { - (Some(bound), Some(port)) => Some(IdunnExpectedRoute { - route_id: bound.route_id.clone(), - transport: endpoint_scheme(declaration.service.transport)?.into(), - stable_endpoint: bound.stable_endpoint.clone(), - candidate_endpoint: format!( - "{}://{}:{port}", - endpoint_scheme(declaration.service.transport)?, - bound.private_host - ), - }), - (None, None) => None, - _ => bail!("plan route and candidate port disagree"), - }; - let artifact_sha256 = self - .artifacts - .iter() - .find(|artifact| artifact.artifact_id == declaration.service.executable_artifact) - .context("sealed release has no executable service artifact")? - .sha256 - .clone(); - let mut capabilities = declaration - .provides - .iter() - .map(|capability| IdunnExpectedCapability { - capability: capability.capability.clone(), - schema: capability.schema.clone(), - compatibility: capability.compatibility.clone(), - minimum_capacity: capability.capacity, - }) - .collect::>(); - capabilities.sort_by(|left, right| { - (&left.capability, &left.schema, &left.compatibility).cmp(&( - &right.capability, - &right.schema, - &right.compatibility, - )) - }); - let mut dependencies = plan - .dependencies - .iter() - .map(DependencySelection::expected_projection) - .collect::>>()?; - dependencies.sort_by(|left, right| { - (&left.capability, &left.schema, &left.compatibility).cmp(&( - &right.capability, - &right.schema, - &right.compatibility, - )) - }); - let expected = ExpectedIncarnation { - schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(), - target: declaration.target.clone(), - plan_id: plan.plan_id.clone(), - incarnation_id: plan.incarnation_id.clone(), - sealed_release_id: self.sealed_release_id.clone(), - source_repository: canonical_repository_identity(&plan.source.origin)?, - source_revision: plan.source.revision.clone(), - recipe_sha256: plan.source.recipe_blob_sha256.clone(), - runtime_id: binding.runtime_identity.runtime_id.clone(), - expected_signer_identity_id: binding - .runtime_identity - .expected_signer_identity_id - .clone(), - health_contract: declaration.service.health.contract.clone(), - artifact_sha256, - state_schema_generation: declaration - .state - .as_ref() - .map(|state| state.schema_generation.clone()), - state_contract_sha256: declaration - .state - .as_ref() - .map(canonical_state_contract_sha256) - .transpose()?, - write_lease_required: declaration.write_lease_required(), - route, - capabilities, - dependencies, - }; - expected.validate()?; - Ok(expected) - } - - fn validate_contents(&self, plan: &CompiledDeploymentPlan) -> Result<()> { - ensure!( - self.schema == SEALED_RELEASE_SCHEMA, - "unsupported sealed-release schema" - ); - plan.validate()?; - let (declaration, _) = plan.parsed_inputs()?; - require_sha256(&self.plan_id, "sealed plan id")?; - ensure!( - self.plan_id == plan.plan_id, - "sealed release refers to a different plan" - ); - ensure!( - self.sealed_at_unix_millis >= plan.created_at_unix_millis, - "release was sealed before it was planned" - ); - ensure!( - self.artifacts - .windows(2) - .all(|pair| pair[0].artifact_id < pair[1].artifact_id), - "artifact receipts are not in canonical order" - ); - ensure!( - self.external_inputs - .windows(2) - .all(|pair| pair[0].input_id < pair[1].input_id), - "external input receipts are not in canonical order" - ); - let declared_ids = declaration - .artifacts - .iter() - .map(|artifact| artifact.id.as_str()) - .collect::>(); - let observed_ids = self - .artifacts - .iter() - .map(|artifact| artifact.artifact_id.as_str()) - .collect::>(); - ensure!( - declared_ids == observed_ids && observed_ids.len() == self.artifacts.len(), - "artifact receipts differ from declared outputs" - ); - for artifact in &self.artifacts { - artifact.validate(&declaration)?; - } - let declared_input_ids = declaration - .external_inputs - .iter() - .map(|input| input.id.as_str()) - .collect::>(); - let observed_input_ids = self - .external_inputs - .iter() - .map(|input| input.input_id.as_str()) - .collect::>(); - ensure!( - declared_input_ids == observed_input_ids - && observed_input_ids.len() == self.external_inputs.len(), - "external input receipts differ from pinned declarations" - ); - for input in &self.external_inputs { - input.validate(&declaration)?; - } - Ok(()) - } - - fn recomputed_release_id(&self) -> Result { - Ok(sha256_id( - &rmp_serde::to_vec(&( - self.schema.as_str(), - self.plan_id.as_str(), - &self.artifacts, - &self.external_inputs, - )) - .context("encoding sealed release identity")?, - )) - } -} - -fn canonical_state_contract_sha256(state: &StateDeclaration) -> Result { - Ok(sha256_id( - &rmp_serde::to_vec(state).context("encoding canonical state contract")?, - )) -} - -fn endpoint_scheme(transport: ServiceTransport) -> Result<&'static str> { - match transport { - ServiceTransport::Http => Ok("http"), - ServiceTransport::Tcp => Ok("tcp"), - ServiceTransport::Rudp | ServiceTransport::Private => { - bail!("service transport has no stable route scheme") - } - } -} - -fn dependency_kind_name(kind: DependencyKind) -> &'static str { - match kind { - DependencyKind::Bootstrap => "bootstrap", - DependencyKind::Required => "required", - DependencyKind::Optional => "optional", - DependencyKind::SharedInfrastructure => "shared-infrastructure", - DependencyKind::Private => "private", - DependencyKind::ExternalOperatorBinding => "external-operator-binding", - } -} - -fn startup_order_name(startup: StartupOrder) -> &'static str { - match startup { - StartupOrder::BeforePromotion => "before-promotion", - StartupOrder::BeforeStart => "before-start", - } -} - -fn canonical_repository_identity(origin: &str) -> Result { - let identity = origin - .strip_prefix("https://") - .and_then(|origin| origin.strip_suffix(".git")) - .context("validated Git origin is not a canonical HTTPS repository")?; - Ok(identity.to_owned()) -} - -fn prefixed_sha256(raw_sha256: &str) -> String { - format!("sha256-{raw_sha256}") -} - -fn require_token(value: &str, label: &str) -> Result<()> { - ensure!( - !value.is_empty() && value.len() <= 128, - "{label} is empty or too long" - ); - ensure!( - value - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() - || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/')), - "{label} contains a forbidden character" - ); - Ok(()) -} - -fn require_contract(capability: &str, schema: &str, compatibility: &str) -> Result<()> { - require_token(capability, "capability")?; - require_token(schema, "capability schema")?; - require_token(compatibility, "capability compatibility") -} - -fn require_value(value: &str, label: &str) -> Result<()> { - ensure!( - !value.trim().is_empty() && value == value.trim(), - "{label} is empty or noncanonical" - ); - ensure!( - value.len() <= 4096 && !value.contains('\0'), - "{label} is oversized or contains NUL" - ); - Ok(()) -} - -fn require_sha1(value: &str, label: &str) -> Result<()> { - require_lower_hex(value, 40, label) -} - -fn require_sha256(value: &str, label: &str) -> Result<()> { - let digest = value - .strip_prefix("sha256-") - .with_context(|| format!("{label} has no sha256- prefix"))?; - require_lower_hex(digest, 64, label) -} - -fn require_lower_hex(value: &str, length: usize, label: &str) -> Result<()> { - ensure!(value.len() == length, "{label} has the wrong length"); - ensure!( - value - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)), - "{label} is not lowercase hexadecimal" - ); - Ok(()) -} - -fn sha256_id(bytes: &[u8]) -> String { - let digest = Sha256::digest(bytes); - let mut encoded = String::with_capacity(71); - encoded.push_str("sha256-"); - for byte in digest { - use std::fmt::Write as _; - write!(&mut encoded, "{byte:02x}").expect("writing to String cannot fail"); - } - encoded -} - -#[cfg(test)] -mod tests { - use super::*; - use cultnet_rs::{ - GameCultProviderHealthIdentity, GameCultRuntimeCapability, IdunnRuntimeActivationLaunch, - IdunnServiceIdentity, ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA, - OdinRuntimeTopologyCorrelationPurpose, OdinRuntimeTopologyCorrelationRecord, - OdinTopologyAuthenticationContext, OdinTopologyIdentity, - authenticate_odin_runtime_topology_correlation, enroll_service_identity_at, - verify_runtime_authority, - }; - - const RECIPE: &str = r#" -schema = "gamecult.idunn.target_declaration.v1" -target = "service" -source_stamp_environment = "SERVICE_BUILD_COMMIT" - -[[steps]] -id = "build" -phase = "build" -runner = "rust" -argv = ["cargo", "build", "--locked"] - -[[external_inputs]] -id = "toolchain-index" -url = "https://example.invalid/toolchain-index" -sha256 = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" -runner = "rust" -destination = "inputs/toolchain-index" - -[[artifacts]] -id = "daemon" -source_kind = "runner-output" -runner = "rust" -source = "target/release/service" -destination = "service" -expected_sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" -executable = true - -[service] -executable_artifact = "daemon" -arguments = [ - { kind = "binding", name = "state_root" }, -] -transport = "http" -route_required = true -required_environment = ["GAMECULT_IDUNN_CANDIDATE_BIND", "GAMECULT_IDUNN_RUNTIME_BUNDLE"] - -[service.health] -contract = "service.health" - -[state] -schema_generation = "v1" - -[[state.slots]] -id = "runtime-cache" -relative_path = "runtime-cache.cc" -kind = "cultcache-file" -schema = "service.runtime-cache.v1" -writer = "none" -recovery = "rebuildable" -startup = "open-at-start" - -[[provides]] -capability = "service.runtime" -schema = "service.runtime.v1" -compatibility = "v1" - -[[dependencies]] -kind = "shared-infrastructure" -capability = "odin.verse-rendezvous" -schema = "odin.verse-topology.v1" -compatibility = "v1" -"#; - - const BINDING: &str = r#" -schema = "gamecult.idunn.operator_binding.v2" -target = "service" - -[repository] -origin = "https://github.com/GameCult/Service.git" -admitted_ref = "refs/heads/main" -minimum_revision = "1111111111111111111111111111111111111111" -selection = "ref-head" -checkout = "/srv/build/Service" -recipe_path = "deployment/idunn/recipe.toml" - -[runners.rust] -driver = "docker" -image = "rust@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -user = "1000:1000" -affordances = ["source-read", "artifact-write"] -allowed_programs = ["cargo"] -network_profile = "build-dependency-egress" -memory_mebibytes = 2048 -cpu_quota_percent = 200 -pids_limit = 512 -tmpfs_mebibytes = 512 - -[workload] -driver = "systemd-transient" -state_group = "service" -unit_prefix = "idunn-service" -release_root = "/srv/service/releases" -state_root = "/var/lib/gamecult/service" -runtime_root = "/run/gamecult/idunn/service" -network = "host-private" -hardening = "strict" -memory_mebibytes = 1024 -cpu_quota_percent = 100 - -[workload.argument_bindings] -state_root = "/var/lib/gamecult/service" - -[workload.secret_files] -GAMECULT_RUNTIME_PRESENCE_IDENTITY = "/etc/gamecult/service/runtime-presence-identity.cc" - -[runtime_identity] -runtime_id = "service-yggdrasil" -expected_signer_identity_id = "service-runtime-signer" -trust_anchor_store = "/etc/gamecult/trust/service.cc" - -[route] -driver = "nginx-stream-tcp" -route_id = "service" -stable_endpoint = "http://127.0.0.1:17999" -private_host = "127.0.0.1" -private_port_start = 18000 -private_port_end = 18009 -config_path = "/etc/nginx/idunn-stream-routes/service.conf" -reload_unit = "nginx.service" - -[brakes] -deployment_store = "/var/lib/gamecult/idunn/service-deployment-brake.cc" -lifecycle_store = "/var/lib/gamecult/idunn/service-lifecycle-brake.cc" - -[rollout] -strategy = "candidate-then-promote" -drain_seconds = 30 -retain_releases = 2 - -[placement] -desired_replicas = 1 -nodes = ["yggdrasil"] -"#; - - fn digest(byte: u8) -> String { - format!("sha256-{}", char::from(byte).to_string().repeat(64)) - } - - fn source(recipe: &str) -> SourceSelectionFacts { - SourceSelectionFacts { - schema: SOURCE_SELECTION_FACTS_SCHEMA.into(), - origin: "https://github.com/GameCult/Service.git".into(), - admitted_ref: "refs/heads/main".into(), - admitted_ref_revision: "2222222222222222222222222222222222222222".into(), - revision: "2222222222222222222222222222222222222222".into(), - source_tree: "3333333333333333333333333333333333333333".into(), - recipe_path: "deployment/idunn/recipe.toml".into(), - recipe_blob_sha256: sha256_id(recipe.as_bytes()), - gitlinks: BTreeMap::new(), - selection: SourceSelection::RefHead, - selected_at_unix_millis: 100, - } - } - - fn odin() -> ExpectedIncarnation { - ExpectedIncarnation { - schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(), - target: "odin".into(), - plan_id: digest(b'a'), - incarnation_id: "odin-incarnation-1".into(), - sealed_release_id: digest(b'e'), - source_repository: "github.com/GameCult/Odin".into(), - source_revision: "2222222222222222222222222222222222222222".into(), - recipe_sha256: digest(b'b'), - runtime_id: "odin-yggdrasil".into(), - expected_signer_identity_id: "odin-runtime-signer".into(), - health_contract: "odin.cultnet-service-health".into(), - artifact_sha256: digest(b'f'), - state_schema_generation: None, - state_contract_sha256: None, - write_lease_required: false, - route: Some(IdunnExpectedRoute { - route_id: "odin-private".into(), - transport: "tcp".into(), - stable_endpoint: "tcp://10.77.0.1:17871".into(), - candidate_endpoint: "tcp://127.0.0.1:17871".into(), - }), - capabilities: vec![IdunnExpectedCapability { - capability: "odin.verse-rendezvous".into(), - schema: "odin.verse-topology.v1".into(), - compatibility: "v1".into(), - minimum_capacity: 1, - }], - dependencies: Vec::new(), - } - } - - fn ready_odin_provider(target: &str, runtime_id: &str, capacity: u32) -> SequenceAdmittedReady { - (|| -> Result { - let root = tempfile::tempdir()?; - let provider = enroll_service_identity_at::( - &root.path().join("provider.cc"), - )?; - let idunn = - enroll_service_identity_at::(&root.path().join("idunn.cc"))?; - let odin_signer = - enroll_service_identity_at::(&root.path().join("odin.cc"))?; - let mut expected = odin(); - expected.target = target.into(); - expected.runtime_id = runtime_id.into(); - expected.expected_signer_identity_id = provider.entry().identity_id.clone(); - let launch = IdunnRuntimeActivationLaunch::issue(&expected, digest(b'8'), 100, &idunn)?; - let activation = launch.activation().clone(); - launch.write_credential(std::io::sink())?; - let authority = verify_runtime_authority( - &expected, - &activation, - &idunn.trust_anchor()?, - &provider.entry().public_key, - )?; - let mut topology = OdinRuntimeTopologyCorrelationRecord { - schema_version: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into(), - target: expected.target.clone(), - expected_projection_sha256: expected.canonical_sha256()?, - expected: true, - current_activation_sha256: Some(activation.canonical_sha256()?), - signed_presence_sha256: Some(digest(b'9')), - observed_presence_state: Some("active".into()), - observed_presence_publisher_sequence: Some(1), - observed_write_lease_sha256: None, - observed_capabilities: vec![GameCultRuntimeCapability { - capability: "odin.verse-rendezvous".into(), - schema: "odin.verse-topology.v1".into(), - compatibility: "v1".into(), - capacity, - }], - runtime_id: expected.runtime_id.clone(), - runtime_instance_id: Some(activation.runtime_instance_id.clone()), - present: true, - ready: true, - dependencies: Vec::new(), - disagreements: Vec::new(), - signer_identity_id: odin_signer.entry().identity_id.clone(), - publisher_sequence: 7, - observed_at_unix_millis: 110, - signature_algorithm: "ed25519".into(), - signature: Vec::new(), - }; - topology.signature = odin_signer - .sign::( - &topology.unsigned_signature_payload()?, - ) - .signature; - let bytes = topology.canonical_bytes()?; - let authenticated = authenticate_odin_runtime_topology_correlation( - &bytes, - &authority, - None, - &odin_signer.entry().public_key, - OdinTopologyAuthenticationContext { - trusted_received_at_unix_millis: 120, - maximum_age_millis: 30, - maximum_future_skew_millis: 5, - }, - )?; - SequenceAdmittedReady::for_test(&expected, authenticated, 120) - })() - .unwrap() - } - - fn plan() -> CompiledDeploymentPlan { - let providers = [ready_odin_provider("odin", "odin-yggdrasil", 1)]; - plan_with(&providers) - } - - fn plan_with(providers: &[SequenceAdmittedReady]) -> CompiledDeploymentPlan { - compile_deployment_plan( - RECIPE.as_bytes(), - BINDING.as_bytes(), - source(RECIPE), - "service-incarnation-1", - Some(18001), - 110, - providers, - ) - .unwrap() - } - - fn artifact_receipt() -> ArtifactReceipt { - ArtifactReceipt { - artifact_id: "daemon".into(), - destination: "service".into(), - sha256: digest(b'c'), - size_bytes: 42, - executable: true, - } - } - - fn external_input_receipt() -> ExternalInputMaterializationReceipt { - ExternalInputMaterializationReceipt { - input_id: "toolchain-index".into(), - url: "https://example.invalid/toolchain-index".into(), - sha256: digest(b'd'), - runner: "rust".into(), - destination: "inputs/toolchain-index".into(), - size_bytes: 17, - } - } - - #[test] - fn compiler_parses_the_exact_bytes_it_receipts() { - let providers = [ready_odin_provider("odin", "odin-yggdrasil", 1)]; - let first = plan_with(&providers); - let second = plan_with(&providers); - assert_eq!(first, second); - assert_eq!(first.recipe_blob.as_slice(), RECIPE.as_bytes()); - assert_eq!(first.binding_blob.as_slice(), BINDING.as_bytes()); - assert_eq!( - sha256_id(&first.recipe_blob), - first.source.recipe_blob_sha256 - ); - let changed = RECIPE.replace( - "contract = \"service.health\"", - "contract = \"service.health.v2\"", - ); - let providers = [ready_odin_provider("odin", "odin-yggdrasil", 1)]; - assert!( - compile_deployment_plan( - changed.as_bytes(), - BINDING.as_bytes(), - source(RECIPE), - "service-incarnation-2", - Some(18002), - 111, - &providers, - ) - .is_err() - ); - let mut corrupted = first; - corrupted - .binding_blob - .extend_from_slice(b"\nunknown = true\n"); - assert!(corrupted.validate().is_err()); - } - - #[test] - fn pinned_policy_requires_the_exact_operator_pin() { - let pinned_binding = BINDING.replace( - "selection = \"ref-head\"", - "selection = \"pinned-object\"\npinned_revision = \"2222222222222222222222222222222222222222\"", - ); - let binding = OperatorBinding::parse(&pinned_binding).unwrap(); - assert!(source(RECIPE).validate_against(&binding).is_err()); - let mut facts = source(RECIPE); - facts.selection = SourceSelection::PinnedObject; - facts.validate_against(&binding).unwrap(); - } - - #[test] - fn gitlink_fact_must_match_the_selected_superproject_tree() { - let recipe = RECIPE.replace( - "source_stamp_environment = \"SERVICE_BUILD_COMMIT\"", - "source_stamp_environment = \"SERVICE_BUILD_COMMIT\"\nrequired_gitlinks = [\"vendor/lib\"]", - ); - let binding_text = BINDING.replace( - "recipe_path = \"deployment/idunn/recipe.toml\"", - "recipe_path = \"deployment/idunn/recipe.toml\"\ngitlinks = { \"vendor/lib\" = { origin = \"https://github.com/GameCult/Lib.git\" } }", - ); - let binding = OperatorBinding::parse(&binding_text).unwrap(); - binding - .admit(&TargetDeclaration::parse(&recipe).unwrap()) - .unwrap(); - let mut facts = source(&recipe); - facts.gitlinks.insert( - "vendor/lib".into(), - GitlinkTreeFact { - origin: "https://github.com/GameCult/Lib.git".into(), - revision: "4444444444444444444444444444444444444444".into(), - }, - ); - facts.validate_against(&binding).unwrap(); - facts - .gitlinks - .get_mut(&PathBuf::from("vendor/lib")) - .unwrap() - .origin = "https://github.com/GameCult/Wrong.git".into(); - assert!(facts.validate_against(&binding).is_err()); - } - - #[test] - fn dependency_selection_uses_observed_ready_capacity_and_stable_identity_order() { - let declaration = TargetDeclaration::parse(RECIPE).unwrap(); - let admitted = [ - ready_odin_provider("odin-z", "odin-runtime-z", 4), - ready_odin_provider("odin-yggdrasil", "odin-runtime-yggdrasil", 2), - ]; - let providers = admitted - .iter() - .flat_map(|provider| managed_ready_provider_refs(provider).unwrap()) - .collect::>(); - let selected = select_dependencies(&declaration, &providers).unwrap(); - assert_eq!( - selected[0].provider.as_ref().unwrap().provider_id, - "odin-yggdrasil" - ); - assert_eq!(selected[0].provider.as_ref().unwrap().capacity, 2); - assert_eq!( - selected[0].provider.as_ref().unwrap().endpoint.as_deref(), - Some("tcp://10.77.0.1:17871") - ); - assert!(matches!( - &selected[0].provider.as_ref().unwrap().authority, - DependencyProviderAuthority::ManagedReady { - odin_topology_publisher_sequence: 7, - .. - } - )); - } - - #[test] - fn external_binding_produces_expected_configuration_only() { - let input = BINDING.replace( - "[placement]", - "[[external_capabilities]]\nprovider_id = \"operator-archive\"\ncapability = \"archive.store\"\nschema = \"archive.store.v1\"\ncompatibility = \"v1\"\ncapacity = 2\nendpoint = \"s3://operator-bound\"\n\n[placement]", - ); - let binding = OperatorBinding::parse(&input).unwrap(); - let providers = external_binding_provider_refs(&binding).unwrap(); - let declaration = TargetDeclaration::parse(&RECIPE.replace( - "kind = \"shared-infrastructure\"\ncapability = \"odin.verse-rendezvous\"\nschema = \"odin.verse-topology.v1\"", - "kind = \"external-operator-binding\"\ncapability = \"archive.store\"\nschema = \"archive.store.v1\"", - )) - .unwrap(); - binding.admit(&declaration).unwrap(); - let selected = select_dependencies(&declaration, &providers).unwrap(); - assert!(matches!( - &providers[0].authority, - DependencyProviderAuthority::ExternalOperatorBinding { .. } - )); - assert_eq!(providers[0].capacity, 2); - assert_eq!( - selected[0].provider.as_ref().unwrap().provider_id, - "operator-archive" - ); - } - - #[test] - fn expected_projection_is_sanitized_and_names_the_selected_graph() { - let plan = plan(); - let release = SealedRelease::new( - &plan, - vec![artifact_receipt()], - vec![external_input_receipt()], - 120, - ) - .unwrap(); - let expected = release.expected_projection(&plan).unwrap(); - assert_eq!(expected.plan_id, plan.plan_id); - assert_eq!(expected.sealed_release_id, release.sealed_release_id); - assert_eq!(expected.incarnation_id, "service-incarnation-1"); - assert_eq!(expected.runtime_id, "service-yggdrasil"); - assert_eq!( - expected.expected_signer_identity_id, - "service-runtime-signer" - ); - assert_eq!(expected.health_contract, "service.health"); - assert_eq!(expected.artifact_sha256, digest(b'c')); - assert_eq!(expected.source_repository, "github.com/GameCult/Service"); - assert_eq!(expected.source_revision, plan.source.revision); - assert_eq!(expected.recipe_sha256, plan.source.recipe_blob_sha256); - assert_eq!(expected.state_schema_generation.as_deref(), Some("v1")); - assert!(expected.state_contract_sha256.is_some()); - assert!(!expected.write_lease_required); - assert_eq!( - expected.dependencies[0].provider_id.as_deref(), - Some("odin") - ); - assert_eq!( - expected.dependencies[0].provider_authority.as_deref(), - Some("managed-incarnation") - ); - assert_eq!( - expected.route.as_ref().unwrap().candidate_endpoint, - "http://127.0.0.1:18001" - ); - assert_eq!(expected.route.as_ref().unwrap().transport, "http"); - assert!(expected.canonical_sha256().unwrap().starts_with("sha256-")); - let mut invalid_release = release; - invalid_release.artifacts[0].size_bytes += 1; - assert!(invalid_release.expected_projection(&plan).is_err()); - } - - #[test] - fn expected_projection_sorts_shared_capability_and_dependency_claims() { - let recipe = RECIPE - .replace( - "[[provides]]\ncapability = \"service.runtime\"", - "[[provides]]\ncapability = \"zeta.runtime\"\nschema = \"zeta.runtime.v1\"\ncompatibility = \"v1\"\n\n[[provides]]\ncapability = \"service.runtime\"", - ) - .replace( - "[[dependencies]]\nkind = \"shared-infrastructure\"", - "[[dependencies]]\nkind = \"optional\"\ncapability = \"zeta.optional\"\nschema = \"zeta.optional.v1\"\ncompatibility = \"v1\"\n\n[[dependencies]]\nkind = \"shared-infrastructure\"", - ); - let plan = compile_deployment_plan( - recipe.as_bytes(), - BINDING.as_bytes(), - source(&recipe), - "service-incarnation-sorted", - Some(18002), - 111, - &[ready_odin_provider("odin", "odin-yggdrasil", 1)], - ) - .unwrap(); - let release = SealedRelease::new( - &plan, - vec![artifact_receipt()], - vec![external_input_receipt()], - 120, - ) - .unwrap(); - let expected = release.expected_projection(&plan).unwrap(); - assert_eq!( - expected - .capabilities - .iter() - .map(|capability| capability.capability.as_str()) - .collect::>(), - ["service.runtime", "zeta.runtime"] - ); - assert_eq!( - expected - .dependencies - .iter() - .map(|dependency| dependency.capability.as_str()) - .collect::>(), - ["odin.verse-rendezvous", "zeta.optional"] - ); - expected.validate().unwrap(); - } - - #[test] - fn sealed_release_address_covers_artifacts_and_external_inputs() { - let receipt = artifact_receipt(); - let input = external_input_receipt(); - let plan = plan(); - let mut wrong_artifact = receipt.clone(); - wrong_artifact.sha256 = digest(b'f'); - assert!(SealedRelease::new(&plan, vec![wrong_artifact], vec![input.clone()], 120).is_err()); - assert!(SealedRelease::new(&plan, vec![receipt.clone()], vec![], 120).is_err()); - let release = - SealedRelease::new(&plan, vec![receipt.clone()], vec![input.clone()], 120).unwrap(); - let later_receipt_time = - SealedRelease::new(&plan, vec![receipt], vec![input], 130).unwrap(); - release.validate_against(&plan).unwrap(); - assert_eq!( - release.sealed_release_id, - later_receipt_time.sealed_release_id - ); - let mut changed = release.clone(); - changed.artifacts[0].size_bytes = 43; - assert!(changed.validate_against(&plan).is_err()); - let mut changed = release; - changed.external_inputs[0].size_bytes = 18; - assert!(changed.validate_against(&plan).is_err()); - } -} diff --git a/crates/idunn-daemon/src/drivers.rs b/crates/idunn-daemon/src/drivers.rs deleted file mode 100644 index 1554408..0000000 --- a/crates/idunn-daemon/src/drivers.rs +++ /dev/null @@ -1,7337 +0,0 @@ -use std::collections::BTreeMap; -use std::ffi::{OsStr, OsString}; -use std::fs::{self, OpenOptions}; -use std::io::{ErrorKind, Read, Write}; -use std::net::{SocketAddr, TcpStream}; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output, Stdio}; -use std::thread; -use std::time::Duration; - -use anyhow::{Context, Result, bail, ensure}; -use cultcache_rs::{ - CacheBackingStore, CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, - SingleFileMessagePackBackingStore, TryCompareExchangeSnapshotOutcome, -}; -use cultmesh_rs::{CultMeshRudpSnapshotOptions, request_raw_snapshot_from_rudp_catalog}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use uuid::Uuid; - -use crate::control_plane::SequenceAdmittedWarming; -use crate::deployment::{ - ArtifactOutput, ArtifactSource, IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT, - IDUNN_RUNTIME_BUNDLE_ENVIRONMENT, IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, LaunchArgument, - OperatorBinding, RUNTIME_PRESENCE_IDENTITY_BINDING, RUNTIME_PRESENCE_IDENTITY_FD_NAME, - RouteBinding, RouteDriver, RunnerBinding, SourceSelectionPolicy, TargetDeclaration, - WorkloadNetwork, -}; -use crate::deployment_plan::{ - ArtifactReceipt, CompiledDeploymentPlan, ExternalInputMaterializationReceipt, GitlinkTreeFact, - SOURCE_SELECTION_FACTS_SCHEMA, SealedRelease, SourceSelection, SourceSelectionFacts, -}; -use cultnet_rs::{ - CultNetMessage, CultNetRawPayloadEncoding, CultNetWireContract, - GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE, - GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, GameCultProviderHealthIdentity, - GameCultServiceTrustAnchorRecord, IDUNN_EXPECTED_INCARNATION_SCHEMA, - IDUNN_PROCESS_WRITE_LEASE_SCHEMA, IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, - IDUNN_RUNTIME_ACTIVATION_SCHEMA, IdunnExpectedIncarnationRecord, IdunnProcessWriteLeaseRecord, - IdunnRuntimeActivationLaunch, IdunnRuntimeActivationRecord, IdunnRuntimeActivationSigner, - ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA, OdinRuntimeTopologyCorrelationRecord, - ServiceIdentityProfile, ServiceIdentityTrustAnchor, decode_cultnet_message_from_slice, - derive_service_identity_id, encode_cultnet_message_to_vec, encode_frame, - open_service_identity_credential_reader, -}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct ProcessIdentity { - pub uid: u32, - pub gid: u32, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct GitTreeEntry { - mode: String, - kind: String, - object: String, - path: PathBuf, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ResolvedSource { - pub facts: SourceSelectionFacts, - pub recipe_bytes: Vec, -} - -impl ResolvedSource { - pub fn validate_against(&self, binding: &OperatorBinding) -> Result<()> { - self.facts.validate_against(binding)?; - ensure!(!self.recipe_bytes.is_empty(), "resolved recipe is empty"); - ensure!( - sha256_id(&self.recipe_bytes) == self.facts.recipe_blob_sha256, - "resolved recipe bytes differ from the selected Git object" - ); - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct FrozenSource { - receipt: FrozenSourceReceipt, - facts: SourceSelectionFacts, - recipe_bytes: Vec, - root: PathBuf, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct FrozenSourceReceipt { - pub transaction_id: String, - pub plan_id: String, - pub snapshot_sha256: String, -} - -impl FrozenSourceReceipt { - pub fn validate_against(&self, plan: &CompiledDeploymentPlan) -> Result<()> { - plan.validate()?; - require_driver_id(&self.transaction_id, "source transaction")?; - ensure!(self.plan_id == plan.plan_id, "frozen source plan differs"); - require_sha256_id(&self.snapshot_sha256, "frozen source snapshot") - } - - fn snapshot_component(&self) -> &str { - self.snapshot_sha256 - .strip_prefix("sha256-") - .expect("validated frozen source digest") - } -} - -pub trait SourcePort { - fn resolve( - &self, - binding: &OperatorBinding, - resolution_id: &str, - selected_at_unix_millis: u64, - ) -> Result; - - fn freeze( - &self, - transaction_id: &str, - plan: &CompiledDeploymentPlan, - ) -> Result; - - fn observe_frozen( - &self, - plan: &CompiledDeploymentPlan, - receipt: &FrozenSourceReceipt, - ) -> Result; - - fn cleanup(&self, transaction_id: &str, receipt: Option<&FrozenSourceReceipt>) -> Result<()>; -} - -pub trait RunnerPort { - fn materialize( - &self, - source: &FrozenSource, - plan: &CompiledDeploymentPlan, - staging_root: &Path, - sealed_at_unix_millis: u64, - ) -> Result; -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MaterializedRelease { - pub release: SealedRelease, - pub root: PathBuf, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct InstalledReleaseObservation { - pub sealed_release_id: String, - pub root: PathBuf, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ServiceCredentialObservation { - pub environment_name: String, - pub delivered_path: PathBuf, - pub device: u64, - pub inode: u64, - pub uid: u32, - pub gid: u32, - pub mode: u32, - pub size: u64, - pub sha256: String, -} - -/// Root-owned source metadata for one descriptor that PID1 opens and passes -/// only to the service's initial process. The process must consume and close -/// descriptors 3 and 4 before spawning any child; no filesystem path is -/// projected into the workload environment. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ParentOnlyFileDescriptorObservation { - pub fd_number: u32, - pub fd_name: String, - pub source_path: PathBuf, - pub access: String, - pub device: u64, - pub inode: u64, - pub uid: u32, - pub gid: u32, - pub mode: u32, - pub links: u64, - pub size: u64, - pub sha256: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct WorkloadObservation { - pub unit: String, - pub unit_description: String, - pub invocation_id: String, - pub exec_main_start_timestamp_monotonic: u64, - pub service_type: String, - pub restart_policy: String, - pub kill_mode: String, - pub dynamic_user: bool, - pub systemd_user: String, - pub systemd_group: String, - pub supplementary_groups: String, - pub capability_bounding_set: String, - pub ambient_capabilities: String, - pub private_mounts: bool, - pub private_pids: bool, - pub protect_proc: String, - pub proc_subset: String, - pub no_new_privileges: bool, - pub umask: String, - pub inaccessible_paths: String, - pub load_credential: String, - pub main_pid: u32, - pub process_start_time: u64, - pub process_uids: [u32; 4], - pub process_gids: [u32; 4], - pub process_groups: Vec, - pub process_cap_inheritable: u64, - pub process_cap_permitted: u64, - pub process_cap_effective: u64, - pub process_cap_bounding: u64, - pub process_cap_ambient: u64, - pub process_no_new_privileges: bool, - pub process_namespace_pids: Vec, - pub mount_namespace_id: u64, - pub pid_namespace_id: u64, - pub executable: PathBuf, - pub executable_device: u64, - pub executable_inode: u64, - pub executable_sha256: String, - pub runtime_instance_id: String, - pub working_directory: PathBuf, - pub runtime_bundle: PathBuf, - pub command_line_sha256: String, - pub environment_names: Vec, - pub environment_contract_sha256: String, - pub control_group: String, - pub credentials_directory: Option, - pub parent_only_file_descriptors: Vec, - pub activation_signer_identity_id: String, - pub activation_signer_public_key: Vec, - pub service_credentials: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct LinuxProcessSecurityObservation { - uids: [u32; 4], - gids: [u32; 4], - groups: Vec, - cap_inheritable: u64, - cap_permitted: u64, - cap_effective: u64, - cap_bounding: u64, - cap_ambient: u64, - no_new_privileges: bool, - namespace_pids: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct SystemdUnitObservation { - properties: BTreeMap, - open_files: Vec, -} - -pub trait WorkloadPort { - fn install( - &self, - plan: &CompiledDeploymentPlan, - release: &MaterializedRelease, - ) -> Result; - - fn prepare_activation( - &self, - plan: &CompiledDeploymentPlan, - expected: &IdunnExpectedIncarnationRecord, - launch: IdunnRuntimeActivationLaunch, - ) -> Result; - - fn start_prepared( - &self, - plan: &CompiledDeploymentPlan, - release: &SealedRelease, - installed: &InstalledReleaseObservation, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result; - - fn discard_prepared( - &self, - plan: &CompiledDeploymentPlan, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result<()>; - - fn observe( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - prior: &WorkloadObservation, - ) -> Result; - - fn stop(&self, observation: &WorkloadObservation) -> Result<()>; -} - -pub trait TopologyPort { - fn publish_expected( - &self, - expected: &IdunnExpectedIncarnationRecord, - provider_anchor: &ServiceIdentityTrustAnchor, - ) -> Result; - fn withdraw_expected( - &self, - expected: &IdunnExpectedIncarnationRecord, - provider_anchor: &ServiceIdentityTrustAnchor, - activation: Option<&IdunnRuntimeActivationRecord>, - lease: Option<&IdunnProcessWriteLeaseRecord>, - ) -> Result<()>; - fn publish_observed_activation( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - observation: &WorkloadObservation, - ) -> Result; - fn publish_process_write_lease( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - lease: &IdunnProcessWriteLeaseRecord, - ) -> Result; - fn withdraw_process_write_lease( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - lease: Option<&IdunnProcessWriteLeaseRecord>, - ) -> Result<()>; - fn receive(&self, target: &str) -> Result>; -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ReceivedOdinTopologyCorrelation { - pub target: String, - pub canonical_bytes: Vec, -} - -pub trait WriteLeasePort { - fn revoke_exact(&self, incumbent: Option<&IdunnProcessWriteLeaseRecord>) -> Result<()>; - fn observe_empty(&self) -> Result; - fn observe_exact(&self, lease: &IdunnProcessWriteLeaseRecord) -> Result; - fn grant( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - warming: &SequenceAdmittedWarming, - lease: &IdunnProcessWriteLeaseRecord, - ) -> Result; - fn observe( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - warming: &SequenceAdmittedWarming, - lease: &IdunnProcessWriteLeaseRecord, - ) -> Result; -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct RouteObservation { - pub route_id: String, - pub runtime_instance_id: String, - pub membership_sha256: String, - pub signed_presence_sha256: String, - pub observed_at_unix_millis: u64, -} - -impl RouteObservation { - pub fn validate(&self) -> Result<()> { - require_driver_id(&self.route_id, "route observation")?; - require_sha256_id(&self.runtime_instance_id, "route runtime instance")?; - require_sha256_id(&self.membership_sha256, "route membership")?; - require_sha256_id(&self.signed_presence_sha256, "route signed presence")?; - ensure!( - self.observed_at_unix_millis > 0, - "route observation has no trusted receipt time" - ); - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct RoutePreflightReceipt { - pub route_id: String, - pub candidate_runtime_instance_id: String, - pub candidate_membership_sha256: String, - pub incumbent_runtime_instance_id: Option, - pub incumbent_membership_sha256: Option, - pub incumbent_configuration: Option>, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct RouteSnapshotResponse { - pub message_id: String, - pub canonical_presence: Vec, -} - -const ROUTE_SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(3); -const ROUTE_SNAPSHOT_MAX_BYTES: usize = 1024 * 1024; -const ROUTE_HTTP_MAX_HEADER_BYTES: usize = 32 * 1024; -const ROUTE_HTTP_SNAPSHOT_PATH: &str = "/cultnet/snapshot"; - -impl RoutePreflightReceipt { - pub fn validate(&self) -> Result<()> { - require_driver_id(&self.route_id, "route preflight")?; - require_sha256_id( - &self.candidate_runtime_instance_id, - "candidate route runtime instance", - )?; - require_sha256_id( - &self.candidate_membership_sha256, - "candidate route membership", - )?; - match ( - &self.incumbent_runtime_instance_id, - &self.incumbent_membership_sha256, - &self.incumbent_configuration, - ) { - (None, None, None) => {} - (Some(runtime), Some(membership), Some(configuration)) => { - require_sha256_id(runtime, "incumbent route runtime instance")?; - require_sha256_id(membership, "incumbent route membership")?; - ensure!( - !configuration.is_empty(), - "incumbent route configuration is empty" - ); - ensure!( - sha256_id(configuration) == *membership, - "incumbent route configuration differs from its membership digest" - ); - } - _ => bail!("incumbent route preflight evidence is partial"), - } - Ok(()) - } -} - -/// Fixed-argv Git source driver. It never interprets recipe text as a command -/// and never derives source policy from the target repository. The configured -/// identity performs every Git/network read; root Idunn extracts only exact Git -/// object archives into a separate transaction-owned immutable store. -pub struct GitSourceDriver { - pub source_cache_root: PathBuf, - pub frozen_source_root: PathBuf, - pub identity: Option, - pub git_program: PathBuf, - pub tar_program: PathBuf, -} - -impl GitSourceDriver { - pub fn new( - source_cache_root: impl Into, - frozen_source_root: impl Into, - identity: Option, - ) -> Self { - Self { - source_cache_root: source_cache_root.into(), - frozen_source_root: frozen_source_root.into(), - identity, - git_program: PathBuf::from("/usr/bin/git"), - tar_program: PathBuf::from("/usr/bin/tar"), - } - } - - fn git_command(&self, args: I) -> Result - where - I: IntoIterator, - S: AsRef, - { - ensure!( - self.git_program.is_absolute(), - "Git source driver program is not absolute" - ); - let mut command = Command::new(&self.git_program); - command - .args(args) - .stdin(Stdio::null()) - .env_clear() - .env("HOME", self.source_cache_root.join(".home")) - .env("PATH", "/usr/bin:/bin") - .env("GIT_CONFIG_NOSYSTEM", "1") - .env("GIT_TERMINAL_PROMPT", "0") - .env("LANG", "C.UTF-8"); - apply_identity(&mut command, self.identity)?; - Ok(command) - } - - fn git(&self, args: I) -> Result - where - I: IntoIterator, - S: AsRef, - { - let output = self.git_command(args)?.output().with_context(|| { - format!( - "starting fixed-argv Git driver {}", - self.git_program.display() - ) - })?; - if !output.status.success() { - bail!( - "Git source driver exited with {}: {}", - output.status, - String::from_utf8_lossy(&output.stderr).trim() - ); - } - Ok(output) - } - - fn git_text(&self, args: I) -> Result - where - I: IntoIterator, - S: AsRef, - { - let output = self.git(args)?; - let value = String::from_utf8(output.stdout).context("Git emitted non-UTF-8 text")?; - Ok(value.trim().to_owned()) - } - - fn ensure_checkout(&self, binding: &OperatorBinding) -> Result<()> { - let checkout = &binding.repository.checkout; - if !checkout.exists() { - self.git([ - OsString::from("clone"), - OsString::from("--filter=blob:none"), - OsString::from("--no-checkout"), - OsString::from("--origin"), - OsString::from("origin"), - binding.repository.origin.clone().into(), - checkout.as_os_str().to_owned(), - ])?; - } - let checkout_metadata = fs::symlink_metadata(checkout) - .with_context(|| format!("inspecting source checkout {}", checkout.display()))?; - ensure!( - checkout_metadata.is_dir() && !checkout_metadata.file_type().is_symlink(), - "source checkout is not a native directory" - ); - let canonical_checkout = checkout.canonicalize()?; - ensure!( - canonical_checkout == *checkout, - "source checkout traverses a symlink or noncanonical path" - ); - let git_metadata = fs::symlink_metadata(checkout.join(".git"))?; - ensure!( - git_metadata.is_dir() && !git_metadata.file_type().is_symlink(), - "source checkout has no native Git object directory" - ); - let actual_origin = self.git_text([ - OsString::from("-C"), - checkout.as_os_str().to_owned(), - OsString::from("remote"), - OsString::from("get-url"), - OsString::from("origin"), - ])?; - ensure!( - actual_origin == binding.repository.origin, - "source checkout origin differs from the operator binding" - ); - Ok(()) - } - - fn admitted_ref_name(binding: &OperatorBinding, resolution_id: &str) -> Result { - require_driver_id(resolution_id, "source resolution")?; - Ok(format!( - "refs/idunn/resolutions/{}/{}", - binding.target, resolution_id - )) - } - - fn resolve_selected_revision( - &self, - binding: &OperatorBinding, - admitted_ref_revision: &str, - ) -> Result<(String, SourceSelection)> { - let checkout = &binding.repository.checkout; - let (revision, selection) = match binding.repository.selection { - SourceSelectionPolicy::PinnedObject => ( - binding - .repository - .pinned_revision - .clone() - .context("pinned source binding lost its exact revision")?, - SourceSelection::PinnedObject, - ), - SourceSelectionPolicy::RefHead => { - (admitted_ref_revision.to_owned(), SourceSelection::RefHead) - } - SourceSelectionPolicy::SignedRelease => { - bail!("signed-release selection requires a release-authority source port") - } - }; - require_git_sha(&revision, "selected source revision")?; - self.git([ - OsString::from("-C"), - checkout.as_os_str().to_owned(), - OsString::from("merge-base"), - OsString::from("--is-ancestor"), - binding.repository.minimum_revision.clone().into(), - revision.clone().into(), - ]) - .context("selected source is below the operator minimum revision")?; - self.git([ - OsString::from("-C"), - checkout.as_os_str().to_owned(), - OsString::from("merge-base"), - OsString::from("--is-ancestor"), - revision.clone().into(), - admitted_ref_revision.into(), - ]) - .context("selected source is outside the fetched admitted ref")?; - Ok((revision, selection)) - } - - fn git_tree_entries(&self, repository: &Path, revision: &str) -> Result> { - let output = self - .git([ - OsString::from("-C"), - repository.as_os_str().to_owned(), - OsString::from("ls-tree"), - OsString::from("-r"), - OsString::from("-z"), - revision.into(), - ])? - .stdout; - let mut entries = Vec::new(); - for record in output - .split(|byte| *byte == 0) - .filter(|record| !record.is_empty()) - { - let tab = record - .iter() - .position(|byte| *byte == b'\t') - .context("Git tree record has no path delimiter")?; - let header = std::str::from_utf8(&record[..tab]) - .context("Git tree record header is not UTF-8")?; - let path = - std::str::from_utf8(&record[tab + 1..]).context("Git tree path is not UTF-8")?; - let mut fields = header.split(' '); - let mode = fields.next().context("Git tree record has no mode")?; - let kind = fields.next().context("Git tree record has no kind")?; - let object = fields.next().context("Git tree record has no object")?; - ensure!(fields.next().is_none(), "Git tree record has extra fields"); - require_git_sha(object, "Git tree object")?; - let path = PathBuf::from(path); - let normalized = normalized_relative(&path)?; - ensure!( - normalized == path.to_string_lossy(), - "Git tree path is not normalized" - ); - ensure!( - path.components().all(|component| !matches!( - component, - std::path::Component::Normal(value) if value == ".git" - )), - "Git tree contains forbidden .git metadata" - ); - entries.push(GitTreeEntry { - mode: mode.to_owned(), - kind: kind.to_owned(), - object: object.to_owned(), - path, - }); - } - entries.sort_by(|left, right| left.path.cmp(&right.path)); - ensure!( - entries.windows(2).all(|pair| pair[0].path != pair[1].path), - "Git tree emits a path twice" - ); - Ok(entries) - } - - fn exact_recipe_and_gitlinks( - &self, - binding: &OperatorBinding, - revision: &str, - ) -> Result<(Vec, BTreeMap)> { - let entries = self.git_tree_entries(&binding.repository.checkout, revision)?; - let recipe = entries - .iter() - .find(|entry| entry.path == binding.repository.recipe_path) - .context("selected tree has no deployment recipe")?; - ensure!( - matches!(recipe.mode.as_str(), "100644" | "100755") && recipe.kind == "blob", - "deployment recipe is not a regular Git blob" - ); - let recipe_bytes = self - .git([ - OsString::from("-C"), - binding.repository.checkout.as_os_str().to_owned(), - OsString::from("cat-file"), - OsString::from("blob"), - recipe.object.clone().into(), - ])? - .stdout; - ensure!( - !recipe_bytes.is_empty(), - "selected deployment recipe is empty" - ); - - let observed_gitlinks = entries - .iter() - .filter(|entry| entry.mode == "160000") - .map(|entry| { - ensure!(entry.kind == "commit", "Gitlink has the wrong object kind"); - Ok((entry.path.clone(), entry.object.clone())) - }) - .collect::>>()?; - let expected_paths = binding - .repository - .gitlinks - .keys() - .cloned() - .collect::>(); - let observed_paths = observed_gitlinks - .keys() - .cloned() - .collect::>(); - ensure!( - observed_paths == expected_paths, - "selected tree Gitlinks do not exactly match operator bindings" - ); - let gitlinks = observed_gitlinks - .into_iter() - .map(|(path, revision)| { - let origin = binding.repository.gitlinks[&path].origin.clone(); - (path, GitlinkTreeFact { origin, revision }) - }) - .collect(); - Ok((recipe_bytes, gitlinks)) - } - - fn prepare_source_root(&self, binding: &OperatorBinding) -> Result<()> { - #[cfg(unix)] - ensure!( - unsafe { libc::geteuid() } != 0 || self.identity.is_some(), - "root Idunn must configure an unprivileged source identity" - ); - ensure!( - binding - .repository - .checkout - .starts_with(&self.source_cache_root) - && binding.repository.checkout != self.source_cache_root, - "repository checkout is outside Idunn's source authority root" - ); - ensure_source_directory(&self.source_cache_root, self.identity)?; - ensure!( - self.source_cache_root.canonicalize()? == self.source_cache_root, - "source cache root traverses a symlink or noncanonical path" - ); - ensure_source_directory(&self.source_cache_root.join(".home"), self.identity)?; - ensure_source_directory_tree( - &self.source_cache_root, - binding - .repository - .checkout - .parent() - .context("repository checkout has no parent directory")?, - self.identity, - )?; - self.ensure_checkout(binding) - } - - fn verify_exact_source( - &self, - binding: &OperatorBinding, - resolved: &ResolvedSource, - ) -> Result<()> { - let actual_tree = self.git_text([ - OsString::from("-C"), - binding.repository.checkout.as_os_str().to_owned(), - OsString::from("rev-parse"), - OsString::from(format!("{}^{{tree}}", resolved.facts.revision)), - ])?; - ensure!( - actual_tree == resolved.facts.source_tree, - "selected revision no longer resolves to the frozen source tree" - ); - let (recipe_bytes, gitlinks) = - self.exact_recipe_and_gitlinks(binding, &resolved.facts.revision)?; - ensure!( - recipe_bytes == resolved.recipe_bytes, - "selected recipe object differs from the durable source resolution" - ); - ensure!( - gitlinks == resolved.facts.gitlinks, - "Gitlinks differ from the durable source resolution" - ); - Ok(()) - } - - fn git_archive_into( - &self, - repository: &Path, - revision: &str, - prefix: Option<&Path>, - destination: &Path, - ) -> Result<()> { - ensure!( - self.tar_program.is_absolute(), - "source archive extractor is not absolute" - ); - let mut archive_args = vec![ - OsString::from("-C"), - repository.as_os_str().to_owned(), - OsString::from("archive"), - OsString::from("--format=tar"), - ]; - if let Some(prefix) = prefix { - archive_args.push(OsString::from(format!( - "--prefix={}/", - normalized_relative(prefix)? - ))); - } - archive_args.push(revision.into()); - let mut archive = self.git_command(archive_args)?; - archive.stdout(Stdio::piped()).stderr(Stdio::piped()); - let mut archive = archive.spawn().context("starting exact Git archive")?; - let archive_stdout = archive.stdout.take().context("Git archive has no stdout")?; - let mut extractor = Command::new(&self.tar_program); - extractor - .args([ - OsString::from("--extract"), - OsString::from("--file=-"), - OsString::from("--directory"), - destination.as_os_str().to_owned(), - OsString::from("--no-same-owner"), - ]) - .stdin(Stdio::from(archive_stdout)) - .stdout(Stdio::null()) - .stderr(Stdio::piped()) - .env_clear() - .env("LANG", "C.UTF-8"); - let extractor = extractor - .spawn() - .context("starting fixed-argv source archive extractor")?; - let archive_output = archive - .wait_with_output() - .context("waiting for exact Git archive")?; - let extractor_output = extractor - .wait_with_output() - .context("waiting for source archive extractor")?; - ensure!( - archive_output.status.success(), - "Git archive failed: {}", - String::from_utf8_lossy(&archive_output.stderr).trim() - ); - ensure!( - extractor_output.status.success(), - "source archive extraction failed: {}", - String::from_utf8_lossy(&extractor_output.stderr).trim() - ); - Ok(()) - } - - fn materialize_gitlink_archive( - &self, - binding: &OperatorBinding, - path: &Path, - fact: &GitlinkTreeFact, - destination: &Path, - ) -> Result<()> { - let gitlink_root = self - .source_cache_root - .join(".gitlinks") - .join(&binding.target); - ensure_source_directory_tree(&self.source_cache_root, &gitlink_root, self.identity)?; - let checkout = gitlink_root.join(format!("{}-{}", fact.revision, Uuid::new_v4())); - let result = (|| { - self.git([ - OsString::from("clone"), - OsString::from("--filter=blob:none"), - OsString::from("--no-checkout"), - OsString::from("--origin"), - OsString::from("origin"), - fact.origin.clone().into(), - checkout.as_os_str().to_owned(), - ])?; - self.git([ - OsString::from("-C"), - checkout.as_os_str().to_owned(), - OsString::from("fetch"), - OsString::from("--no-tags"), - OsString::from("origin"), - fact.revision.clone().into(), - ])?; - let actual = self.git_text([ - OsString::from("-C"), - checkout.as_os_str().to_owned(), - OsString::from("rev-parse"), - OsString::from(format!("{}^{{commit}}", fact.revision)), - ])?; - ensure!(actual == fact.revision, "Gitlink exact revision is absent"); - ensure!( - !self - .git_tree_entries(&checkout, &fact.revision)? - .iter() - .any(|entry| entry.mode == "160000"), - "nested Gitlinks are not admitted in Idunn v1" - ); - self.git_archive_into(&checkout, &fact.revision, Some(path), destination) - })(); - let cleanup = if checkout.exists() { - remove_tree_inside(&gitlink_root, &checkout) - } else { - Ok(()) - }; - match (result, cleanup) { - (Ok(()), Ok(())) => Ok(()), - (Err(error), _) => Err(error), - (Ok(()), Err(error)) => Err(error.context("cleaning exact Gitlink checkout")), - } - } -} - -impl SourcePort for GitSourceDriver { - fn resolve( - &self, - binding: &OperatorBinding, - resolution_id: &str, - selected_at_unix_millis: u64, - ) -> Result { - binding.validate()?; - ensure!( - selected_at_unix_millis > 0, - "source selection has no timestamp" - ); - self.prepare_source_root(binding)?; - let fetched_ref = Self::admitted_ref_name(binding, resolution_id)?; - self.git([ - OsString::from("-C"), - binding.repository.checkout.as_os_str().to_owned(), - OsString::from("fetch"), - OsString::from("--force"), - OsString::from("--no-tags"), - OsString::from("origin"), - OsString::from(format!( - "+{}:{fetched_ref}", - binding.repository.admitted_ref - )), - ])?; - let admitted_ref_revision = self.git_text([ - OsString::from("-C"), - binding.repository.checkout.as_os_str().to_owned(), - OsString::from("rev-parse"), - OsString::from(format!("{fetched_ref}^{{commit}}")), - ])?; - require_git_sha(&admitted_ref_revision, "fetched admitted-ref revision")?; - let (revision, selection) = - self.resolve_selected_revision(binding, &admitted_ref_revision)?; - let source_tree = self.git_text([ - OsString::from("-C"), - binding.repository.checkout.as_os_str().to_owned(), - OsString::from("rev-parse"), - OsString::from(format!("{revision}^{{tree}}")), - ])?; - require_git_sha(&source_tree, "selected source tree")?; - let (recipe_bytes, gitlinks) = self.exact_recipe_and_gitlinks(binding, &revision)?; - let facts = SourceSelectionFacts { - schema: SOURCE_SELECTION_FACTS_SCHEMA.into(), - origin: binding.repository.origin.clone(), - admitted_ref: binding.repository.admitted_ref.clone(), - admitted_ref_revision, - revision, - source_tree, - recipe_path: binding.repository.recipe_path.clone(), - recipe_blob_sha256: sha256_id(&recipe_bytes), - gitlinks, - selection, - selected_at_unix_millis, - }; - facts.validate_against(binding)?; - let resolved = ResolvedSource { - facts, - recipe_bytes, - }; - resolved.validate_against(binding)?; - Ok(resolved) - } - - fn freeze( - &self, - transaction_id: &str, - plan: &CompiledDeploymentPlan, - ) -> Result { - plan.validate()?; - require_driver_id(transaction_id, "source transaction")?; - let (_, binding) = plan.parsed_inputs()?; - let resolved = ResolvedSource { - facts: plan.source.clone(), - recipe_bytes: plan.recipe_blob.clone(), - }; - resolved.validate_against(&binding)?; - #[cfg(unix)] - ensure!( - unsafe { libc::geteuid() } == 0 && self.identity.is_some(), - "freezing source requires root Idunn with an unprivileged Git identity" - ); - self.prepare_source_root(&binding)?; - self.git([ - OsString::from("-C"), - binding.repository.checkout.as_os_str().to_owned(), - OsString::from("fetch"), - OsString::from("--no-tags"), - OsString::from("origin"), - resolved.facts.revision.clone().into(), - ]) - .context("fetching the durable exact source revision")?; - self.verify_exact_source(&binding, &resolved)?; - let transaction_root = - prepare_frozen_transaction_root(&self.frozen_source_root, transaction_id)?; - let partial = transaction_root.join(".partial"); - prepare_frozen_source_destination(&partial)?; - let materialization = (|| { - self.git_archive_into( - &binding.repository.checkout, - &resolved.facts.revision, - None, - &partial, - )?; - for (path, fact) in &resolved.facts.gitlinks { - self.materialize_gitlink_archive(&binding, path, fact, &partial)?; - } - let recipe_path = partial.join(&resolved.facts.recipe_path); - let recipe_metadata = fs::symlink_metadata(&recipe_path)?; - ensure!( - recipe_metadata.is_file() && !recipe_metadata.file_type().is_symlink(), - "frozen deployment recipe is not a regular file" - ); - let materialized_recipe = - fs::read(&recipe_path).context("reading frozen deployment recipe")?; - ensure!( - materialized_recipe == resolved.recipe_bytes, - "frozen recipe differs from the durable source resolution" - ); - harden_frozen_source(&partial)?; - validate_frozen_source(&partial)?; - frozen_source_sha256(&partial) - })(); - let snapshot_sha256 = match materialization { - Ok(snapshot_sha256) => snapshot_sha256, - Err(error) => { - let _ = remove_frozen_transaction_root(&self.frozen_source_root, transaction_id); - return Err(error); - } - }; - let snapshot_component = snapshot_sha256 - .strip_prefix("sha256-") - .expect("generated frozen source digest"); - let final_root = transaction_root.join(snapshot_component); - fs::rename(&partial, &final_root).context("publishing immutable frozen source")?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&transaction_root, fs::Permissions::from_mode(0o500))?; - } - let receipt = FrozenSourceReceipt { - transaction_id: transaction_id.to_owned(), - plan_id: plan.plan_id.clone(), - snapshot_sha256, - }; - receipt.validate_against(plan)?; - Ok(receipt) - } - - fn observe_frozen( - &self, - plan: &CompiledDeploymentPlan, - receipt: &FrozenSourceReceipt, - ) -> Result { - receipt.validate_against(plan)?; - validate_frozen_source_store(&self.frozen_source_root)?; - let root = self - .frozen_source_root - .join(&receipt.transaction_id) - .join(receipt.snapshot_component()); - let canonical_store = self.frozen_source_root.canonicalize()?; - let canonical_root = root.canonicalize()?; - ensure!( - canonical_store == self.frozen_source_root - && canonical_root == root - && canonical_root.starts_with(&canonical_store), - "frozen source receipt resolves outside its authority root" - ); - validate_frozen_source(&root)?; - ensure!( - frozen_source_sha256(&root)? == receipt.snapshot_sha256, - "frozen source snapshot differs from its receipt" - ); - let recipe_path = root.join(&plan.source.recipe_path); - let recipe_metadata = fs::symlink_metadata(&recipe_path)?; - ensure!( - recipe_metadata.is_file() && !recipe_metadata.file_type().is_symlink(), - "observed deployment recipe is not a regular file" - ); - ensure!( - fs::read(&recipe_path)? == plan.recipe_blob, - "observed deployment recipe differs from the persisted plan" - ); - Ok(FrozenSource { - receipt: receipt.clone(), - facts: plan.source.clone(), - recipe_bytes: plan.recipe_blob.clone(), - root, - }) - } - - fn cleanup(&self, transaction_id: &str, receipt: Option<&FrozenSourceReceipt>) -> Result<()> { - require_driver_id(transaction_id, "source transaction")?; - if let Some(receipt) = receipt { - ensure!( - receipt.transaction_id == transaction_id, - "frozen source cleanup receipt belongs to another transaction" - ); - require_sha256_id(&receipt.snapshot_sha256, "frozen source snapshot")?; - } - let transaction_root = self.frozen_source_root.join(transaction_id); - if !transaction_root.exists() { - return Ok(()); - } - remove_frozen_transaction_root(&self.frozen_source_root, transaction_id) - } -} - -/// Docker is only a runner substrate. Recipe argv stays an argv vector, the -/// operator binding selects the exact image/network/mount affordances, and the -/// driver returns complete materialization receipts rather than build truth by -/// convention. -pub struct DockerRunnerDriver { - pub docker_program: PathBuf, -} - -impl Default for DockerRunnerDriver { - fn default() -> Self { - Self { - docker_program: PathBuf::from("/usr/bin/docker"), - } - } -} - -impl DockerRunnerDriver { - fn docker(&self, args: I) -> Result - where - I: IntoIterator, - S: AsRef, - { - ensure!( - self.docker_program.is_absolute(), - "Docker runner program is not absolute" - ); - let output = Command::new(&self.docker_program) - .args(args) - .stdin(Stdio::null()) - .output() - .with_context(|| format!("starting Docker runner {}", self.docker_program.display()))?; - if !output.status.success() { - bail!( - "Docker runner exited with {}: {}", - output.status, - String::from_utf8_lossy(&output.stderr).trim() - ); - } - Ok(output) - } - - fn run_in_workspace( - &self, - runner: &RunnerBinding, - workspace: &Path, - working_directory: &Path, - argv: &[String], - required_environment: &std::collections::BTreeSet, - source_stamp: (&str, &str), - ) -> Result<()> { - ensure!(!argv.is_empty(), "runner command is empty"); - ensure!( - runner.allowed_programs.contains(&argv[0]), - "runner program {} is not operator-bound", - argv[0] - ); - let mut args = self.base_run_args(runner, workspace)?; - args.extend([ - OsString::from("--workdir"), - OsString::from(format!( - "/workspace/{}", - normalized_relative(working_directory)? - )), - OsString::from("--env"), - OsString::from(format!("{}={}", source_stamp.0, source_stamp.1)), - ]); - for name in required_environment { - if let Some(value) = runner.environment.get(name) { - args.push(OsString::from("--env")); - args.push(OsString::from(format!("{name}={value}"))); - } else if let Some(path) = runner.secret_files.get(name) { - validate_runner_secret(path, container_identity(&runner.user)?)?; - args.push(OsString::from("--env")); - args.push(OsString::from(format!("{name}=/run/idunn/secrets/{name}"))); - args.push(OsString::from("--mount")); - args.push(bind_mount( - path, - &format!("/run/idunn/secrets/{name}"), - true, - )?); - } else { - bail!("runner lacks declared step environment {name}") - } - } - args.push(runner.image.clone().into()); - args.extend(argv.iter().map(OsString::from)); - self.docker(args)?; - Ok(()) - } - - fn base_run_args(&self, runner: &RunnerBinding, workspace: &Path) -> Result> { - let identity = container_identity(&runner.user)?; - let mut args = vec![ - OsString::from("run"), - OsString::from("--rm"), - OsString::from("--network"), - OsString::from(runner.network_profile.as_deref().unwrap_or("none")), - OsString::from("--memory"), - OsString::from(format!("{}m", runner.memory_mebibytes)), - OsString::from("--cpus"), - OsString::from(format!( - "{:.2}", - f64::from(runner.cpu_quota_percent) / 100.0 - )), - OsString::from("--mount"), - bind_mount(workspace, "/workspace", false)?, - OsString::from("--user"), - OsString::from(&runner.user), - OsString::from("--cap-drop"), - OsString::from("ALL"), - OsString::from("--security-opt"), - OsString::from("no-new-privileges"), - OsString::from("--read-only"), - OsString::from("--pids-limit"), - OsString::from(runner.pids_limit.to_string()), - OsString::from("--tmpfs"), - OsString::from(format!( - "/tmp:rw,nosuid,nodev,noexec,size={}m", - runner.tmpfs_mebibytes - )), - ]; - if let Some(cache_root) = &runner.cache_root { - ensure_runner_cache_root(cache_root, identity)?; - args.push(OsString::from("--mount")); - args.push(bind_mount(cache_root, "/cache", false)?); - } - Ok(args) - } - - fn materialize_external_input( - &self, - declaration: &TargetDeclaration, - binding: &OperatorBinding, - workspaces: &BTreeMap, - input_id: &str, - ) -> Result { - let input = declaration - .external_inputs - .iter() - .find(|candidate| candidate.id == input_id) - .context("external input declaration disappeared")?; - let runner = &binding.runners[&input.runner]; - let workspace = &workspaces[&input.runner]; - let destination = workspace.join(&input.destination); - ensure!( - destination.starts_with(workspace), - "external input escaped its runner workspace" - ); - if let Some(parent) = destination.parent() { - fs::create_dir_all(parent)?; - } - let mut args = self.base_run_args(runner, workspace)?; - args.extend([ - runner.image.clone().into(), - OsString::from("curl"), - OsString::from("--fail"), - OsString::from("--location"), - OsString::from("--proto"), - OsString::from("=https"), - OsString::from("--output"), - OsString::from(format!( - "/workspace/{}", - normalized_relative(&input.destination)? - )), - input.url.clone().into(), - ]); - self.docker(args)?; - let bytes = fs::read(&destination).with_context(|| { - format!( - "reading materialized external input {}", - destination.display() - ) - })?; - ensure!(!bytes.is_empty(), "materialized external input is empty"); - let digest = raw_sha256(&bytes); - ensure!( - digest == input.sha256, - "materialized external input digest differs from its recipe pin" - ); - Ok(ExternalInputMaterializationReceipt { - input_id: input.id.clone(), - url: input.url.clone(), - sha256: format!("sha256-{digest}"), - runner: input.runner.clone(), - destination: input.destination.clone(), - size_bytes: bytes.len().try_into()?, - }) - } - - fn collect_artifact( - &self, - declaration: &TargetDeclaration, - source: &FrozenSource, - workspaces: &BTreeMap, - staging_root: &Path, - artifact_id: &str, - ) -> Result { - let artifact = declaration - .artifacts - .iter() - .find(|candidate| candidate.id == artifact_id) - .context("artifact declaration disappeared")?; - let source_path = match artifact.source_kind { - ArtifactSource::RunnerOutput => workspaces - .get( - artifact - .runner - .as_deref() - .context("runner artifact lost its runner")?, - ) - .context("runner workspace is absent")? - .join(&artifact.source), - ArtifactSource::WorktreeTree => source.root.join(&artifact.source), - }; - ensure!(source_path.exists(), "declared artifact output is absent"); - let destination = staging_root.join(&artifact.destination); - ensure!( - destination.starts_with(staging_root), - "artifact destination escaped its release staging root" - ); - copy_artifact(&source_path, &destination)?; - let (sha256, size_bytes) = digest_artifact(&destination)?; - if let Some(expected) = &artifact.expected_sha256 { - ensure!( - &sha256 == expected, - "artifact output differs from its recipe-pinned digest" - ); - } - Ok(ArtifactReceipt { - artifact_id: artifact.id.clone(), - destination: artifact.destination.clone(), - sha256: format!("sha256-{sha256}"), - size_bytes, - executable: artifact.executable, - }) - } -} - -impl RunnerPort for DockerRunnerDriver { - fn materialize( - &self, - source: &FrozenSource, - plan: &CompiledDeploymentPlan, - staging_parent: &Path, - sealed_at_unix_millis: u64, - ) -> Result { - plan.validate()?; - source.receipt.validate_against(plan)?; - ensure!( - source.facts == plan.source && source.recipe_bytes == plan.recipe_blob, - "runner source differs from the compiled plan" - ); - let (declaration, binding) = plan.parsed_inputs()?; - fs::create_dir_all(staging_parent)?; - let staging_root = staging_parent.join(&source.receipt.transaction_id); - if staging_root.exists() { - remove_tree_inside(staging_parent, &staging_root)?; - } - fs::create_dir_all(&staging_root)?; - - let mut workspaces = BTreeMap::new(); - for runner_id in binding.runners.keys() { - let workspace = staging_root.join(format!(".runner-{runner_id}")); - copy_tree(&source.root, &workspace)?; - workspaces.insert(runner_id.clone(), workspace); - } - - for input in &declaration.external_inputs { - let workspace = &workspaces[&input.runner]; - let destination = workspace.join(&input.destination); - ensure!( - destination.starts_with(workspace), - "external input escaped its runner workspace" - ); - if let Some(parent) = destination.parent() { - fs::create_dir_all(parent)?; - } - } - for (runner_id, workspace) in &workspaces { - assign_runner_tree( - workspace, - container_identity(&binding.runners[runner_id].user)?, - )?; - } - - let mut external_inputs = Vec::new(); - for input in &declaration.external_inputs { - external_inputs.push(self.materialize_external_input( - &declaration, - &binding, - &workspaces, - &input.id, - )?); - } - for step in &declaration.steps { - let runner = &binding.runners[&step.runner]; - let workspace = &workspaces[&step.runner]; - for required in &step.required_environment { - ensure!( - runner.environment.contains_key(required) - || runner.secret_files.contains_key(required), - "step {} lacks operator-bound environment {required}", - step.id - ); - } - self.run_in_workspace( - runner, - workspace, - &step.working_directory, - &step.argv, - &step.required_environment, - ( - &declaration.source_stamp_environment, - &source.facts.revision, - ), - )?; - } - - let mut artifacts = Vec::new(); - for artifact in &declaration.artifacts { - artifacts.push(self.collect_artifact( - &declaration, - source, - &workspaces, - &staging_root, - &artifact.id, - )?); - } - for workspace in workspaces.values() { - remove_tree_inside(&staging_root, workspace)?; - } - let release = SealedRelease::new( - plan, - artifacts.clone(), - external_inputs.clone(), - sealed_at_unix_millis, - )?; - Ok(MaterializedRelease { - release, - root: staging_root, - }) - } -} - -/// systemd owns process execution. This driver lowers one validated launch -/// contract into a transient unit and then proves the native process and -/// executable that systemd actually started. It does not decide admission, -/// readiness, write authority, or route membership. -pub struct SystemdTransientWorkloadDriver { - pub systemd_run_program: PathBuf, - pub systemctl_program: PathBuf, - pub proc_root: PathBuf, - pub credential_root: PathBuf, -} - -impl Default for SystemdTransientWorkloadDriver { - fn default() -> Self { - Self { - systemd_run_program: PathBuf::from("/usr/bin/systemd-run"), - systemctl_program: PathBuf::from("/usr/bin/systemctl"), - proc_root: PathBuf::from("/proc"), - credential_root: PathBuf::from("/run/idunn/activation-credentials"), - } - } -} - -impl SystemdTransientWorkloadDriver { - fn command(&self, program: &Path, args: I) -> Result - where - I: IntoIterator, - S: AsRef, - { - ensure!( - program.is_absolute(), - "workload actuator program is not absolute" - ); - let output = Command::new(program) - .args(args) - .stdin(Stdio::null()) - .env_clear() - .env("LANG", "C.UTF-8") - .output() - .with_context(|| format!("starting workload actuator {}", program.display()))?; - if !output.status.success() { - bail!( - "workload actuator {} exited with {}: {}", - program.display(), - output.status, - String::from_utf8_lossy(&output.stderr).trim() - ); - } - Ok(output) - } - - fn unit_name(&self, prefix: &str, runtime_instance_id: &str) -> Result { - let suffix = runtime_instance_id - .strip_prefix("sha256-") - .context("runtime instance id has no sha256 prefix")?; - ensure!( - suffix.len() == 64 && suffix.bytes().all(|byte| byte.is_ascii_hexdigit()), - "runtime instance id is not a SHA-256 digest" - ); - Ok(format!("{prefix}-{suffix}.service")) - } - - fn activation_credential_source( - &self, - activation: &IdunnRuntimeActivationRecord, - ) -> Result { - activation.validate()?; - ensure!( - self.credential_root.is_absolute() - && !self - .credential_root - .as_os_str() - .to_string_lossy() - .chars() - .any(char::is_whitespace), - "activation credential root must be an absolute path without whitespace" - ); - Ok(self - .credential_root - .join(format!("{}.credential", activation.runtime_instance_id))) - } - - fn write_activation_credential( - &self, - launch: IdunnRuntimeActivationLaunch, - ) -> Result<(IdunnRuntimeActivationRecord, PathBuf)> { - #[cfg(unix)] - use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; - - ensure_activation_credential_root(&self.credential_root)?; - let expected_activation = launch.activation().clone(); - let source = self.activation_credential_source(&expected_activation)?; - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - options.mode(0o400); - let mut file = options.open(&source).with_context(|| { - format!( - "creating one-shot activation credential {}", - source.display() - ) - })?; - let written = (|| -> Result { - #[cfg(unix)] - file.set_permissions(fs::Permissions::from_mode(0o400))?; - let activation = launch - .write_credential(&mut file) - .context("writing one-shot activation credential")?; - file.flush()?; - file.sync_all()?; - Ok(activation) - })(); - drop(file); - let activation = match written { - Ok(activation) => activation, - Err(error) => { - return match remove_activation_credential_source(&source) { - Ok(()) => Err(error), - Err(cleanup) => Err(error.context(format!( - "deleting incomplete activation credential also failed: {cleanup:#}" - ))), - }; - } - }; - let validation = (|| -> Result<()> { - ensure!( - activation == expected_activation, - "activation launch changed while writing its credential" - ); - validate_activation_credential_source(&source)?; - sync_parent_directory(&source) - })(); - if let Err(error) = validation { - return match remove_activation_credential_source(&source) { - Ok(()) => Err(error), - Err(cleanup) => Err(error.context(format!( - "deleting invalid activation credential also failed: {cleanup:#}" - ))), - }; - } - Ok((activation, source)) - } - - fn validate_prepared_activation_credential( - &self, - activation: &IdunnRuntimeActivationRecord, - source: &Path, - ) -> Result<()> { - validate_activation_credential_source(source)?; - let signer = IdunnRuntimeActivationSigner::from_credential_reader( - open_native_read_only(source).with_context(|| { - format!( - "opening prepared activation credential {}", - source.display() - ) - })?, - )?; - ensure!( - signer.identity_id() == activation.activation_signer_identity_id - && signer.public_key() == activation.activation_signer_public_key, - "prepared activation credential differs from the persisted activation" - ); - Ok(()) - } - - fn parent_only_file_descriptors( - &self, - binding: &OperatorBinding, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result> { - let activation_source = self.activation_credential_source(activation)?; - self.validate_prepared_activation_credential(activation, &activation_source)?; - let presence_source = binding - .workload - .secret_files - .get(RUNTIME_PRESENCE_IDENTITY_BINDING) - .context("workload has no parent-only runtime presence identity source")?; - let presence_signer = - open_service_identity_credential_reader::( - open_native_read_only(presence_source).with_context(|| { - format!( - "opening runtime presence identity source {}", - presence_source.display() - ) - })?, - )?; - ensure!( - presence_signer.entry().identity_id == expected.expected_signer_identity_id, - "runtime presence identity source differs from Expected" - ); - let descriptors = vec![ - observe_parent_only_file_descriptor( - 3, - IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, - &activation_source, - )?, - observe_parent_only_file_descriptor( - 4, - RUNTIME_PRESENCE_IDENTITY_FD_NAME, - presence_source, - )?, - ]; - parent_only_open_file_properties(&descriptors)?; - Ok(descriptors) - } - - fn stop_submitted_unit(&self, unit: &str, expected_description: &str) -> Result<()> { - let Some(observation) = self.show_unit(unit)? else { - return Ok(()); - }; - let values = &observation.properties; - ensure!( - values.get("Description").map(String::as_str) == Some(expected_description), - "refusing to stop a submitted unit whose description changed" - ); - self.command( - &self.systemctl_program, - [OsString::from("stop"), OsString::from(unit)], - )?; - if let Some(observation) = self.show_unit(unit)? { - let values = &observation.properties; - ensure!( - values - .get("ActiveState") - .is_some_and(|state| { matches!(state.as_str(), "inactive" | "failed") }), - "submitted systemd unit remained active after stop" - ); - } - Ok(()) - } - - fn install_release( - &self, - plan: &CompiledDeploymentPlan, - release: &MaterializedRelease, - ) -> Result { - release.release.validate_against(plan)?; - let (_, binding) = plan.parsed_inputs()?; - let release_root = &binding.workload.release_root; - fs::create_dir_all(release_root) - .with_context(|| format!("creating release root {}", release_root.display()))?; - let installed = release_root.join(&release.release.sealed_release_id); - if !installed.exists() { - let temporary = release_root.join(format!( - ".install-{}-{}", - release.release.sealed_release_id, - Uuid::new_v4() - )); - copy_tree(&release.root, &temporary)?; - if let Err(error) = fs::rename(&temporary, &installed) { - let cleanup = remove_tree_inside(release_root, &temporary); - if installed.exists() && error.kind() == ErrorKind::AlreadyExists { - cleanup?; - } else { - cleanup?; - return Err(error).with_context(|| { - format!("installing sealed release {}", installed.display()) - }); - } - } - } - for artifact in &release.release.artifacts { - let path = installed.join(&artifact.destination); - let (sha256, size_bytes) = digest_artifact(&path)?; - ensure!( - format!("sha256-{sha256}") == artifact.sha256 && size_bytes == artifact.size_bytes, - "installed artifact {} differs from its sealed receipt", - artifact.artifact_id - ); - } - harden_installed_release(&installed, &release.release.artifacts)?; - Ok(InstalledReleaseObservation { - sealed_release_id: release.release.sealed_release_id.clone(), - root: installed, - }) - } - - fn validate_installed_release( - &self, - plan: &CompiledDeploymentPlan, - release: &SealedRelease, - installed: &InstalledReleaseObservation, - ) -> Result<()> { - release.validate_against(plan)?; - let (_, binding) = plan.parsed_inputs()?; - ensure!( - installed.sealed_release_id == release.sealed_release_id - && installed.root - == binding - .workload - .release_root - .join(&release.sealed_release_id), - "installed release observation belongs to another sealed release" - ); - for artifact in &release.artifacts { - let path = installed.root.join(&artifact.destination); - let (sha256, size_bytes) = digest_artifact(&path)?; - ensure!( - format!("sha256-{sha256}") == artifact.sha256 && size_bytes == artifact.size_bytes, - "installed artifact {} differs from its sealed receipt", - artifact.artifact_id - ); - } - harden_installed_release(&installed.root, &release.artifacts) - } - - fn prepare_runtime_bundle( - &self, - binding: &OperatorBinding, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result { - let bundle = binding - .workload - .runtime_root - .join(&activation.runtime_instance_id); - fs::create_dir_all(&bundle) - .with_context(|| format!("creating runtime bundle {}", bundle.display()))?; - write_immutable_record( - &bundle.join("expected.cc"), - CultCacheEnvelope { - key: expected.target.clone(), - r#type: IdunnExpectedIncarnationRecord::TYPE.into(), - payload: expected.canonical_bytes()?, - stored_at: rfc3339_millis(activation.issued_at_unix_millis)?, - schema_id: Some(IDUNN_EXPECTED_INCARNATION_SCHEMA.into()), - }, - )?; - write_immutable_record( - &bundle.join("activation.cc"), - CultCacheEnvelope { - key: expected.target.clone(), - r#type: IdunnRuntimeActivationRecord::TYPE.into(), - payload: activation.canonical_bytes()?, - stored_at: rfc3339_millis(activation.issued_at_unix_millis)?, - schema_id: Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA.into()), - }, - )?; - harden_runtime_bundle(&bundle)?; - Ok(bundle) - } - - fn show_unit(&self, unit: &str) -> Result> { - ensure!( - self.systemctl_program.is_absolute(), - "systemctl program is not absolute" - ); - let output = Command::new(&self.systemctl_program) - .args([ - OsString::from("show"), - OsString::from(unit), - OsString::from("--no-pager"), - OsString::from("--property=LoadState"), - OsString::from("--property=ActiveState"), - OsString::from("--property=SubState"), - OsString::from("--property=Description"), - OsString::from("--property=InvocationID"), - OsString::from("--property=MainPID"), - OsString::from("--property=ExecMainStartTimestampMonotonic"), - OsString::from("--property=Type"), - OsString::from("--property=Restart"), - OsString::from("--property=KillMode"), - OsString::from("--property=DynamicUser"), - OsString::from("--property=User"), - OsString::from("--property=Group"), - OsString::from("--property=SupplementaryGroups"), - OsString::from("--property=CapabilityBoundingSet"), - OsString::from("--property=AmbientCapabilities"), - OsString::from("--property=PrivateMounts"), - OsString::from("--property=PrivatePIDs"), - OsString::from("--property=ProtectProc"), - OsString::from("--property=ProcSubset"), - OsString::from("--property=NoNewPrivileges"), - OsString::from("--property=UMask"), - OsString::from("--property=InaccessiblePaths"), - OsString::from("--property=LoadCredential"), - OsString::from("--property=OpenFile"), - OsString::from("--property=WorkingDirectory"), - OsString::from("--property=ControlGroup"), - ]) - .stdin(Stdio::null()) - .env_clear() - .env("LANG", "C.UTF-8") - .output() - .with_context(|| format!("observing systemd unit {unit}"))?; - let text = - std::str::from_utf8(&output.stdout).context("systemd show output is not UTF-8")?; - let mut values = BTreeMap::new(); - let mut open_files = Vec::new(); - for line in text.lines().filter(|line| !line.is_empty()) { - let (name, value) = line - .split_once('=') - .context("systemd show output is malformed")?; - if name == "OpenFile" { - open_files.push(value.to_owned()); - continue; - } - ensure!( - values.insert(name.to_owned(), value.to_owned()).is_none(), - "systemd show property is duplicated" - ); - } - if values - .get("LoadState") - .is_some_and(|value| value == "not-found") - { - return Ok(None); - } - ensure!( - output.status.success(), - "systemd show failed for {unit}: {}", - String::from_utf8_lossy(&output.stderr).trim() - ); - Ok(Some(SystemdUnitObservation { - properties: values, - open_files, - })) - } - - fn observe_unit( - &self, - unit: &str, - expected_executable: &Path, - runtime_instance_id: &str, - activation_signer_identity_id: &str, - activation_signer_public_key: &[u8], - environment_names: &[String], - service_credential_names: &[String], - parent_only_file_descriptors: &[ParentOnlyFileDescriptorObservation], - ) -> Result { - ensure!( - service_credential_names - .windows(2) - .all(|pair| pair[0] < pair[1]), - "service credential names are not unique and sorted" - ); - let unit_observation = self - .show_unit(unit)? - .with_context(|| format!("systemd unit {unit} is absent"))?; - let values = &unit_observation.properties; - ensure!( - unit_observation.open_files - == parent_only_open_file_properties(parent_only_file_descriptors)?, - "systemd parent-only descriptor contract differs from the Idunn launch" - ); - ensure!( - values - .get("ActiveState") - .is_some_and(|value| value == "active") - && values - .get("SubState") - .is_some_and(|value| value == "running"), - "systemd unit {unit} is not running" - ); - let invocation_id = values - .get("InvocationID") - .filter(|value| value.len() == 32 && value.bytes().all(|byte| byte.is_ascii_hexdigit())) - .context("systemd unit has no canonical invocation id")? - .clone(); - let exec_main_start_timestamp_monotonic = - required_systemd_property(&values, "ExecMainStartTimestampMonotonic")? - .parse::() - .context("systemd unit has no numeric main-process start timestamp")?; - ensure!( - exec_main_start_timestamp_monotonic > 0, - "systemd unit has no main-process start timestamp" - ); - let unit_description = required_systemd_property(&values, "Description")?.to_owned(); - let service_type = required_systemd_property(&values, "Type")?.to_owned(); - let restart_policy = required_systemd_property(&values, "Restart")?.to_owned(); - let kill_mode = required_systemd_property(&values, "KillMode")?.to_owned(); - let dynamic_user = parse_systemd_boolean(&values, "DynamicUser")?; - let systemd_user = systemd_property(&values, "User")?.to_owned(); - let systemd_group = systemd_property(&values, "Group")?.to_owned(); - let supplementary_groups = systemd_property(&values, "SupplementaryGroups")?.to_owned(); - let capability_bounding_set = - systemd_property(&values, "CapabilityBoundingSet")?.to_owned(); - let ambient_capabilities = systemd_property(&values, "AmbientCapabilities")?.to_owned(); - let private_mounts = parse_systemd_boolean(&values, "PrivateMounts")?; - let private_pids = parse_systemd_boolean(&values, "PrivatePIDs")?; - let protect_proc = required_systemd_property(&values, "ProtectProc")?.to_owned(); - let proc_subset = required_systemd_property(&values, "ProcSubset")?.to_owned(); - let no_new_privileges = parse_systemd_boolean(&values, "NoNewPrivileges")?; - let umask = required_systemd_property(&values, "UMask")?.to_owned(); - let inaccessible_paths = - required_systemd_property(&values, "InaccessiblePaths")?.to_owned(); - let load_credential = required_systemd_property(&values, "LoadCredential")?.to_owned(); - ensure!( - service_type == "exec" - && restart_policy == "no" - && kill_mode == "mixed" - && dynamic_user - && systemd_user.is_empty() - && supplementary_groups.is_empty() - && capability_bounding_set.is_empty() - && ambient_capabilities.is_empty() - && private_mounts - && private_pids - && protect_proc == "invisible" - && proc_subset == "all" - && no_new_privileges - && umask == "0007" - && inaccessible_paths == self.credential_root.display().to_string() - && load_credential - == if service_credential_names.is_empty() { - "" - } else { - "[unprintable]" - }, - "systemd workload isolation properties differ from the Idunn contract" - ); - let working_directory = - PathBuf::from(required_systemd_property(&values, "WorkingDirectory")?); - ensure!( - working_directory.is_absolute(), - "systemd unit working directory is not absolute" - ); - let control_group = required_systemd_property(&values, "ControlGroup")?.to_owned(); - ensure!( - control_group.starts_with('/') && !control_group.contains(['\n', '\r', '\0']), - "systemd unit control group is invalid" - ); - let main_pid: u32 = values - .get("MainPID") - .context("systemd unit has no MainPID")? - .parse() - .context("systemd MainPID is not a u32")?; - ensure!(main_pid > 0, "systemd unit has no live main process"); - let process_root = self.proc_root.join(main_pid.to_string()); - let process_executable = process_root.join("exe"); - let executable = fs::read_link(&process_executable) - .with_context(|| format!("observing executable for process {main_pid}"))?; - let mut executable_file = open_proc_magic_link(&process_executable)?; - let executable_metadata = executable_file.metadata()?; - let expected_executable_metadata = fs::metadata(expected_executable)?; - #[cfg(unix)] - let (executable_device, executable_inode) = { - use std::os::unix::fs::MetadataExt; - ensure!( - executable_metadata.is_file() - && executable_metadata.dev() == expected_executable_metadata.dev() - && executable_metadata.ino() == expected_executable_metadata.ino(), - "systemd started an executable inode outside the sealed release" - ); - (executable_metadata.dev(), executable_metadata.ino()) - }; - #[cfg(not(unix))] - let (executable_device, executable_inode) = (0, 0); - ensure!( - fs::canonicalize(&executable)? == fs::canonicalize(expected_executable)?, - "systemd started an executable outside the sealed release" - ); - let executable_sha256 = sha256_reader(&mut executable_file)?; - let process_start_time = linux_process_start_time(&process_root.join("stat"))?; - let process_security = linux_process_security(&process_root.join("status"), main_pid)?; - ensure!( - process_security - .uids - .iter() - .all(|uid| *uid == process_security.uids[0]) - && (61_184..=65_519).contains(&process_security.uids[0]), - "systemd workload does not have one unprivileged process uid" - ); - ensure!( - process_security - .gids - .iter() - .all(|gid| *gid == process_security.gids[0]) - && process_security.gids[0] > 0 - && process_security - .groups - .iter() - .all(|gid| *gid == process_security.gids[0]), - "systemd workload has foreign supplementary groups" - ); - ensure!( - [ - process_security.cap_inheritable, - process_security.cap_permitted, - process_security.cap_effective, - process_security.cap_bounding, - process_security.cap_ambient, - ] - .iter() - .all(|capabilities| *capabilities == 0), - "systemd workload retained Linux capabilities" - ); - ensure!( - process_security.no_new_privileges, - "systemd workload lacks kernel no-new-privileges enforcement" - ); - ensure!( - process_security.namespace_pids.len() >= 2 - && process_security.namespace_pids[0] == main_pid - && process_security.namespace_pids.last() == Some(&1) - && process_security.namespace_pids.iter().all(|pid| *pid > 0), - "systemd workload is not observed in a private pid namespace" - ); - let mount_namespace_id = linux_namespace_id(&process_root.join("ns/mnt"), "mnt")?; - let pid_namespace_id = linux_namespace_id(&process_root.join("ns/pid"), "pid")?; - let observer_mount_namespace_id = - linux_namespace_id(&self.proc_root.join("self/ns/mnt"), "mnt")?; - let observer_pid_namespace_id = - linux_namespace_id(&self.proc_root.join("self/ns/pid"), "pid")?; - ensure!( - mount_namespace_id != observer_mount_namespace_id - && pid_namespace_id != observer_pid_namespace_id, - "systemd workload did not receive private mount and pid namespaces" - ); - let process_control_groups = fs::read_to_string(process_root.join("cgroup"))?; - let process_control_groups = process_control_groups.lines().collect::>(); - ensure!( - process_control_groups.len() == 1 - && process_control_groups[0] == format!("0::{control_group}"), - "systemd MainPID is outside the unit control group" - ); - let command_line = fs::read(process_root.join("cmdline"))?; - ensure!( - !command_line.is_empty(), - "systemd MainPID has no command line" - ); - let process_environment = read_process_environment(&process_root.join("environ"))?; - let selected_environment = - select_process_environment(&process_environment, environment_names)?; - let runtime_bundle = PathBuf::from( - selected_environment - .get(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT) - .context("systemd MainPID lacks the Idunn runtime bundle environment")?, - ); - ensure!( - runtime_bundle.is_absolute(), - "runtime bundle path is not absolute" - ); - let credentials_directory = if service_credential_names.is_empty() { - ensure!( - !process_environment - .iter() - .any(|entry| entry.starts_with(b"CREDENTIALS_DIRECTORY=")), - "systemd MainPID exposed an unowned credential directory" - ); - None - } else { - let path = PathBuf::from(required_process_environment_value( - &process_environment, - "CREDENTIALS_DIRECTORY", - )?); - ensure!( - path == Path::new("/run/credentials").join(unit), - "systemd MainPID exposed an unexpected credential directory" - ); - Some(path) - }; - let activation_descriptor = &parent_only_file_descriptors[0]; - ensure!( - activation_descriptor.fd_name == IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME - && activation_descriptor.size == 32 - && activation_descriptor.uid == 0 - && activation_descriptor.gid == 0 - && activation_descriptor.mode == 0o400 - && activation_descriptor.links == 1, - "activation signing descriptor is not exact root-only source material" - ); - let mut service_credentials = Vec::new(); - for name in service_credential_names { - let delivered_path = credentials_directory - .as_ref() - .context("service credential has no systemd credential directory")? - .join(name); - let delivered_value = delivered_path.display().to_string(); - ensure!( - selected_environment.get(name) == Some(&delivered_value), - "workload secret environment does not name its delivered systemd credential" - ); - let observer_path = - path_inside_process_root(&process_root.join("root"), &delivered_path)?; - let mut file = open_native_read_only(&observer_path).with_context(|| { - format!( - "opening delivered service credential {}", - delivered_path.display() - ) - })?; - let metadata = file.metadata()?; - #[cfg(unix)] - let (device, inode, uid, gid, mode, links) = { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - ( - metadata.dev(), - metadata.ino(), - metadata.uid(), - metadata.gid(), - metadata.permissions().mode() & 0o777, - metadata.nlink(), - ) - }; - #[cfg(not(unix))] - let (device, inode, uid, gid, mode, links) = (0, 0, 0, 0, 0, 0); - ensure!( - metadata.is_file() - && metadata.len() > 0 - && links == 1 - && uid == process_security.uids[0] - && gid == process_security.gids[0] - && mode == 0o400, - "delivered service credential is not readable only by the workload identity" - ); - service_credentials.push(ServiceCredentialObservation { - environment_name: name.clone(), - delivered_path, - device, - inode, - uid, - gid, - mode, - size: metadata.len(), - sha256: sha256_reader(&mut file)?, - }); - } - let final_values = self - .show_unit(unit)? - .with_context(|| format!("systemd unit {unit} vanished during observation"))?; - ensure!( - final_values == unit_observation - && linux_process_start_time(&process_root.join("stat"))? == process_start_time, - "systemd workload identity changed during native observation" - ); - Ok(WorkloadObservation { - unit: unit.to_owned(), - unit_description, - invocation_id, - exec_main_start_timestamp_monotonic, - service_type, - restart_policy, - kill_mode, - dynamic_user, - systemd_user, - systemd_group, - supplementary_groups, - capability_bounding_set, - ambient_capabilities, - private_mounts, - private_pids, - protect_proc, - proc_subset, - no_new_privileges, - umask, - inaccessible_paths, - load_credential, - main_pid, - process_start_time, - process_uids: process_security.uids, - process_gids: process_security.gids, - process_groups: process_security.groups, - process_cap_inheritable: process_security.cap_inheritable, - process_cap_permitted: process_security.cap_permitted, - process_cap_effective: process_security.cap_effective, - process_cap_bounding: process_security.cap_bounding, - process_cap_ambient: process_security.cap_ambient, - process_no_new_privileges: process_security.no_new_privileges, - process_namespace_pids: process_security.namespace_pids, - mount_namespace_id, - pid_namespace_id, - executable, - executable_device, - executable_inode, - executable_sha256, - runtime_instance_id: runtime_instance_id.to_owned(), - working_directory, - runtime_bundle, - command_line_sha256: sha256_id(&command_line), - environment_names: environment_names.to_vec(), - environment_contract_sha256: sha256_id(&rmp_serde::to_vec(&selected_environment)?), - control_group, - credentials_directory, - parent_only_file_descriptors: parent_only_file_descriptors.to_vec(), - activation_signer_identity_id: activation_signer_identity_id.to_owned(), - activation_signer_public_key: activation_signer_public_key.to_vec(), - service_credentials, - }) - } - - fn launch_command( - &self, - declaration: &TargetDeclaration, - binding: &OperatorBinding, - installed: &Path, - ) -> Result> { - let executable_artifact = - release_artifact(declaration, &declaration.service.executable_artifact)?; - let executable = installed.join(&executable_artifact.destination); - ensure!(executable.is_file(), "sealed service executable is absent"); - let mut command = vec![executable.into_os_string()]; - for argument in &declaration.service.arguments { - command.push(match argument { - LaunchArgument::Literal { value } => value.into(), - LaunchArgument::Binding { name } => { - binding.workload.argument_bindings[name].clone().into() - } - }); - } - Ok(command) - } - - fn launch_environment( - &self, - binding: &OperatorBinding, - bundle: &Path, - expected: &IdunnExpectedIncarnationRecord, - unit: &str, - ) -> Result> { - let mut environment = binding.workload.environment.clone(); - let credentials_directory = Path::new("/run/credentials").join(unit); - for name in binding - .workload - .secret_files - .keys() - .filter(|name| name.as_str() != RUNTIME_PRESENCE_IDENTITY_BINDING) - { - ensure!( - environment - .insert( - name.clone(), - credentials_directory.join(name).display().to_string(), - ) - .is_none(), - "workload environment and secret bindings collide" - ); - } - ensure!( - environment - .insert( - IDUNN_RUNTIME_BUNDLE_ENVIRONMENT.into(), - bundle.display().to_string(), - ) - .is_none(), - "operator binding attempts to replace the Idunn runtime bundle" - ); - match &expected.route { - Some(route) => { - let (host, port) = endpoint_host_port( - &route.candidate_endpoint, - &format!("{}://", route.transport), - )?; - ensure!( - environment - .insert( - IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT.into(), - format!("{host}:{port}"), - ) - .is_none(), - "operator binding attempts to replace the Idunn candidate bind" - ); - } - None => ensure!( - !environment.contains_key(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT), - "unrouted workload carries an Idunn candidate bind" - ), - } - match &binding.process_write_lease { - Some(write_lease) => ensure!( - environment - .insert( - IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT.into(), - write_lease.record_path.display().to_string(), - ) - .is_none(), - "operator binding attempts to replace the Idunn process write lease" - ), - None => ensure!( - !environment.contains_key(IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT), - "stateless workload carries an Idunn process write lease" - ), - } - Ok(environment) - } - - fn validate_launch_observation( - &self, - observation: &WorkloadObservation, - declaration: &TargetDeclaration, - binding: &OperatorBinding, - installed: &Path, - bundle: &Path, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result<()> { - let command = self.launch_command(declaration, binding, installed)?; - let environment = self.launch_environment(binding, bundle, expected, &observation.unit)?; - let environment_names = environment.keys().cloned().collect::>(); - let expected_description = format!( - "Idunn {} {}", - binding.target, - bundle - .file_name() - .context("runtime bundle has no instance id")? - .to_string_lossy() - ); - ensure!( - observation.unit.ends_with(".service"), - "workload unit has no service suffix" - ); - let expected_group = binding.workload.state_group.as_deref(); - let expected_group_id = expected_group.map(resolve_group_id).transpose()?; - let regular_credential_names = binding - .workload - .secret_files - .keys() - .filter(|name| name.as_str() != RUNTIME_PRESENCE_IDENTITY_BINDING) - .cloned() - .collect::>(); - let expected_credentials_directory = (!regular_credential_names.is_empty()) - .then(|| Path::new("/run/credentials").join(&observation.unit)); - let descriptor_properties = - parent_only_open_file_properties(&observation.parent_only_file_descriptors)?; - let activation_source = self.activation_credential_source(activation)?; - let presence_source = binding - .workload - .secret_files - .get(RUNTIME_PRESENCE_IDENTITY_BINDING) - .context("workload has no parent-only runtime presence identity source")?; - let observed_credential_names = observation - .service_credentials - .iter() - .map(|credential| credential.environment_name.clone()) - .collect::>(); - ensure!( - observation.unit_description == expected_description - && observation.service_type == "exec" - && observation.restart_policy == "no" - && observation.kill_mode == "mixed" - && observation.dynamic_user - && observation.systemd_user.is_empty() - && match expected_group { - Some(group) => observation.systemd_group == group, - None => observation.systemd_group.is_empty(), - } - && observation.supplementary_groups.is_empty() - && observation.capability_bounding_set.is_empty() - && observation.ambient_capabilities.is_empty() - && observation.private_mounts - && observation.private_pids - && observation.protect_proc == "invisible" - && observation.proc_subset == "all" - && observation.no_new_privileges - && observation.umask == "0007" - && observation.inaccessible_paths == self.credential_root.display().to_string() - && observation.load_credential - == if regular_credential_names.is_empty() { - "" - } else { - "[unprintable]" - } - && observation.working_directory == installed - && observation.runtime_bundle == bundle - && observation.credentials_directory == expected_credentials_directory - && observation.command_line_sha256 == sha256_id(&proc_command_line(&command)) - && observation.environment_names == environment_names - && observation.environment_contract_sha256 - == sha256_id(&rmp_serde::to_vec(&environment)?) - && descriptor_properties.len() == 2 - && observation.parent_only_file_descriptors[0].source_path == activation_source - && observation.parent_only_file_descriptors[0].size == 32 - && observation.parent_only_file_descriptors[1].source_path == *presence_source - && observation.activation_signer_identity_id - == activation.activation_signer_identity_id - && observation.activation_signer_public_key - == activation.activation_signer_public_key - && observed_credential_names == regular_credential_names - && match expected_group_id { - Some(group_id) => observation.process_gids[0] == group_id, - None => observation.process_gids[0] == observation.process_uids[0], - }, - "running workload launch contract differs from the admitted launch" - ); - ensure!( - Path::new(&observation.control_group).file_name() - == Some(OsStr::new(&observation.unit)), - "running workload control group belongs to another unit" - ); - Ok(()) - } - - fn validate_writable_bindings(&self, binding: &OperatorBinding) -> Result<()> { - let Some(state_group) = binding.workload.state_group.as_deref() else { - ensure!( - binding.workload.state_root.is_none() - && binding.workload.read_write_paths.is_empty(), - "dynamic workload writable paths have no fixed state group" - ); - return Ok(()); - }; - let state_group_id = resolve_group_id(state_group)?; - if let Some(state_root) = &binding.workload.state_root { - validate_workload_writable_path(state_root, state_group_id, true)?; - } - for path in &binding.workload.read_write_paths { - validate_workload_writable_path(path, state_group_id, false)?; - } - Ok(()) - } - - fn start_transient( - &self, - declaration: &TargetDeclaration, - binding: &OperatorBinding, - installed: &Path, - bundle: &Path, - expected: &IdunnExpectedIncarnationRecord, - parent_only_file_descriptors: &[ParentOnlyFileDescriptorObservation], - unit: &str, - ) -> Result<()> { - ensure!( - declaration - .service - .required_environment - .contains(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT), - "target does not declare the standard Idunn runtime bundle" - ); - ensure!( - !binding - .workload - .environment - .contains_key(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT) - && !binding - .workload - .secret_files - .contains_key(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT), - "operator binding attempts to replace the Idunn runtime bundle" - ); - validate_service_credential_sources(&binding.workload.secret_files)?; - let parent_only_open_files = - parent_only_open_file_properties(parent_only_file_descriptors)?; - let environment = self.launch_environment(binding, bundle, expected, unit)?; - let executable_artifact = - release_artifact(declaration, &declaration.service.executable_artifact)?; - let executable = installed.join(&executable_artifact.destination); - ensure!(executable.is_file(), "sealed service executable is absent"); - let unit_description = format!( - "Idunn {} {}", - binding.target, - bundle - .file_name() - .context("runtime bundle has no instance id")? - .to_string_lossy() - ); - let mut args = vec![ - OsString::from("--no-block"), - OsString::from("--no-ask-password"), - OsString::from("--expand-environment=no"), - OsString::from(format!("--unit={unit}")), - OsString::from("--property=Type=exec"), - OsString::from("--property=Restart=no"), - OsString::from("--property=KillMode=mixed"), - OsString::from("--property=DynamicUser=yes"), - OsString::from("--property=SupplementaryGroups="), - OsString::from("--property=CapabilityBoundingSet="), - OsString::from("--property=AmbientCapabilities="), - OsString::from("--property=NoNewPrivileges=yes"), - OsString::from("--property=PrivateMounts=yes"), - OsString::from("--property=PrivatePIDs=yes"), - OsString::from("--property=ProtectProc=invisible"), - OsString::from("--property=ProcSubset=all"), - OsString::from("--property=PrivateTmp=yes"), - OsString::from("--property=ProtectSystem=strict"), - OsString::from("--property=ProtectHome=yes"), - OsString::from("--property=ProtectControlGroups=yes"), - OsString::from("--property=ProtectKernelModules=yes"), - OsString::from("--property=ProtectKernelTunables=yes"), - OsString::from("--property=RestrictSUIDSGID=yes"), - OsString::from("--property=LockPersonality=yes"), - OsString::from("--property=UMask=0007"), - OsString::from(format!("--property=Description={unit_description}")), - OsString::from(format!( - "--property=InaccessiblePaths={}", - self.credential_root.display() - )), - OsString::from(format!( - "--property=MemoryMax={}M", - binding.workload.memory_mebibytes - )), - OsString::from(format!( - "--property=CPUQuota={}%", - binding.workload.cpu_quota_percent - )), - OsString::from(format!("--working-directory={}", installed.display())), - OsString::from(format!("--property=ReadOnlyPaths={}", installed.display())), - OsString::from(format!("--property=ReadOnlyPaths={}", bundle.display())), - ]; - for open_file in parent_only_open_files { - args.push(OsString::from(format!("--property=OpenFile={open_file}"))); - } - if let Some(state_group) = &binding.workload.state_group { - args.push(OsString::from(format!("--property=Group={state_group}"))); - } - if binding.workload.network == WorkloadNetwork::None { - args.push(OsString::from("--property=PrivateNetwork=yes")); - } - if let Some(state_root) = &binding.workload.state_root { - args.push(OsString::from(format!( - "--property=ReadWritePaths={}", - state_root.display() - ))); - } - if let Some(write_lease) = &binding.process_write_lease { - for path in [write_lease.record_path.clone(), write_lease.lock_path()] { - args.push(OsString::from(format!( - "--property=ReadOnlyPaths=-{}", - path.display() - ))); - } - } - for path in &binding.workload.read_only_paths { - args.push(OsString::from(format!( - "--property=ReadOnlyPaths={}", - path.display() - ))); - } - for path in &binding.workload.read_write_paths { - args.push(OsString::from(format!( - "--property=ReadWritePaths={}", - path.display() - ))); - } - if binding.workload.devices.is_empty() { - args.push(OsString::from("--property=PrivateDevices=yes")); - } else { - args.push(OsString::from("--property=DevicePolicy=closed")); - for device in &binding.workload.devices { - args.push(OsString::from(format!( - "--property=DeviceAllow={} rw", - device.display() - ))); - } - } - for (name, value) in environment { - args.push(OsString::from(format!("--setenv={name}={value}"))); - } - for (name, path) in binding - .workload - .secret_files - .iter() - .filter(|(name, _)| name.as_str() != RUNTIME_PRESENCE_IDENTITY_BINDING) - { - args.push(OsString::from(format!( - "--property=LoadCredential={name}:{}", - path.display() - ))); - } - args.extend(self.launch_command(declaration, binding, installed)?); - self.command(&self.systemd_run_program, args)?; - Ok(()) - } -} - -impl WorkloadPort for SystemdTransientWorkloadDriver { - fn install( - &self, - plan: &CompiledDeploymentPlan, - release: &MaterializedRelease, - ) -> Result { - self.install_release(plan, release) - } - - fn prepare_activation( - &self, - plan: &CompiledDeploymentPlan, - expected: &IdunnExpectedIncarnationRecord, - launch: IdunnRuntimeActivationLaunch, - ) -> Result { - plan.validate()?; - expected.validate()?; - let proposed_activation = launch.activation(); - proposed_activation.validate()?; - ensure!( - expected.plan_id == plan.plan_id - && proposed_activation.expected_projection_sha256 == expected.canonical_sha256()?, - "prepared activation does not belong to the deployment plan" - ); - let (_, binding) = plan.parsed_inputs()?; - ensure!( - expected.target == binding.target, - "prepared activation target differs from the operator binding" - ); - let unit = self.unit_name( - &binding.workload.unit_prefix, - &proposed_activation.runtime_instance_id, - )?; - ensure!( - self.show_unit(&unit)?.is_none(), - "refusing to replace prepared activation material while its deterministic unit exists" - ); - ensure_activation_credential_root(&self.credential_root)?; - let source = self.activation_credential_source(proposed_activation)?; - match fs::symlink_metadata(&source) { - Ok(_) => remove_activation_credential_source(&source) - .context("retiring an orphaned pre-persistence activation credential")?, - Err(error) if error.kind() == ErrorKind::NotFound => {} - Err(error) => { - return Err(error).with_context(|| { - format!( - "inspecting pre-persistence activation credential {}", - source.display() - ) - }); - } - } - let (activation, written_source) = self.write_activation_credential(launch)?; - if written_source != source { - let error = - anyhow::anyhow!("prepared activation used a nondeterministic credential path"); - return match remove_activation_credential_source(&written_source) { - Ok(()) => Err(error), - Err(cleanup) => Err(error.context(format!( - "deleting nondeterministic activation credential also failed: {cleanup:#}" - ))), - }; - } - Ok(activation) - } - - fn start_prepared( - &self, - plan: &CompiledDeploymentPlan, - release: &SealedRelease, - installed: &InstalledReleaseObservation, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result { - plan.validate()?; - release.validate_against(plan)?; - self.validate_installed_release(plan, release, installed)?; - expected.validate()?; - activation.validate()?; - ensure!( - expected.plan_id == plan.plan_id - && expected.sealed_release_id == release.sealed_release_id - && activation.expected_projection_sha256 == expected.canonical_sha256()?, - "workload inputs do not describe one sealed incarnation" - ); - let (declaration, binding) = plan.parsed_inputs()?; - self.validate_writable_bindings(&binding)?; - let executable_artifact = - release_artifact(&declaration, &declaration.service.executable_artifact)?; - let executable = installed.root.join(&executable_artifact.destination); - let unit = self.unit_name( - &binding.workload.unit_prefix, - &activation.runtime_instance_id, - )?; - let bundle = self.prepare_runtime_bundle(&binding, expected, activation)?; - let service_credential_names = binding - .workload - .secret_files - .keys() - .filter(|name| name.as_str() != RUNTIME_PRESENCE_IDENTITY_BINDING) - .cloned() - .collect::>(); - let environment_names = self - .launch_environment(&binding, &bundle, expected, &unit)? - .into_keys() - .collect::>(); - let parent_only_file_descriptors = - self.parent_only_file_descriptors(&binding, expected, activation)?; - let unit_exists = self.show_unit(&unit)?.is_some(); - if !unit_exists { - self.start_transient( - &declaration, - &binding, - &installed.root, - &bundle, - expected, - &parent_only_file_descriptors, - &unit, - )?; - } - let mut last_error = None; - for _ in 0..100 { - match self.observe_unit( - &unit, - &executable, - &activation.runtime_instance_id, - &activation.activation_signer_identity_id, - &activation.activation_signer_public_key, - &environment_names, - &service_credential_names, - &parent_only_file_descriptors, - ) { - Ok(observation) => { - let validation = self.validate_launch_observation( - &observation, - &declaration, - &binding, - &installed.root, - &bundle, - expected, - &activation, - ); - match validation.and_then(|()| { - ensure!( - observation.executable_sha256 == expected.artifact_sha256, - "started workload executable differs from Expected" - ); - Ok(()) - }) { - Ok(()) => return Ok(observation), - Err(error) => last_error = Some(error), - } - } - Err(error) => last_error = Some(error), - } - thread::sleep(Duration::from_millis(50)); - } - Err(last_error.unwrap_or_else(|| anyhow::anyhow!("systemd did not expose the candidate"))) - } - - fn discard_prepared( - &self, - plan: &CompiledDeploymentPlan, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result<()> { - plan.validate()?; - expected.validate()?; - activation.validate()?; - ensure!( - expected.plan_id == plan.plan_id - && activation.expected_projection_sha256 == expected.canonical_sha256()?, - "discarded activation does not belong to the prepared deployment" - ); - let (_, binding) = plan.parsed_inputs()?; - ensure!( - binding.target == expected.target, - "discarded activation target differs from its binding" - ); - let unit = self.unit_name( - &binding.workload.unit_prefix, - &activation.runtime_instance_id, - )?; - let unit_description = format!( - "Idunn {} {}", - binding.target, activation.runtime_instance_id - ); - self.stop_submitted_unit(&unit, &unit_description) - .context("stopping prepared candidate without a durable workload observation")?; - remove_activation_credential_source(&self.activation_credential_source(activation)?) - .context("deleting discarded activation credential source") - } - - fn observe( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - prior: &WorkloadObservation, - ) -> Result { - expected.validate()?; - activation.validate()?; - ensure!( - activation.expected_projection_sha256 == expected.canonical_sha256()? - && activation.runtime_instance_id == prior.runtime_instance_id, - "workload observation belongs to another activation" - ); - let observed = self.observe_unit( - &prior.unit, - &prior.executable, - &activation.runtime_instance_id, - &activation.activation_signer_identity_id, - &activation.activation_signer_public_key, - &prior.environment_names, - &prior - .service_credentials - .iter() - .map(|credential| credential.environment_name.clone()) - .collect::>(), - &prior.parent_only_file_descriptors, - )?; - ensure!( - observed == *prior && observed.executable_sha256 == expected.artifact_sha256, - "native workload identity changed after observation" - ); - let credential_source = self.activation_credential_source(activation)?; - remove_activation_credential_source(&credential_source) - .context("retiring a recovered activation credential source")?; - let after_unlink = self.observe_unit( - &prior.unit, - &prior.executable, - &activation.runtime_instance_id, - &activation.activation_signer_identity_id, - &activation.activation_signer_public_key, - &prior.environment_names, - &prior - .service_credentials - .iter() - .map(|credential| credential.environment_name.clone()) - .collect::>(), - &prior.parent_only_file_descriptors, - )?; - ensure!( - after_unlink == observed, - "native workload identity changed after recovered credential cleanup" - ); - Ok(after_unlink) - } - - fn stop(&self, observation: &WorkloadObservation) -> Result<()> { - let Some(unit_observation) = self.show_unit(&observation.unit)? else { - return Ok(()); - }; - let values = &unit_observation.properties; - let active = required_systemd_property(&values, "ActiveState")?; - let sub = required_systemd_property(&values, "SubState")?; - if active == "active" && sub == "running" { - let current = self.observe_unit( - &observation.unit, - &observation.executable, - &observation.runtime_instance_id, - &observation.activation_signer_identity_id, - &observation.activation_signer_public_key, - &observation.environment_names, - &observation - .service_credentials - .iter() - .map(|credential| credential.environment_name.clone()) - .collect::>(), - &observation.parent_only_file_descriptors, - )?; - ensure!( - current == *observation, - "refusing to stop a workload whose native identity changed" - ); - } else { - ensure!( - values.get("InvocationID") == Some(&observation.invocation_id) - && values.get("Description") == Some(&observation.unit_description) - && matches!(active, "inactive" | "failed"), - "refusing to stop a foreign or transitional systemd unit" - ); - } - self.command( - &self.systemctl_program, - [OsString::from("stop"), OsString::from(&observation.unit)], - )?; - if let Some(unit_observation) = self.show_unit(&observation.unit)? { - let values = &unit_observation.properties; - ensure!( - values - .get("ActiveState") - .is_some_and(|state| state == "inactive" || state == "failed"), - "systemd unit remained active after stop" - ); - } - Ok(()) - } -} - -/// One dedicated CultCache file is the write-lease authority for one target. -/// The admitted target holds its sibling lock shared for that process lifetime. -/// Grant and revocation therefore make one nonblocking CAS attempt; revocation -/// follows an exact incumbent stop. A foreign or stuck holder cannot freeze -/// Idunn's control loop. Route membership never enters this store. -pub struct CultCacheWriteLeaseDriver { - pub target: String, - pub record_path: PathBuf, -} - -impl CultCacheWriteLeaseDriver { - pub fn new(target: impl Into, record_path: impl Into) -> Self { - Self { - target: target.into(), - record_path: record_path.into(), - } - } - - fn current(&self) -> Result> { - validate_root_authority_path(&self.record_path)?; - if !self.record_path.exists() { - return Ok(None); - } - let entries = SingleFileMessagePackBackingStore::new(&self.record_path) - .pull_all_read_only_snapshot()?; - match entries.as_slice() { - [] => Ok(None), - [envelope] - if envelope.r#type == IdunnProcessWriteLeaseRecord::TYPE - && envelope.schema_id.as_deref() == Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA) => - { - let lease = IdunnProcessWriteLeaseRecord::decode_canonical(&envelope.payload)?; - ensure!( - envelope.key == lease.target, - "write-lease key is not its target" - ); - ensure!( - lease.target == self.target, - "write-lease store belongs to another target" - ); - Ok(Some((envelope.clone(), lease))) - } - _ => bail!("process write-lease store is foreign or ambiguous"), - } - } - - fn envelope(&self, lease: &IdunnProcessWriteLeaseRecord) -> Result { - Ok(CultCacheEnvelope { - key: lease.target.clone(), - r#type: IdunnProcessWriteLeaseRecord::TYPE.into(), - payload: lease.canonical_bytes()?, - stored_at: rfc3339_millis(lease.issued_at_unix_millis)?, - schema_id: Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into()), - }) - } - - fn validate_grant( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - warming: &SequenceAdmittedWarming, - lease: &IdunnProcessWriteLeaseRecord, - ) -> Result<()> { - expected.validate()?; - activation.validate()?; - lease.validate()?; - let expected_sha256 = expected.canonical_sha256()?; - let activation_sha256 = activation.canonical_sha256()?; - ensure!( - self.target == expected.target - && lease.target == expected.target - && lease.expected_projection_sha256 == expected_sha256 - && lease.plan_id == expected.plan_id - && lease.incarnation_id == expected.incarnation_id - && lease.sealed_release_id == expected.sealed_release_id - && lease.activation_witness_sha256 == activation_sha256 - && lease.runtime_id == expected.runtime_id - && lease.runtime_instance_id == activation.runtime_instance_id - && lease.state_schema_generation - == expected - .state_schema_generation - .as_deref() - .context("write-lease Expected has no state generation")? - && lease.state_contract_sha256 - == expected - .state_contract_sha256 - .as_deref() - .context("write-lease Expected has no state contract")? - && lease.warming_presence_sha256 == warming.signed_presence_sha256() - && warming.runtime_instance_id() == activation.runtime_instance_id.as_str(), - "process write lease does not bind the exact warming candidate" - ); - Ok(()) - } -} - -impl WriteLeasePort for CultCacheWriteLeaseDriver { - fn revoke_exact(&self, incumbent: Option<&IdunnProcessWriteLeaseRecord>) -> Result<()> { - if let Some(incumbent) = incumbent { - incumbent.validate()?; - ensure!( - incumbent.target == self.target, - "incumbent write lease belongs to another target" - ); - } - let current = self.current()?; - let Some((envelope, current_lease)) = current else { - return Ok(()); - }; - ensure!( - incumbent == Some(¤t_lease), - "refusing to revoke an unexpected process write lease" - ); - let store = SingleFileMessagePackBackingStore::new(&self.record_path); - match store.try_compare_exchange_snapshot(std::slice::from_ref(&envelope), &[])? { - TryCompareExchangeSnapshotOutcome::Exchanged => Ok(()), - TryCompareExchangeSnapshotOutcome::Mismatch => { - bail!("process write lease changed while fencing the incumbent") - } - TryCompareExchangeSnapshotOutcome::LockContended => { - bail!("process write lease is held by a shared-lock consumer") - } - } - } - - fn observe_empty(&self) -> Result { - Ok(self.current()?.is_none()) - } - - fn observe_exact(&self, lease: &IdunnProcessWriteLeaseRecord) -> Result { - lease.validate()?; - ensure!( - lease.target == self.target, - "observed process write lease belongs to another target" - ); - Ok(self - .current()? - .is_some_and(|(_, current)| current == *lease)) - } - - fn grant( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - warming: &SequenceAdmittedWarming, - lease: &IdunnProcessWriteLeaseRecord, - ) -> Result { - self.validate_grant(expected, activation, warming, lease)?; - if let Some((_, current)) = self.current()? { - ensure!( - current == *lease, - "another process already owns the write lease" - ); - harden_root_authority_file(&self.record_path)?; - harden_root_authority_file(&authority_lock_path(&self.record_path))?; - return lease.canonical_sha256(); - } - let envelope = self.envelope(lease)?; - let store = SingleFileMessagePackBackingStore::new(&self.record_path); - match store.try_compare_exchange_snapshot(&[], &[envelope])? { - TryCompareExchangeSnapshotOutcome::Exchanged => {} - TryCompareExchangeSnapshotOutcome::Mismatch => { - bail!("process write-lease grant lost its empty-store compare-exchange") - } - TryCompareExchangeSnapshotOutcome::LockContended => { - bail!("process write lease is held by a shared-lock consumer") - } - } - harden_root_authority_file(&self.record_path)?; - harden_root_authority_file(&authority_lock_path(&self.record_path))?; - lease.canonical_sha256() - } - - fn observe( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - warming: &SequenceAdmittedWarming, - lease: &IdunnProcessWriteLeaseRecord, - ) -> Result { - self.validate_grant(expected, activation, warming, lease)?; - Ok(self - .current()? - .is_some_and(|(_, current)| current == *lease)) - } -} - -/// Idunn projects desired identity plus its own activation and current-lease -/// facts here. Service presence is absent by construction; only Odin may -/// correlate these records with signed runtime observation into Present/Ready. -pub struct CultCacheTopologyDriver { - pub projection_store: PathBuf, - pub correlation_store: PathBuf, -} - -impl CultCacheTopologyDriver { - /// Atomically demotes a failed pre-fence candidate back to the admitted - /// generation's Expected projection. Runtime activation and write-lease - /// records are deliberately absent until admitted-body supervision proves - /// the physical process and lease again. - pub fn restore_admitted_expected_only( - &self, - failed_expected: &IdunnExpectedIncarnationRecord, - failed_provider_anchor: &ServiceIdentityTrustAnchor, - failed_activation: Option<&IdunnRuntimeActivationRecord>, - admitted_expected: &IdunnExpectedIncarnationRecord, - admitted_provider_anchor: &ServiceIdentityTrustAnchor, - admitted_activation: &IdunnRuntimeActivationRecord, - admitted_lease: Option<&IdunnProcessWriteLeaseRecord>, - ) -> Result { - failed_expected.validate()?; - admitted_expected.validate()?; - ensure!( - failed_expected.target == admitted_expected.target, - "projection restoration crosses deployment targets" - ); - let failed_anchor = runtime_presence_trust_anchor(failed_expected, failed_provider_anchor)?; - let admitted_anchor = - runtime_presence_trust_anchor(admitted_expected, admitted_provider_anchor)?; - if let Some(activation) = failed_activation { - activation.validate()?; - ensure!( - activation.expected_projection_sha256 == failed_expected.canonical_sha256()?, - "failed activation does not bind the failed Expected projection" - ); - } - admitted_activation.validate()?; - ensure!( - admitted_activation.expected_projection_sha256 - == admitted_expected.canonical_sha256()?, - "admitted activation does not bind the admitted Expected projection" - ); - if let Some(lease) = admitted_lease { - validate_topology_lease(admitted_expected, admitted_activation, lease)?; - } - if let Some(parent) = self.projection_store.parent() { - fs::create_dir_all(parent)?; - } - let store = SingleFileMessagePackBackingStore::new(&self.projection_store); - let target = admitted_expected.target.as_str(); - let anchor_key = runtime_presence_trust_anchor_id(target); - for _ in 0..8 { - let entries = store.pull_all_read_only_snapshot()?; - let current_expected = - projection_entry(&entries, IdunnExpectedIncarnationRecord::TYPE, target)?; - if let Some(envelope) = current_expected { - ensure!( - envelope.schema_id.as_deref() == Some(IDUNN_EXPECTED_INCARNATION_SCHEMA), - "restored Expected projection schema is foreign" - ); - let current = IdunnExpectedIncarnationRecord::decode_canonical(&envelope.payload)?; - ensure!( - current == *failed_expected || current == *admitted_expected, - "refusing to replace an unknown Expected projection" - ); - } - let current_anchor = projection_entry( - &entries, - GameCultServiceTrustAnchorRecord::TYPE, - &anchor_key, - )?; - if let Some(envelope) = current_anchor { - let current = service_trust_anchor_from_envelope(envelope)?; - ensure!( - current == failed_anchor || current == admitted_anchor, - "refusing to replace an unknown runtime presence trust anchor" - ); - } - let current_activation = - projection_entry(&entries, IdunnRuntimeActivationRecord::TYPE, target)?; - if let Some(envelope) = current_activation { - ensure!( - envelope.schema_id.as_deref() == Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA), - "restored activation projection schema is foreign" - ); - let current = IdunnRuntimeActivationRecord::decode_canonical(&envelope.payload)?; - ensure!( - failed_activation == Some(¤t) || admitted_activation == ¤t, - "refusing to remove an unknown runtime activation projection" - ); - } - let current_lease = - projection_entry(&entries, IdunnProcessWriteLeaseRecord::TYPE, target)?; - if let Some(envelope) = current_lease { - ensure!( - envelope.schema_id.as_deref() == Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA), - "restored write-lease projection schema is foreign" - ); - let current = IdunnProcessWriteLeaseRecord::decode_canonical(&envelope.payload)?; - ensure!( - admitted_lease == Some(¤t), - "refusing to remove an unknown process write-lease projection" - ); - } - if current_expected.is_some_and(|envelope| { - IdunnExpectedIncarnationRecord::decode_canonical(&envelope.payload) - .is_ok_and(|current| current == *admitted_expected) - }) && current_anchor.is_some_and(|envelope| { - service_trust_anchor_from_envelope(envelope) - .is_ok_and(|current| current == admitted_anchor) - }) && current_activation.is_none() - && current_lease.is_none() - { - return admitted_expected.canonical_sha256(); - } - let mut replacement = entries - .iter() - .filter(|envelope| { - !((envelope.key == target - && matches!( - envelope.r#type.as_str(), - IdunnExpectedIncarnationRecord::TYPE - | IdunnRuntimeActivationRecord::TYPE - | IdunnProcessWriteLeaseRecord::TYPE - )) - || (envelope.key == anchor_key - && envelope.r#type == GameCultServiceTrustAnchorRecord::TYPE)) - }) - .cloned() - .collect::>(); - replacement.extend([ - CultCacheEnvelope { - key: admitted_expected.target.clone(), - r#type: IdunnExpectedIncarnationRecord::TYPE.into(), - payload: admitted_expected.canonical_bytes()?, - stored_at: chrono::Utc::now().to_rfc3339(), - schema_id: Some(IDUNN_EXPECTED_INCARNATION_SCHEMA.into()), - }, - CultCacheEnvelope { - key: admitted_anchor.trust_anchor_id.clone(), - r#type: GameCultServiceTrustAnchorRecord::TYPE.into(), - payload: rmp_serde::to_vec(&admitted_anchor)?, - stored_at: rfc3339_millis(admitted_anchor.bound_at_unix_millis)?, - schema_id: Some(GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into()), - }, - ]); - if store.compare_exchange_snapshot(&entries, &replacement)? { - return admitted_expected.canonical_sha256(); - } - } - bail!("topology projection changed repeatedly during admitted restoration") - } - - pub fn admitted_runtime_projection_is_exact( - &self, - expected: &IdunnExpectedIncarnationRecord, - provider_anchor: &ServiceIdentityTrustAnchor, - activation: &IdunnRuntimeActivationRecord, - lease: Option<&IdunnProcessWriteLeaseRecord>, - ) -> Result { - expected.validate()?; - activation.validate()?; - ensure!( - activation.expected_projection_sha256 == expected.canonical_sha256()?, - "admitted activation does not bind its Expected projection" - ); - if let Some(lease) = lease { - validate_topology_lease(expected, activation, lease)?; - } - if !self.projection_store.exists() { - return Ok(false); - } - let entries = SingleFileMessagePackBackingStore::new(&self.projection_store) - .pull_all_read_only_snapshot()?; - let anchor = runtime_presence_trust_anchor(expected, provider_anchor)?; - let expected_is_exact = match projection_entry( - &entries, - IdunnExpectedIncarnationRecord::TYPE, - &expected.target, - )? { - Some(envelope) => { - ensure!( - envelope.schema_id.as_deref() == Some(IDUNN_EXPECTED_INCARNATION_SCHEMA), - "admitted Expected projection schema is foreign" - ); - ensure!( - IdunnExpectedIncarnationRecord::decode_canonical(&envelope.payload)? - == *expected, - "admitted Expected projection was replaced by another incarnation" - ); - true - } - None => false, - }; - let anchor_is_exact = match projection_entry( - &entries, - GameCultServiceTrustAnchorRecord::TYPE, - &anchor.trust_anchor_id, - )? { - Some(envelope) => { - ensure!( - service_trust_anchor_from_envelope(envelope)? == anchor, - "admitted runtime presence trust anchor was replaced" - ); - true - } - None => false, - }; - let activation_is_exact = match projection_entry( - &entries, - IdunnRuntimeActivationRecord::TYPE, - &expected.target, - )? { - Some(envelope) => { - ensure!( - envelope.schema_id.as_deref() == Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA), - "admitted activation projection schema is foreign" - ); - ensure!( - IdunnRuntimeActivationRecord::decode_canonical(&envelope.payload)? - == *activation, - "admitted activation projection was replaced" - ); - true - } - None => false, - }; - let lease_is_exact = match projection_entry( - &entries, - IdunnProcessWriteLeaseRecord::TYPE, - &expected.target, - )? { - Some(envelope) => { - ensure!( - envelope.schema_id.as_deref() == Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA), - "admitted write-lease projection schema is foreign" - ); - let current = IdunnProcessWriteLeaseRecord::decode_canonical(&envelope.payload)?; - ensure!( - lease == Some(¤t), - "admitted write-lease projection was replaced" - ); - true - } - None => lease.is_none(), - }; - Ok(expected_is_exact && anchor_is_exact && activation_is_exact && lease_is_exact) - } -} - -fn runtime_presence_trust_anchor( - expected: &IdunnExpectedIncarnationRecord, - provider_anchor: &ServiceIdentityTrustAnchor, -) -> Result { - expected.validate()?; - ensure!( - provider_anchor.schema_version - == ::TRUST_ANCHOR_SCHEMA, - "runtime presence trust anchor schema is unsupported" - ); - ensure!( - derive_service_identity_id::(&provider_anchor.public_key)? - == provider_anchor.identity_id - && provider_anchor.identity_id == expected.expected_signer_identity_id, - "runtime presence trust anchor does not bind the Expected signer" - ); - let bound_at_unix_millis: u64 = - chrono::DateTime::parse_from_rfc3339(&provider_anchor.identity_created_at)? - .timestamp_millis() - .try_into() - .context("runtime presence trust anchor creation time predates Unix epoch")?; - let anchor = GameCultServiceTrustAnchorRecord { - schema_version: GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(), - trust_anchor_id: runtime_presence_trust_anchor_id(&expected.target), - service_id: expected.target.clone(), - runtime_id: expected.runtime_id.clone(), - signer_identity_id: provider_anchor.identity_id.clone(), - signer_public_key: provider_anchor.public_key.clone(), - signature_algorithm: "ed25519".into(), - signing_purpose: GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE.into(), - signed_schema: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(), - binding_authority: "root".into(), - bound_at_unix_millis, - expires_at_unix_millis: None, - private_state_exposed: false, - }; - anchor.validate()?; - Ok(anchor) -} - -fn runtime_presence_trust_anchor_id(target: &str) -> String { - format!("root/{target}/runtime-presence") -} - -fn validate_topology_lease( - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - lease: &IdunnProcessWriteLeaseRecord, -) -> Result<()> { - expected.validate()?; - activation.validate()?; - lease.validate()?; - ensure!( - expected.write_lease_required - && lease.target == expected.target - && lease.expected_projection_sha256 == expected.canonical_sha256()? - && lease.plan_id == expected.plan_id - && lease.incarnation_id == expected.incarnation_id - && lease.sealed_release_id == expected.sealed_release_id - && lease.activation_witness_sha256 == activation.canonical_sha256()? - && lease.state_schema_generation - == expected - .state_schema_generation - .as_deref() - .context("write-lease Expected has no state generation")? - && lease.state_contract_sha256 - == expected - .state_contract_sha256 - .as_deref() - .context("write-lease Expected has no state contract")? - && lease.runtime_id == expected.runtime_id - && lease.runtime_instance_id == activation.runtime_instance_id, - "topology write lease does not bind the exact Expected activation" - ); - Ok(()) -} - -fn service_trust_anchor_from_envelope( - envelope: &CultCacheEnvelope, -) -> Result { - ensure!( - envelope.schema_id.as_deref() == Some(GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA), - "service trust-anchor projection schema is foreign" - ); - let anchor: GameCultServiceTrustAnchorRecord = rmp_serde::from_slice(&envelope.payload)?; - ensure!( - rmp_serde::to_vec(&anchor)? == envelope.payload, - "service trust-anchor projection is noncanonical" - ); - anchor.validate()?; - Ok(anchor) -} - -fn replace_records_atomically(path: &Path, replacements: &[CultCacheEnvelope]) -> Result<()> { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - ensure!( - replacements.iter().enumerate().all(|(index, entry)| { - replacements[index + 1..].iter().all(|other| { - (entry.r#type.as_str(), entry.key.as_str()) - != (other.r#type.as_str(), other.key.as_str()) - }) - }), - "atomic projection set contains a duplicate identity" - ); - let store = SingleFileMessagePackBackingStore::new(path); - for _ in 0..8 { - let entries = store.pull_all_read_only_snapshot()?; - let conditions = replacements - .iter() - .map(|replacement| { - Ok(CultCacheExpectedEnvelope { - r#type: replacement.r#type.clone(), - key: replacement.key.clone(), - current: projection_entry(&entries, &replacement.r#type, &replacement.key)? - .cloned(), - }) - }) - .collect::>>()?; - if conditions - .iter() - .zip(replacements) - .all(|(condition, replacement)| condition.current.as_ref() == Some(replacement)) - { - return Ok(()); - } - if store.compare_exchange(&conditions, replacements)? { - return Ok(()); - } - } - bail!("CultCache projection changed too often to publish atomic set") -} - -fn projection_entry<'a>( - entries: &'a [CultCacheEnvelope], - r#type: &str, - key: &str, -) -> Result> { - let mut matches = entries - .iter() - .filter(|entry| entry.r#type == r#type && entry.key == key); - let current = matches.next(); - ensure!( - matches.next().is_none(), - "CultCache projection identity is ambiguous" - ); - Ok(current) -} - -fn insert_exact_process_lease( - path: &Path, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - replacement: CultCacheEnvelope, -) -> Result<()> { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - let store = SingleFileMessagePackBackingStore::new(path); - for _ in 0..8 { - let entries = store.pull_all_read_only_snapshot()?; - let projected_expected = projection_entry( - &entries, - IdunnExpectedIncarnationRecord::TYPE, - &expected.target, - )? - .context("process write lease has no current Expected projection")?; - ensure!( - projected_expected.schema_id.as_deref() == Some(IDUNN_EXPECTED_INCARNATION_SCHEMA) - && IdunnExpectedIncarnationRecord::decode_canonical(&projected_expected.payload)? - == *expected, - "process write lease current Expected projection is substituted" - ); - let projected_activation = projection_entry( - &entries, - IdunnRuntimeActivationRecord::TYPE, - &expected.target, - )? - .context("process write lease has no observed activation projection")?; - ensure!( - projected_activation.schema_id.as_deref() == Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA) - && IdunnRuntimeActivationRecord::decode_canonical(&projected_activation.payload)? - == *activation, - "process write lease observed activation projection is substituted" - ); - let projected_anchor = service_trust_anchor_from_envelope( - projection_entry( - &entries, - GameCultServiceTrustAnchorRecord::TYPE, - &runtime_presence_trust_anchor_id(&expected.target), - )? - .context("process write lease has no runtime presence trust anchor")?, - )?; - ensure!( - projected_anchor.service_id == expected.target - && projected_anchor.runtime_id == expected.runtime_id - && projected_anchor.signer_identity_id == expected.expected_signer_identity_id - && projected_anchor.signing_purpose - == GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE - && projected_anchor.signed_schema == GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, - "process write lease runtime presence trust anchor is substituted" - ); - let current = projection_entry(&entries, &replacement.r#type, &replacement.key)?; - if current == Some(&replacement) { - return Ok(()); - } - ensure!( - current.is_none(), - "refusing to replace a different current process write-lease projection" - ); - let conditions = [ - CultCacheExpectedEnvelope { - r#type: IdunnExpectedIncarnationRecord::TYPE.into(), - key: expected.target.clone(), - current: Some(projected_expected.clone()), - }, - CultCacheExpectedEnvelope { - r#type: IdunnRuntimeActivationRecord::TYPE.into(), - key: expected.target.clone(), - current: Some(projected_activation.clone()), - }, - CultCacheExpectedEnvelope { - r#type: GameCultServiceTrustAnchorRecord::TYPE.into(), - key: runtime_presence_trust_anchor_id(&expected.target), - current: projection_entry( - &entries, - GameCultServiceTrustAnchorRecord::TYPE, - &runtime_presence_trust_anchor_id(&expected.target), - )? - .cloned(), - }, - CultCacheExpectedEnvelope { - r#type: replacement.r#type.clone(), - key: replacement.key.clone(), - current: None, - }, - ]; - if store.compare_exchange(&conditions, std::slice::from_ref(&replacement))? { - return Ok(()); - } - } - bail!("CultCache projection changed too often to publish exact record") -} - -impl TopologyPort for CultCacheTopologyDriver { - fn publish_expected( - &self, - expected: &IdunnExpectedIncarnationRecord, - provider_anchor: &ServiceIdentityTrustAnchor, - ) -> Result { - expected.validate()?; - let anchor = runtime_presence_trust_anchor(expected, provider_anchor)?; - replace_records_atomically( - &self.projection_store, - &[ - CultCacheEnvelope { - key: expected.target.clone(), - r#type: IdunnExpectedIncarnationRecord::TYPE.into(), - payload: expected.canonical_bytes()?, - stored_at: chrono::Utc::now().to_rfc3339(), - schema_id: Some(IDUNN_EXPECTED_INCARNATION_SCHEMA.into()), - }, - CultCacheEnvelope { - key: anchor.trust_anchor_id.clone(), - r#type: GameCultServiceTrustAnchorRecord::TYPE.into(), - payload: rmp_serde::to_vec(&anchor)?, - stored_at: rfc3339_millis(anchor.bound_at_unix_millis)?, - schema_id: Some(GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into()), - }, - ], - )?; - expected.canonical_sha256() - } - - fn withdraw_expected( - &self, - expected: &IdunnExpectedIncarnationRecord, - provider_anchor: &ServiceIdentityTrustAnchor, - activation: Option<&IdunnRuntimeActivationRecord>, - lease: Option<&IdunnProcessWriteLeaseRecord>, - ) -> Result<()> { - expected.validate()?; - let exact_anchor = runtime_presence_trust_anchor(expected, provider_anchor)?; - if let Some(activation) = activation { - activation.validate()?; - ensure!( - activation.expected_projection_sha256 == expected.canonical_sha256()? - && activation.runtime_id == expected.runtime_id, - "withdrawn activation does not bind the exact Expected projection" - ); - } - if let Some(lease) = lease { - validate_topology_lease( - expected, - activation.context("withdrawn lease has no exact activation")?, - lease, - )?; - } - if !self.projection_store.exists() { - return Ok(()); - } - let store = SingleFileMessagePackBackingStore::new(&self.projection_store); - for _ in 0..8 { - let entries = store.pull_all_read_only_snapshot()?; - let mut found_expected = false; - let mut found_anchor = false; - let mut found_activation = false; - let mut found_lease = false; - let mut retained = Vec::with_capacity(entries.len()); - for envelope in &entries { - if envelope.r#type == GameCultServiceTrustAnchorRecord::TYPE - && envelope.key == exact_anchor.trust_anchor_id - { - ensure!( - !found_anchor - && service_trust_anchor_from_envelope(envelope)? == exact_anchor, - "refusing to withdraw a substituted runtime presence trust anchor" - ); - found_anchor = true; - continue; - } - if envelope.key != expected.target { - retained.push(envelope.clone()); - continue; - } - if envelope.r#type == IdunnExpectedIncarnationRecord::TYPE { - ensure!( - !found_expected - && envelope.schema_id.as_deref() - == Some(IDUNN_EXPECTED_INCARNATION_SCHEMA) - && IdunnExpectedIncarnationRecord::decode_canonical(&envelope.payload)? - == *expected, - "refusing to withdraw a substituted Expected projection" - ); - found_expected = true; - continue; - } - if envelope.r#type == IdunnRuntimeActivationRecord::TYPE { - let current = - IdunnRuntimeActivationRecord::decode_canonical(&envelope.payload)?; - ensure!( - !found_activation - && envelope.schema_id.as_deref() - == Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA) - && activation == Some(¤t), - "refusing to withdraw a substituted runtime activation" - ); - found_activation = true; - continue; - } - if envelope.r#type == IdunnProcessWriteLeaseRecord::TYPE { - let current = - IdunnProcessWriteLeaseRecord::decode_canonical(&envelope.payload)?; - ensure!( - !found_lease - && envelope.schema_id.as_deref() - == Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA) - && lease == Some(¤t), - "refusing to withdraw a substituted process write lease" - ); - found_lease = true; - continue; - } - retained.push(envelope.clone()); - } - if !found_expected && !found_anchor && !found_activation && !found_lease { - return Ok(()); - } - if store.compare_exchange_snapshot(&entries, &retained)? { - return Ok(()); - } - } - bail!("Expected projection changed repeatedly while withdrawing it") - } - - fn publish_observed_activation( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - observation: &WorkloadObservation, - ) -> Result { - expected.validate()?; - activation.validate()?; - ensure!( - activation.expected_projection_sha256 == expected.canonical_sha256()? - && activation.runtime_instance_id == observation.runtime_instance_id - && observation.executable_sha256 == expected.artifact_sha256, - "observed activation does not name the Expected native process" - ); - upsert_record( - &self.projection_store, - CultCacheEnvelope { - key: expected.target.clone(), - r#type: IdunnRuntimeActivationRecord::TYPE.into(), - payload: activation.canonical_bytes()?, - stored_at: rfc3339_millis(activation.issued_at_unix_millis)?, - schema_id: Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA.into()), - }, - )?; - activation.canonical_sha256() - } - - fn publish_process_write_lease( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - lease: &IdunnProcessWriteLeaseRecord, - ) -> Result { - validate_topology_lease(expected, activation, lease)?; - insert_exact_process_lease( - &self.projection_store, - expected, - activation, - CultCacheEnvelope { - key: expected.target.clone(), - r#type: IdunnProcessWriteLeaseRecord::TYPE.into(), - payload: lease.canonical_bytes()?, - stored_at: rfc3339_millis(lease.issued_at_unix_millis)?, - schema_id: Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into()), - }, - )?; - lease.canonical_sha256() - } - - fn withdraw_process_write_lease( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - lease: Option<&IdunnProcessWriteLeaseRecord>, - ) -> Result<()> { - expected.validate()?; - activation.validate()?; - if let Some(lease) = lease { - validate_topology_lease(expected, activation, lease)?; - } - if !self.projection_store.exists() { - return Ok(()); - } - let store = SingleFileMessagePackBackingStore::new(&self.projection_store); - for _ in 0..8 { - let entries = store.pull_all_read_only_snapshot()?; - let mut found = false; - let mut retained = Vec::with_capacity(entries.len()); - for envelope in &entries { - if envelope.key != expected.target - || envelope.r#type != IdunnProcessWriteLeaseRecord::TYPE - { - retained.push(envelope.clone()); - continue; - } - let current = IdunnProcessWriteLeaseRecord::decode_canonical(&envelope.payload)?; - ensure!( - !found - && envelope.schema_id.as_deref() == Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA) - && lease == Some(¤t), - "refusing to withdraw an unexpected process write-lease projection" - ); - found = true; - } - if !found { - return Ok(()); - } - if store.compare_exchange_snapshot(&entries, &retained)? { - return Ok(()); - } - } - bail!("process write-lease projection changed repeatedly while withdrawing it") - } - - fn receive(&self, target: &str) -> Result> { - require_driver_id(target, "topology target")?; - if !self.correlation_store.exists() { - return Ok(None); - } - let entries = SingleFileMessagePackBackingStore::new(&self.correlation_store) - .pull_all_read_only_snapshot()?; - let mut matches = entries.iter().filter(|envelope| { - envelope.r#type == OdinRuntimeTopologyCorrelationRecord::TYPE && envelope.key == target - }); - let Some(envelope) = matches.next() else { - return Ok(None); - }; - ensure!( - matches.next().is_none(), - "Odin topology correlation is ambiguous" - ); - ensure!( - envelope.schema_id.as_deref() == Some(ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA), - "Odin topology correlation schema is foreign" - ); - Ok(Some(ReceivedOdinTopologyCorrelation { - target: target.to_owned(), - canonical_bytes: envelope.payload.clone(), - })) - } -} - -/// nginx owns proxy mechanics. Idunn supplies one exact backend membership, -/// validates the complete nginx configuration, and reloads it. Configuration -/// bytes are actuator state, not proof that the selected runtime answered on -/// the stable route; the control plane admits that proof separately. -pub struct NginxRouteDriver { - pub binding: RouteBinding, - pub nginx_program: PathBuf, - pub systemd_run_program: PathBuf, - pub systemctl_program: PathBuf, - pub preflight_root: PathBuf, -} - -impl NginxRouteDriver { - pub fn new(binding: RouteBinding) -> Self { - Self { - binding, - nginx_program: PathBuf::from("/usr/sbin/nginx"), - systemd_run_program: PathBuf::from("/usr/bin/systemd-run"), - systemctl_program: PathBuf::from("/usr/bin/systemctl"), - preflight_root: PathBuf::from("/run/idunn/route-preflight"), - } - } - - fn command(&self, program: &Path, args: I) -> Result - where - I: IntoIterator, - S: AsRef, - { - ensure!( - program.is_absolute(), - "route actuator program is not absolute" - ); - let output = Command::new(program) - .args(args) - .stdin(Stdio::null()) - .env_clear() - .env("LANG", "C.UTF-8") - .output() - .with_context(|| format!("starting route actuator {}", program.display()))?; - if !output.status.success() { - bail!( - "route actuator {} exited with {}: {}", - program.display(), - output.status, - String::from_utf8_lossy(&output.stderr).trim() - ); - } - Ok(output) - } - - fn render(&self, expected: &IdunnExpectedIncarnationRecord) -> Result> { - expected.validate()?; - let expected_projection_sha256 = expected.canonical_sha256()?; - let route = expected - .route - .as_ref() - .context("expected incarnation has no route")?; - ensure!( - route.route_id == self.binding.route_id - && route.stable_endpoint == self.binding.stable_endpoint, - "route driver binding differs from Expected" - ); - let endpoint_prefix = match (self.binding.driver, route.transport.as_str()) { - (RouteDriver::NginxStreamTcp, "http") => "http://", - (RouteDriver::NginxStreamTcp, "tcp") => "tcp://", - (RouteDriver::NginxStreamUdp, "rudp") => "rudp://", - _ => bail!("route driver cannot carry the Expected transport"), - }; - let (candidate_host, candidate_port) = - endpoint_host_port(&route.candidate_endpoint, endpoint_prefix)?; - ensure!( - candidate_host == self.binding.private_host - && (self.binding.private_port_start..=self.binding.private_port_end) - .contains(&candidate_port), - "Expected candidate endpoint is outside the route binding" - ); - let upstream = nginx_identifier(&self.binding.route_id)?; - let rendered = match self.binding.driver { - RouteDriver::NginxStreamTcp => { - let (stable_host, stable_port) = - endpoint_host_port(&route.stable_endpoint, endpoint_prefix)?; - format!( - "# Idunn Expected {expected_projection_sha256}\nupstream {upstream} {{\n server {candidate_host}:{candidate_port};\n}}\nserver {{\n listen {stable_host}:{stable_port};\n proxy_pass {upstream};\n}}\n" - ) - } - RouteDriver::NginxStreamUdp => { - let (stable_host, stable_port) = - endpoint_host_port(&route.stable_endpoint, "rudp://")?; - format!( - "# Idunn Expected {expected_projection_sha256}\nupstream {upstream} {{\n server {candidate_host}:{candidate_port};\n}}\nserver {{\n listen {stable_host}:{stable_port} udp reuseport;\n proxy_pass {upstream};\n}}\n" - ) - } - }; - Ok(rendered.into_bytes()) - } - - fn current_configuration(&self) -> Result>> { - Ok(match fs::read(&self.binding.config_path) { - Ok(bytes) => Some(bytes), - Err(error) if error.kind() == ErrorKind::NotFound => None, - Err(error) => return Err(error).context("reading route fragment"), - }) - } - - fn write_fragment(&self, content: Option<&[u8]>) -> Result<()> { - match content { - Some(bytes) => atomic_replace(&self.binding.config_path, bytes), - None => match fs::remove_file(&self.binding.config_path) { - Ok(()) => sync_parent_directory(&self.binding.config_path), - Err(error) if error.kind() == ErrorKind::NotFound => Ok(()), - Err(error) => Err(error).context("removing route fragment"), - }, - } - } - - fn reload(&self) -> Result<()> { - self.command(&self.nginx_program, [OsString::from("-t")])?; - self.command( - &self.systemctl_program, - [ - OsString::from("reload"), - OsString::from(&self.binding.reload_unit), - ], - )?; - Ok(()) - } - - fn validate_candidate_in_private_mount(&self, rendered: &[u8]) -> Result<()> { - ensure_route_preflight_root(&self.preflight_root)?; - let route = nginx_identifier(&self.binding.route_id)?; - let nonce = Uuid::new_v4(); - let candidate = self - .preflight_root - .join(format!("{route}-{nonce}.candidate")); - write_root_owned_file(&candidate, rendered, 0o400)?; - let unit = format!("idunn-nginx-preflight-{nonce}"); - let validation = self.command( - &self.systemd_run_program, - [ - OsString::from("--wait"), - OsString::from("--collect"), - OsString::from("--quiet"), - OsString::from(format!("--unit={unit}")), - OsString::from("--property=Type=exec"), - OsString::from("--property=PrivateMounts=yes"), - systemd_read_only_bind_property(&candidate, &self.binding.config_path)?, - OsString::from("--"), - self.nginx_program.clone().into_os_string(), - OsString::from("-t"), - ], - ); - let cleanup = remove_exact_root_owned_file(&candidate, 0o400); - match (validation, cleanup) { - (Ok(_), Ok(())) => Ok(()), - (Err(validation), Ok(())) => { - Err(validation).context("candidate route is invalid in a private mount namespace") - } - (Ok(_), Err(cleanup)) => { - Err(cleanup).context("deleting route preflight material") - } - (Err(validation), Err(cleanup)) => Err(validation).context(format!( - "candidate route is invalid; deleting its private preflight material also failed: {cleanup:#}" - )), - } - } - - fn restore(&self, prior: Option<&[u8]>) -> Result<()> { - self.write_fragment(prior)?; - self.reload() - } - - fn fail_after_rollback( - &self, - prior: Option<&[u8]>, - failure: anyhow::Error, - context: &str, - ) -> Result { - match self.restore(prior) { - Ok(()) => Err(failure).context(context.to_owned()), - Err(rollback) => Err(failure).context(format!( - "{context}; route rollback also failed: {rollback:#}" - )), - } - } - - pub fn preflight( - &self, - expected: &IdunnExpectedIncarnationRecord, - runtime_instance_id: &str, - incumbent: Option<&RouteObservation>, - ) -> Result { - let rendered = self.render(expected)?; - ensure!(!rendered.is_empty(), "candidate route rendered empty"); - let current = self.current_configuration()?; - let incumbent_membership_sha256 = current.as_ref().map(|bytes| sha256_id(bytes)); - match incumbent { - Some(incumbent) => ensure!( - incumbent.route_id == self.binding.route_id - && Some(incumbent.membership_sha256.as_str()) - == incumbent_membership_sha256.as_deref(), - "route preflight baseline differs from the admitted incumbent" - ), - None => ensure!( - incumbent_membership_sha256.is_none(), - "route preflight found an unadmitted incumbent" - ), - } - self.validate_candidate_in_private_mount(&rendered)?; - let after = self.current_configuration()?; - ensure!( - after == current, - "nginx route baseline changed during candidate validation" - ); - let receipt = RoutePreflightReceipt { - route_id: self.binding.route_id.clone(), - candidate_runtime_instance_id: runtime_instance_id.to_owned(), - candidate_membership_sha256: sha256_id(&rendered), - incumbent_runtime_instance_id: incumbent - .map(|observation| observation.runtime_instance_id.clone()), - incumbent_membership_sha256, - incumbent_configuration: current, - }; - receipt.validate()?; - Ok(receipt) - } - - /// Install the candidate route membership and require nginx to accept the - /// complete configuration. Success is not route admission: callers must - /// still obtain a fresh signed runtime observation through the stable - /// listener. - pub fn install( - &self, - expected: &IdunnExpectedIncarnationRecord, - runtime_instance_id: &str, - preflight: &RoutePreflightReceipt, - rollback_allowed: bool, - ) -> Result { - preflight.validate()?; - let rendered = self.render(expected)?; - ensure!( - preflight.route_id == self.binding.route_id - && preflight.candidate_runtime_instance_id == runtime_instance_id - && preflight.candidate_membership_sha256 == sha256_id(&rendered), - "route preflight does not authorize this candidate membership" - ); - let prior = self.current_configuration()?; - let prior_sha256 = prior.as_ref().map(|bytes| sha256_id(bytes)); - let candidate_already_written = prior.as_deref() == Some(rendered.as_slice()); - ensure!( - candidate_already_written - || (prior == preflight.incumbent_configuration - && prior_sha256 == preflight.incumbent_membership_sha256), - "route baseline changed after preflight" - ); - if !candidate_already_written { - atomic_replace(&self.binding.config_path, &rendered)?; - } - if let Err(error) = self.reload() { - if rollback_allowed { - return self.fail_after_rollback( - preflight.incumbent_configuration.as_deref(), - error, - "candidate route validation or reload failed", - ); - } - return Err(error).context( - "candidate route reload failed after incumbent route authority was fenced; candidate fragment retained for retry", - ); - } - ensure!( - self.current_configuration()?.as_deref() == Some(rendered.as_slice()), - "candidate route fragment changed during reload" - ); - Ok(sha256_id(&rendered)) - } - - pub fn observe_membership( - &self, - expected: &IdunnExpectedIncarnationRecord, - membership_sha256: &str, - ) -> Result { - let rendered = self.render(expected)?; - ensure!( - membership_sha256 == sha256_id(&rendered), - "route observation does not describe the expected membership" - ); - Ok(self.current_configuration()?.as_deref() == Some(rendered.as_slice())) - } - - /// Restore the exact membership owned by an admitted generation. Any - /// different fragment is drift, not a rollback baseline, so it is never - /// restored after a failed reload. A failed reload removes the newly - /// written fragment so the next continuity pass cannot mistake disk bytes - /// for an adopted route. The caller must still challenge the stable - /// listener to prove that nginx workers adopted this membership. - pub fn restore_admitted_membership( - &self, - expected: &IdunnExpectedIncarnationRecord, - membership_sha256: &str, - ) -> Result<()> { - let rendered = self.render(expected)?; - ensure!( - membership_sha256 == sha256_id(&rendered), - "admitted route receipt does not describe the expected membership" - ); - self.validate_candidate_in_private_mount(&rendered)?; - if self.current_configuration()?.as_deref() != Some(rendered.as_slice()) { - atomic_replace(&self.binding.config_path, &rendered)?; - } - if let Err(reload) = self.reload() { - return match self.write_fragment(None) { - Ok(()) => Err(reload).context("reloading the exact admitted route membership"), - Err(cleanup) => Err(reload).context(format!( - "reloading the exact admitted route membership; removing its unproved fragment also failed: {cleanup:#}" - )), - }; - } - ensure!( - self.current_configuration()?.as_deref() == Some(rendered.as_slice()), - "admitted route fragment changed during restoration" - ); - Ok(()) - } - - /// Ask the stable listener for one freshly minted provider-owned presence - /// statement. This method validates the CultNet wire exchange and exact - /// document selection only; Idunn's control plane authenticates and - /// correlates the signed payload against current authority. - pub fn request_runtime_presence( - &self, - expected: &IdunnExpectedIncarnationRecord, - message_id: &str, - ) -> Result { - let route = expected - .route - .as_ref() - .context("route challenge has no Expected route")?; - ensure!( - route.route_id == self.binding.route_id - && route.stable_endpoint == self.binding.stable_endpoint, - "route challenge binding differs from Expected" - ); - self.request_runtime_presence_at(expected, message_id, &route.stable_endpoint) - } - - /// The bootstrap exception for the first managed Odin observes Warming on - /// the exact candidate endpoint. It does not install or admit a route. - pub fn request_candidate_runtime_presence( - &self, - expected: &IdunnExpectedIncarnationRecord, - message_id: &str, - ) -> Result { - let route = expected - .route - .as_ref() - .context("candidate challenge has no Expected route")?; - ensure!( - route.route_id == self.binding.route_id, - "candidate challenge binding differs from Expected" - ); - self.render(expected)?; - self.request_runtime_presence_at(expected, message_id, &route.candidate_endpoint) - } - - fn request_runtime_presence_at( - &self, - expected: &IdunnExpectedIncarnationRecord, - message_id: &str, - endpoint: &str, - ) -> Result { - expected.validate()?; - require_driver_id(message_id, "route challenge message")?; - let route = expected - .route - .as_ref() - .context("route challenge has no Expected route")?; - let request = CultNetMessage::SnapshotRequest { - message_id: message_id.to_owned(), - schema_ids: Some(vec![GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into()]), - record_keys: Some(vec![expected.target.clone()]), - }; - let endpoint_prefix = match route.transport.as_str() { - "http" => "http://", - "tcp" => "tcp://", - "rudp" => "rudp://", - _ => bail!("route challenge transport is unsupported"), - }; - let (host, port) = endpoint_host_port(endpoint, endpoint_prefix)?; - let target = SocketAddr::new( - host.parse() - .context("route challenge endpoint host is not an IP address")?, - port, - ); - let response = match route.transport.as_str() { - "http" => { - let payload = - encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?; - let response = request_http_snapshot(target, &payload)?; - decode_cultnet_message_from_slice(&response, CultNetWireContract::CultNetSchemaV0)? - } - "tcp" => { - let payload = - encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?; - let response = request_tcp_snapshot(target, &payload)?; - decode_cultnet_message_from_slice(&response, CultNetWireContract::CultNetSchemaV0)? - } - "rudp" => request_raw_snapshot_from_rudp_catalog(CultMeshRudpSnapshotOptions { - target, - runtime_id: "idunn-route-observer".into(), - message_id: message_id.to_owned(), - schema_ids: Some(vec![GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into()]), - record_keys: Some(vec![expected.target.clone()]), - ..CultMeshRudpSnapshotOptions::default() - })?, - _ => bail!("route challenge transport is unsupported"), - }; - exact_route_snapshot_response(response, message_id, &expected.target) - } - - /// Restore the exact preflight baseline. This may only replace the exact - /// candidate authorized by the receipt; an unrelated writer is never - /// overwritten as a side effect of rollback. - pub fn rollback( - &self, - expected: &IdunnExpectedIncarnationRecord, - runtime_instance_id: &str, - preflight: &RoutePreflightReceipt, - ) -> Result<()> { - preflight.validate()?; - let rendered = self.render(expected)?; - ensure!( - preflight.route_id == self.binding.route_id - && preflight.candidate_runtime_instance_id == runtime_instance_id - && preflight.candidate_membership_sha256 == sha256_id(&rendered), - "route preflight does not authorize rollback of this candidate membership" - ); - ensure!( - self.current_configuration()?.as_deref() == Some(rendered.as_slice()), - "candidate route changed before rollback" - ); - self.restore(preflight.incumbent_configuration.as_deref()) - } -} - -fn request_tcp_snapshot(target: SocketAddr, payload: &[u8]) -> Result> { - let mut stream = TcpStream::connect_timeout(&target, ROUTE_SNAPSHOT_TIMEOUT) - .with_context(|| format!("connecting stable CultNet TCP route {target}"))?; - stream.set_read_timeout(Some(ROUTE_SNAPSHOT_TIMEOUT))?; - stream.set_write_timeout(Some(ROUTE_SNAPSHOT_TIMEOUT))?; - stream.write_all(&encode_frame(payload)?)?; - stream.flush()?; - - let mut header = [0_u8; 4]; - stream - .read_exact(&mut header) - .context("reading stable CultNet TCP response frame")?; - let length = u32::from_be_bytes(header) as usize; - ensure!( - (1..=ROUTE_SNAPSHOT_MAX_BYTES).contains(&length), - "stable CultNet TCP response exceeds the route observation bound" - ); - let mut response = vec![0_u8; length]; - stream - .read_exact(&mut response) - .context("reading stable CultNet TCP response payload")?; - Ok(response) -} - -fn request_http_snapshot(target: SocketAddr, payload: &[u8]) -> Result> { - let mut stream = TcpStream::connect_timeout(&target, ROUTE_SNAPSHOT_TIMEOUT) - .with_context(|| format!("connecting stable CultNet HTTP route {target}"))?; - stream.set_read_timeout(Some(ROUTE_SNAPSHOT_TIMEOUT))?; - stream.set_write_timeout(Some(ROUTE_SNAPSHOT_TIMEOUT))?; - let head = format!( - "POST {ROUTE_HTTP_SNAPSHOT_PATH} HTTP/1.1\r\nHost: {target}\r\nContent-Type: application/msgpack\r\nAccept: application/msgpack\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", - payload.len() - ); - stream.write_all(head.as_bytes())?; - stream.write_all(payload)?; - stream.flush()?; - - let maximum = ROUTE_HTTP_MAX_HEADER_BYTES - .checked_add(ROUTE_SNAPSHOT_MAX_BYTES) - .context("route HTTP response bound overflow")?; - let mut response = Vec::new(); - (&mut stream) - .take((maximum + 1) as u64) - .read_to_end(&mut response) - .context("reading stable CultNet HTTP response")?; - ensure!( - response.len() <= maximum, - "stable CultNet HTTP response exceeds the route observation bound" - ); - let header_end = response - .windows(4) - .position(|window| window == b"\r\n\r\n") - .map(|index| index + 4) - .context("stable CultNet HTTP response has no header boundary")?; - ensure!( - header_end <= ROUTE_HTTP_MAX_HEADER_BYTES, - "stable CultNet HTTP response headers exceed their bound" - ); - let headers = std::str::from_utf8(&response[..header_end]) - .context("stable CultNet HTTP response headers are not UTF-8")?; - let mut lines = headers.split("\r\n"); - let status = lines - .next() - .context("stable CultNet HTTP response has no status")?; - ensure!( - matches!(status, "HTTP/1.1 200 OK" | "HTTP/1.0 200 OK"), - "stable CultNet HTTP route rejected the snapshot challenge: {status}" - ); - let mut content_length = None; - for line in lines.filter(|line| !line.is_empty()) { - let (name, value) = line - .split_once(':') - .context("stable CultNet HTTP response contains a malformed header")?; - if name.eq_ignore_ascii_case("transfer-encoding") { - bail!("stable CultNet HTTP response uses unsupported transfer encoding"); - } - if name.eq_ignore_ascii_case("content-length") { - ensure!( - content_length.is_none(), - "stable CultNet HTTP response repeats Content-Length" - ); - content_length = Some( - value - .trim() - .parse::() - .context("stable CultNet HTTP Content-Length is invalid")?, - ); - } - } - let content_length = - content_length.context("stable CultNet HTTP response has no Content-Length")?; - ensure!( - content_length <= ROUTE_SNAPSHOT_MAX_BYTES - && response.len().saturating_sub(header_end) == content_length, - "stable CultNet HTTP response body differs from its bounded Content-Length" - ); - Ok(response[header_end..].to_vec()) -} - -fn exact_route_snapshot_response( - response: CultNetMessage, - message_id: &str, - target: &str, -) -> Result { - let CultNetMessage::SnapshotResponseRaw { - message_id: response_id, - documents, - } = response - else { - bail!("stable route returned a non-raw snapshot response") - }; - ensure!( - response_id == message_id, - "stable route snapshot response belongs to another challenge" - ); - ensure!( - documents.len() == 1, - "stable route snapshot response is not the exact singleton presence document" - ); - let document = documents - .into_iter() - .next() - .expect("singleton response length was checked"); - ensure!( - document.schema_id == GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA - && document.record_key == target - && document.payload_encoding == CultNetRawPayloadEncoding::Messagepack, - "stable route substituted the runtime presence document" - ); - ensure!( - !document.payload.is_empty() && document.payload.len() <= ROUTE_SNAPSHOT_MAX_BYTES, - "stable route presence payload is empty or exceeds its bound" - ); - Ok(RouteSnapshotResponse { - message_id: response_id, - canonical_presence: document.payload, - }) -} - -fn release_artifact<'a>( - declaration: &'a TargetDeclaration, - artifact_id: &str, -) -> Result<&'a ArtifactOutput> { - declaration - .artifacts - .iter() - .find(|artifact| artifact.id == artifact_id) - .with_context(|| format!("target declares no artifact {artifact_id}")) -} - -fn write_immutable_record(path: &Path, envelope: CultCacheEnvelope) -> Result<()> { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - let mut store = SingleFileMessagePackBackingStore::new(path); - match store.pull_all_read_only_snapshot()?.as_slice() { - [] => store.push(&envelope), - [current] if current == &envelope => Ok(()), - _ => bail!( - "immutable runtime document {} already differs", - path.display() - ), - } -} - -fn upsert_record(path: &Path, replacement: CultCacheEnvelope) -> Result<()> { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - let store = SingleFileMessagePackBackingStore::new(path); - for _ in 0..8 { - let entries = store.pull_all_read_only_snapshot()?; - let mut matches = entries - .iter() - .filter(|entry| entry.r#type == replacement.r#type && entry.key == replacement.key); - let current = matches.next().cloned(); - ensure!( - matches.next().is_none(), - "CultCache projection identity is ambiguous" - ); - if current.as_ref() == Some(&replacement) { - return Ok(()); - } - if store.compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: replacement.r#type.clone(), - key: replacement.key.clone(), - current, - }], - std::slice::from_ref(&replacement), - )? { - return Ok(()); - } - } - bail!("CultCache projection changed too often to publish") -} - -fn rfc3339_millis(millis: u64) -> Result { - Ok( - chrono::DateTime::from_timestamp_millis(i64::try_from(millis)?) - .context("runtime timestamp is out of range")? - .to_rfc3339(), - ) -} - -#[cfg(unix)] -fn validate_frozen_source_store(store: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - ensure!(store.is_absolute(), "frozen source store is not absolute"); - let canonical_store = store - .canonicalize() - .with_context(|| format!("resolving frozen source store {}", store.display()))?; - ensure!( - canonical_store == store, - "frozen source store traverses a symlink or noncanonical path" - ); - let metadata = fs::symlink_metadata(store)?; - ensure!( - metadata.is_dir() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.permissions().mode() & 0o022 == 0, - "frozen source store is not root-owned and nonwritable" - ); - Ok(()) -} - -#[cfg(not(unix))] -fn validate_frozen_source_store(_store: &Path) -> Result<()> { - bail!("frozen source materialization requires a Unix actuator") -} - -#[cfg(unix)] -fn prepare_frozen_transaction_root(store: &Path, transaction_id: &str) -> Result { - use std::os::unix::fs::PermissionsExt; - - require_driver_id(transaction_id, "source transaction")?; - validate_frozen_source_store(store)?; - let transaction_root = store.join(transaction_id); - if transaction_root.exists() { - remove_frozen_transaction_root(store, transaction_id)?; - } - fs::create_dir(&transaction_root)?; - fs::set_permissions(&transaction_root, fs::Permissions::from_mode(0o700))?; - Ok(transaction_root) -} - -#[cfg(not(unix))] -fn prepare_frozen_transaction_root(_store: &Path, _transaction_id: &str) -> Result { - bail!("frozen source materialization requires a Unix actuator") -} - -#[cfg(unix)] -fn remove_frozen_transaction_root(store: &Path, transaction_id: &str) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - require_driver_id(transaction_id, "source transaction")?; - validate_frozen_source_store(store)?; - let transaction_root = store.join(transaction_id); - let metadata = fs::symlink_metadata(&transaction_root)?; - ensure!( - metadata.is_dir() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.permissions().mode() & 0o022 == 0, - "frozen source transaction root is not Idunn-owned" - ); - fs::set_permissions(&transaction_root, fs::Permissions::from_mode(0o700))?; - fs::remove_dir_all(&transaction_root).with_context(|| { - format!( - "removing exact frozen source transaction {}", - transaction_root.display() - ) - }) -} - -#[cfg(not(unix))] -fn remove_frozen_transaction_root(_store: &Path, _transaction_id: &str) -> Result<()> { - bail!("frozen source cleanup requires a Unix actuator") -} - -#[cfg(unix)] -fn prepare_frozen_source_destination(destination: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - ensure!( - unsafe { libc::geteuid() } == 0, - "frozen source materialization requires root Idunn" - ); - ensure!( - destination.is_absolute(), - "frozen source destination is not absolute" - ); - let parent = destination - .parent() - .context("frozen source destination has no parent")?; - ensure!(destination != parent, "frozen source destination is broad"); - let canonical_parent = parent - .canonicalize() - .with_context(|| format!("resolving frozen source parent {}", parent.display()))?; - ensure!( - canonical_parent == parent, - "frozen source parent traverses a symlink or noncanonical path" - ); - let parent_metadata = fs::symlink_metadata(parent)?; - ensure!( - parent_metadata.is_dir() - && !parent_metadata.file_type().is_symlink() - && parent_metadata.uid() == 0 - && parent_metadata.permissions().mode() & 0o022 == 0, - "frozen source parent is not root-owned and nonwritable" - ); - if destination.exists() { - remove_frozen_source_destination(destination)?; - } - fs::create_dir(destination) - .with_context(|| format!("creating frozen source {}", destination.display()))?; - fs::set_permissions(destination, fs::Permissions::from_mode(0o700))?; - Ok(()) -} - -#[cfg(not(unix))] -fn prepare_frozen_source_destination(_destination: &Path) -> Result<()> { - bail!("frozen source materialization requires a Unix actuator") -} - -#[cfg(unix)] -fn remove_frozen_source_destination(destination: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - ensure!( - destination.is_absolute(), - "frozen source destination is not absolute" - ); - let parent = destination - .parent() - .context("frozen source destination has no parent")?; - ensure!(destination != parent, "frozen source destination is broad"); - let parent_metadata = fs::symlink_metadata(parent)?; - let metadata = fs::symlink_metadata(destination)?; - ensure!( - parent_metadata.is_dir() - && !parent_metadata.file_type().is_symlink() - && parent_metadata.uid() == 0 - && parent_metadata.permissions().mode() & 0o022 == 0, - "frozen source parent is not root-owned and nonwritable" - ); - ensure!( - metadata.is_dir() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.permissions().mode() & 0o022 == 0, - "existing frozen source is not an Idunn-owned directory" - ); - fs::remove_dir_all(destination) - .with_context(|| format!("removing exact frozen source {}", destination.display())) -} - -#[cfg(not(unix))] -fn remove_frozen_source_destination(_destination: &Path) -> Result<()> { - bail!("frozen source materialization requires a Unix actuator") -} - -#[cfg(unix)] -fn harden_frozen_source(root: &Path) -> Result<()> { - harden_frozen_source_tree(root, root) -} - -#[cfg(unix)] -fn harden_frozen_source_tree(root: &Path, current: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let metadata = fs::symlink_metadata(current)?; - ensure!(metadata.uid() == 0, "frozen source entry is not root-owned"); - ensure!( - current == root || current.file_name() != Some(OsStr::new(".git")), - "frozen source contains forbidden .git metadata" - ); - if metadata.is_dir() { - let mut entries = fs::read_dir(current)?.collect::>>()?; - entries.sort_by_key(|entry| entry.file_name()); - for entry in entries { - harden_frozen_source_tree(root, &entry.path())?; - } - fs::set_permissions(current, fs::Permissions::from_mode(0o555))?; - } else if metadata.is_file() { - let mode = if metadata.permissions().mode() & 0o111 == 0 { - 0o444 - } else { - 0o555 - }; - fs::set_permissions(current, fs::Permissions::from_mode(mode))?; - } else if metadata.file_type().is_symlink() { - validate_frozen_source_symlink(root, current)?; - } else { - bail!("frozen source contains a special filesystem entry") - } - Ok(()) -} - -#[cfg(unix)] -fn validate_frozen_source_symlink(root: &Path, path: &Path) -> Result<()> { - let target = fs::read_link(path)?; - ensure!(target.is_relative(), "frozen source symlink is absolute"); - let parent = path - .parent() - .context("frozen source symlink has no parent")?; - let mut components = parent - .strip_prefix(root)? - .components() - .filter_map(|component| match component { - std::path::Component::Normal(value) => Some(value.to_os_string()), - _ => None, - }) - .collect::>(); - for component in target.components() { - match component { - std::path::Component::CurDir => {} - std::path::Component::Normal(value) => components.push(value.to_os_string()), - std::path::Component::ParentDir => { - ensure!( - components.pop().is_some(), - "frozen source symlink escapes its root" - ); - } - std::path::Component::RootDir | std::path::Component::Prefix(_) => { - bail!("frozen source symlink is absolute") - } - } - } - Ok(()) -} - -#[cfg(not(unix))] -fn harden_frozen_source(_root: &Path) -> Result<()> { - bail!("frozen source materialization requires Unix permissions") -} - -#[cfg(unix)] -fn validate_frozen_source(root: &Path) -> Result<()> { - validate_frozen_source_tree(root, root) -} - -#[cfg(unix)] -fn validate_frozen_source_tree(root: &Path, current: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let metadata = fs::symlink_metadata(current)?; - ensure!(metadata.uid() == 0, "frozen source entry is not root-owned"); - ensure!( - current == root || current.file_name() != Some(OsStr::new(".git")), - "frozen source contains forbidden .git metadata" - ); - if metadata.is_dir() { - ensure!( - metadata.permissions().mode() & 0o777 == 0o555, - "frozen source directory is not 0555" - ); - let mut entries = fs::read_dir(current)?.collect::>>()?; - entries.sort_by_key(|entry| entry.file_name()); - for entry in entries { - validate_frozen_source_tree(root, &entry.path())?; - } - } else if metadata.is_file() { - ensure!( - matches!(metadata.permissions().mode() & 0o777, 0o444 | 0o555), - "frozen source file has a noncanonical mode" - ); - } else if metadata.file_type().is_symlink() { - validate_frozen_source_symlink(root, current)?; - } else { - bail!("frozen source contains a special filesystem entry") - } - Ok(()) -} - -#[cfg(not(unix))] -fn validate_frozen_source(_root: &Path) -> Result<()> { - bail!("frozen source observation requires Unix permissions") -} - -#[cfg(unix)] -fn frozen_source_sha256(root: &Path) -> Result { - let mut hasher = Sha256::new(); - hash_frozen_source_tree(root, root, &mut hasher)?; - Ok(format!("sha256-{:x}", hasher.finalize())) -} - -#[cfg(unix)] -fn hash_frozen_source_tree(root: &Path, current: &Path, hasher: &mut Sha256) -> Result<()> { - use std::os::unix::fs::PermissionsExt; - - let mut entries = fs::read_dir(current)?.collect::>>()?; - entries.sort_by_key(|entry| entry.file_name()); - for entry in entries { - let path = entry.path(); - let relative = normalized_relative(path.strip_prefix(root)?)?; - let metadata = fs::symlink_metadata(&path)?; - if metadata.is_dir() { - hasher.update(b"dir\0"); - hasher.update(relative.as_bytes()); - hasher.update(b"\0"); - hash_frozen_source_tree(root, &path, hasher)?; - } else if metadata.is_file() { - let bytes = fs::read(&path)?; - hasher.update(b"file\0"); - hasher.update(relative.as_bytes()); - hasher.update(b"\0"); - hasher.update( - (metadata.permissions().mode() & 0o111 != 0) - .to_string() - .as_bytes(), - ); - hasher.update(b"\0"); - hasher.update((bytes.len() as u64).to_le_bytes()); - hasher.update(&bytes); - } else if metadata.file_type().is_symlink() { - let target = fs::read_link(&path)?; - hasher.update(b"link\0"); - hasher.update(relative.as_bytes()); - hasher.update(b"\0"); - hasher.update(target.as_os_str().as_encoded_bytes()); - hasher.update(b"\0"); - } else { - bail!("frozen source contains a special filesystem entry") - } - } - Ok(()) -} - -#[cfg(not(unix))] -fn frozen_source_sha256(_root: &Path) -> Result { - bail!("frozen source observation requires Unix permissions") -} - -#[cfg(unix)] -fn harden_installed_release(root: &Path, artifacts: &[ArtifactReceipt]) -> Result<()> { - let executable_paths = artifacts - .iter() - .filter(|artifact| artifact.executable) - .map(|artifact| root.join(&artifact.destination)) - .collect::>(); - harden_root_tree(root, root, &executable_paths) -} - -#[cfg(unix)] -fn harden_root_tree( - root: &Path, - current: &Path, - executable_paths: &std::collections::BTreeSet, -) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let metadata = fs::symlink_metadata(current)?; - ensure!( - metadata.uid() == 0, - "sealed release entry is not root-owned" - ); - if metadata.is_dir() { - let mut entries = fs::read_dir(current)?.collect::>>()?; - entries.sort_by_key(|entry| entry.file_name()); - for entry in entries { - harden_root_tree(root, &entry.path(), executable_paths)?; - } - fs::set_permissions(current, fs::Permissions::from_mode(0o555))?; - } else if metadata.is_file() { - fs::set_permissions( - current, - fs::Permissions::from_mode(if executable_paths.contains(current) { - 0o555 - } else { - 0o444 - }), - )?; - } else if metadata.file_type().is_symlink() { - validate_release_symlink(root, current)?; - } else { - bail!("sealed release contains a special filesystem entry") - } - Ok(()) -} - -#[cfg(unix)] -fn validate_release_symlink(root: &Path, path: &Path) -> Result<()> { - let target = fs::read_link(path)?; - ensure!(target.is_relative(), "sealed release symlink is absolute"); - ensure!( - target.components().all(|component| matches!( - component, - std::path::Component::CurDir | std::path::Component::Normal(_) - )), - "sealed release symlink has a parent traversal" - ); - let destination = path - .parent() - .context("sealed release symlink has no parent")? - .join(target); - ensure!( - destination.starts_with(root), - "sealed release symlink escaped its release" - ); - Ok(()) -} - -#[cfg(not(unix))] -fn harden_installed_release(_root: &Path, _artifacts: &[ArtifactReceipt]) -> Result<()> { - bail!("systemd workload installation requires Unix permissions") -} - -#[cfg(unix)] -fn harden_runtime_bundle(bundle: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let metadata = fs::symlink_metadata(bundle)?; - let parent = bundle.parent().context("runtime bundle has no parent")?; - let parent_metadata = fs::symlink_metadata(parent)?; - ensure!( - metadata.is_dir() && !metadata.file_type().is_symlink() && metadata.uid() == 0, - "runtime bundle is not a root-owned directory" - ); - ensure!( - parent_metadata.is_dir() - && !parent_metadata.file_type().is_symlink() - && parent_metadata.uid() == 0 - && parent_metadata.permissions().mode() & 0o022 == 0, - "runtime bundle root is not root-owned and service-nonwritable" - ); - for name in [ - "expected.cc", - "expected.cc.lock", - "activation.cc", - "activation.cc.lock", - ] { - let path = bundle.join(name); - let metadata = fs::symlink_metadata(&path)?; - ensure!( - metadata.is_file() && !metadata.file_type().is_symlink() && metadata.uid() == 0, - "runtime bundle document is not root-owned" - ); - fs::set_permissions(path, fs::Permissions::from_mode(0o444))?; - } - fs::set_permissions(bundle, fs::Permissions::from_mode(0o555))?; - Ok(()) -} - -#[cfg(not(unix))] -fn harden_runtime_bundle(_bundle: &Path) -> Result<()> { - bail!("systemd runtime bundles require Unix permissions") -} - -fn observe_parent_only_file_descriptor( - fd_number: u32, - fd_name: &str, - source_path: &Path, -) -> Result { - validate_open_file_component(fd_name, "parent-only descriptor name")?; - ensure!( - source_path.is_absolute(), - "parent-only descriptor source is not absolute" - ); - validate_open_file_component( - &source_path.as_os_str().to_string_lossy(), - "parent-only descriptor source", - )?; - let mut file = open_native_read_only(source_path).with_context(|| { - format!( - "opening parent-only descriptor source {}", - source_path.display() - ) - })?; - let metadata = file.metadata()?; - ensure!( - metadata.is_file() && metadata.len() > 0, - "parent-only descriptor source is not one nonempty native file" - ); - #[cfg(unix)] - let (device, inode, uid, gid, mode, links) = { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - ( - metadata.dev(), - metadata.ino(), - metadata.uid(), - metadata.gid(), - metadata.permissions().mode() & 0o777, - metadata.nlink(), - ) - }; - #[cfg(not(unix))] - let (device, inode, uid, gid, mode, links) = (0, 0, 0, 0, 0, 0); - ensure!( - uid == 0 && gid == 0 && mode == 0o400 && links == 1, - "parent-only descriptor source is not root-owned, 0400, and singly linked" - ); - Ok(ParentOnlyFileDescriptorObservation { - fd_number, - fd_name: fd_name.to_owned(), - source_path: source_path.to_owned(), - access: "read-only".into(), - device, - inode, - uid, - gid, - mode, - links, - size: metadata.len(), - sha256: sha256_reader(&mut file)?, - }) -} - -fn parent_only_open_file_properties( - descriptors: &[ParentOnlyFileDescriptorObservation], -) -> Result> { - ensure!( - descriptors.len() == 2 - && descriptors[0].fd_number == 3 - && descriptors[0].fd_name == IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME - && descriptors[1].fd_number == 4 - && descriptors[1].fd_name == RUNTIME_PRESENCE_IDENTITY_FD_NAME, - "parent-only descriptor set is not the exact ordered activation/presence pair" - ); - descriptors - .iter() - .map(|descriptor| { - validate_open_file_component(&descriptor.fd_name, "parent-only descriptor name")?; - validate_open_file_component( - &descriptor.source_path.as_os_str().to_string_lossy(), - "parent-only descriptor source", - )?; - ensure!( - descriptor.source_path.is_absolute() - && descriptor.access == "read-only" - && descriptor.uid == 0 - && descriptor.gid == 0 - && descriptor.mode == 0o400 - && descriptor.links == 1 - && descriptor.size > 0, - "parent-only descriptor metadata is outside the Idunn contract" - ); - Ok(format!( - "{}:{}:{}", - descriptor.source_path.display(), - descriptor.fd_name, - descriptor.access - )) - }) - .collect() -} - -fn validate_open_file_component(value: &str, label: &str) -> Result<()> { - ensure!( - !value.is_empty() && !value.contains(':') && !value.chars().any(char::is_control), - "{label} cannot be represented by systemd OpenFile" - ); - Ok(()) -} - -#[cfg(unix)] -fn ensure_activation_credential_root(path: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - ensure!( - unsafe { libc::geteuid() } == 0, - "activation credential actuation requires root Idunn" - ); - ensure!( - path.is_absolute(), - "activation credential root is not absolute" - ); - let parent = path - .parent() - .context("activation credential root has no parent")?; - let parent_metadata = fs::symlink_metadata(parent).with_context(|| { - format!( - "inspecting activation credential parent {}", - parent.display() - ) - })?; - ensure!( - parent_metadata.is_dir() - && !parent_metadata.file_type().is_symlink() - && parent_metadata.uid() == 0 - && parent_metadata.permissions().mode() & 0o022 == 0 - && parent.canonicalize()? == parent, - "activation credential parent is not a canonical root-owned directory" - ); - match fs::symlink_metadata(path) { - Ok(metadata) => ensure!( - metadata.is_dir() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == 0 - && metadata.permissions().mode() & 0o777 == 0o700 - && path.canonicalize()? == path, - "activation credential root is not an exact root-only native directory" - ), - Err(error) if error.kind() == ErrorKind::NotFound => { - fs::create_dir(path).with_context(|| { - format!("creating activation credential root {}", path.display()) - })?; - fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; - let metadata = fs::symlink_metadata(path)?; - ensure!( - metadata.is_dir() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == 0 - && metadata.permissions().mode() & 0o777 == 0o700, - "new activation credential root has the wrong authority" - ); - } - Err(error) => { - return Err(error).with_context(|| { - format!("inspecting activation credential root {}", path.display()) - }); - } - } - Ok(()) -} - -#[cfg(not(unix))] -fn ensure_activation_credential_root(_path: &Path) -> Result<()> { - bail!("systemd activation credentials require a Unix authority path") -} - -#[cfg(unix)] -fn validate_activation_credential_source(path: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let metadata = fs::symlink_metadata(path) - .with_context(|| format!("inspecting activation credential source {}", path.display()))?; - ensure!( - metadata.is_file() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == 0 - && metadata.permissions().mode() & 0o777 == 0o400 - && metadata.nlink() == 1 - && metadata.len() == 32, - "activation credential source is not one exact root-owned 0400 32-byte file" - ); - Ok(()) -} - -#[cfg(not(unix))] -fn validate_activation_credential_source(_path: &Path) -> Result<()> { - bail!("systemd activation credentials require Unix file authority") -} - -#[cfg(unix)] -fn validate_service_credential_sources(sources: &BTreeMap) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - for (name, path) in sources { - ensure!( - path.is_absolute(), - "service credential {name} is not absolute" - ); - let parent = path - .parent() - .context("service credential source has no parent")?; - let parent_metadata = fs::symlink_metadata(parent).with_context(|| { - format!("inspecting service credential parent {}", parent.display()) - })?; - let metadata = fs::symlink_metadata(path) - .with_context(|| format!("inspecting service credential source {}", path.display()))?; - ensure!( - parent.canonicalize()? == parent - && parent_metadata.is_dir() - && !parent_metadata.file_type().is_symlink() - && parent_metadata.uid() == 0 - && parent_metadata.permissions().mode() & 0o022 == 0 - && path.canonicalize()? == path.as_path() - && metadata.is_file() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == 0 - && metadata.permissions().mode() & 0o777 == 0o400 - && metadata.nlink() == 1 - && metadata.len() > 0, - "service credential {name} is not one canonical root-owned 0400 file" - ); - } - Ok(()) -} - -#[cfg(not(unix))] -fn validate_service_credential_sources(_sources: &BTreeMap) -> Result<()> { - bail!("systemd service credentials require Unix file authority") -} - -fn remove_activation_credential_source(path: &Path) -> Result<()> { - match fs::symlink_metadata(path) { - Ok(metadata) => { - validate_activation_credential_source_for_removal(path, &metadata)?; - fs::remove_file(path).with_context(|| { - format!("deleting activation credential source {}", path.display()) - })?; - sync_parent_directory(path)?; - ensure!( - matches!(fs::symlink_metadata(path), Err(error) if error.kind() == ErrorKind::NotFound), - "activation credential source remained after deletion" - ); - Ok(()) - } - Err(error) if error.kind() == ErrorKind::NotFound => Ok(()), - Err(error) => Err(error) - .with_context(|| format!("inspecting activation credential source {}", path.display())), - } -} - -#[cfg(unix)] -fn validate_activation_credential_source_for_removal( - path: &Path, - metadata: &fs::Metadata, -) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let parent = path - .parent() - .context("activation credential source has no parent")?; - let parent_metadata = fs::symlink_metadata(parent)?; - ensure!( - parent_metadata.is_dir() - && !parent_metadata.file_type().is_symlink() - && parent_metadata.uid() == 0 - && parent_metadata.gid() == 0 - && parent_metadata.permissions().mode() & 0o777 == 0o700 - && metadata.is_file() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == 0 - && metadata.nlink() == 1 - && metadata.len() <= 32, - "refusing to delete a surprising activation credential source" - ); - Ok(()) -} - -#[cfg(not(unix))] -fn validate_activation_credential_source_for_removal( - _path: &Path, - _metadata: &fs::Metadata, -) -> Result<()> { - bail!("systemd activation credentials require Unix file authority") -} - -fn sync_parent_directory(path: &Path) -> Result<()> { - let parent = path.parent().context("file has no parent to synchronize")?; - let directory = open_native_read_only(parent)?; - directory - .sync_all() - .with_context(|| format!("synchronizing directory {}", parent.display())) -} - -fn open_native_read_only(path: &Path) -> Result { - let mut options = OpenOptions::new(); - options.read(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW); - } - Ok(options.open(path)?) -} - -fn open_proc_magic_link(path: &Path) -> Result { - let mut options = OpenOptions::new(); - options.read(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.custom_flags(libc::O_CLOEXEC); - } - options - .open(path) - .with_context(|| format!("opening procfs executable {}", path.display())) -} - -fn sha256_reader(reader: &mut impl Read) -> Result { - let mut digest = Sha256::new(); - let mut buffer = [0_u8; 64 * 1024]; - loop { - let read = reader.read(&mut buffer)?; - if read == 0 { - break; - } - digest.update(&buffer[..read]); - } - Ok(format!("sha256-{:x}", digest.finalize())) -} - -fn path_inside_process_root(process_root: &Path, absolute_path: &Path) -> Result { - ensure!( - process_root.is_absolute() && absolute_path.is_absolute(), - "process-root projection requires absolute paths" - ); - ensure!( - absolute_path.components().all(|component| matches!( - component, - std::path::Component::RootDir | std::path::Component::Normal(_) - )), - "process-root projection path is not normalized" - ); - Ok(process_root.join(absolute_path.strip_prefix(Path::new("/"))?)) -} - -fn linux_process_security( - status_path: &Path, - expected_host_pid: u32, -) -> Result { - let status = fs::read_to_string(status_path) - .with_context(|| format!("reading process status {}", status_path.display()))?; - let uids = linux_status_u32_array(&status, "Uid")?; - let gids = linux_status_u32_array(&status, "Gid")?; - let groups = linux_status_u32_values(&status, "Groups")?; - let cap_inheritable = linux_status_hex_u64(&status, "CapInh")?; - let cap_permitted = linux_status_hex_u64(&status, "CapPrm")?; - let cap_effective = linux_status_hex_u64(&status, "CapEff")?; - let cap_bounding = linux_status_hex_u64(&status, "CapBnd")?; - let cap_ambient = linux_status_hex_u64(&status, "CapAmb")?; - let no_new_privileges = match linux_status_value(&status, "NoNewPrivs")? { - "1" => true, - "0" => false, - _ => bail!("process NoNewPrivs value is invalid"), - }; - let namespace_pids = linux_status_u32_values(&status, "NSpid")?; - ensure!( - namespace_pids.first() == Some(&expected_host_pid), - "process status belongs to another host pid" - ); - Ok(LinuxProcessSecurityObservation { - uids, - gids, - groups, - cap_inheritable, - cap_permitted, - cap_effective, - cap_bounding, - cap_ambient, - no_new_privileges, - namespace_pids, - }) -} - -fn linux_status_value<'a>(status: &'a str, name: &str) -> Result<&'a str> { - let prefix = format!("{name}:"); - let matches = status - .lines() - .filter_map(|line| line.strip_prefix(&prefix)) - .collect::>(); - ensure!( - matches.len() == 1, - "process status has zero or duplicate {name} fields" - ); - Ok(matches[0].trim()) -} - -fn linux_status_u32_values(status: &str, name: &str) -> Result> { - linux_status_value(status, name)? - .split_whitespace() - .map(|value| { - value - .parse::() - .with_context(|| format!("process status {name} value is not a u32")) - }) - .collect() -} - -fn linux_status_u32_array(status: &str, name: &str) -> Result<[u32; 4]> { - linux_status_u32_values(status, name)? - .try_into() - .map_err(|_| anyhow::anyhow!("process status {name} does not have four values")) -} - -fn linux_status_hex_u64(status: &str, name: &str) -> Result { - u64::from_str_radix(linux_status_value(status, name)?, 16) - .with_context(|| format!("process status {name} value is not hexadecimal")) -} - -fn linux_namespace_id(path: &Path, kind: &str) -> Result { - let target = fs::read_link(path) - .with_context(|| format!("reading Linux namespace link {}", path.display()))?; - let target = target - .to_str() - .context("Linux namespace link is not UTF-8")?; - let prefix = format!("{kind}:["); - let id = target - .strip_prefix(&prefix) - .and_then(|value| value.strip_suffix(']')) - .context("Linux namespace link has an unexpected shape")?; - let id = id - .parse::() - .context("Linux namespace id is not a u64")?; - ensure!(id > 0, "Linux namespace id is zero"); - Ok(id) -} - -#[cfg(unix)] -fn resolve_group_id(group: &str) -> Result { - use std::ffi::CString; - - if let Ok(group_id) = group.parse::() { - ensure!(group_id > 0, "state group must be unprivileged"); - return Ok(group_id); - } - let group = CString::new(group).context("state group contains a NUL byte")?; - let mut buffer_size = 16_384_usize; - loop { - let mut entry = std::mem::MaybeUninit::::uninit(); - let mut result = std::ptr::null_mut(); - let mut buffer = vec![0_u8; buffer_size]; - let status = unsafe { - libc::getgrnam_r( - group.as_ptr(), - entry.as_mut_ptr(), - buffer.as_mut_ptr().cast(), - buffer.len(), - &mut result, - ) - }; - if status == libc::ERANGE && buffer_size < 1_048_576 { - buffer_size *= 2; - continue; - } - ensure!( - status == 0, - "resolving state group failed with errno {status}" - ); - ensure!(!result.is_null(), "configured state group does not exist"); - let entry = unsafe { entry.assume_init() }; - ensure!(entry.gr_gid > 0, "state group must be unprivileged"); - return Ok(entry.gr_gid); - } -} - -#[cfg(not(unix))] -fn resolve_group_id(_group: &str) -> Result { - bail!("systemd workload groups require a Unix actuator") -} - -#[cfg(unix)] -fn validate_workload_writable_path( - path: &Path, - state_group_id: u32, - require_setgid: bool, -) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let metadata = fs::symlink_metadata(path) - .with_context(|| format!("inspecting workload writable path {}", path.display()))?; - let mode = metadata.permissions().mode(); - ensure!( - !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == state_group_id - && mode & 0o002 == 0, - "workload writable path {} is not preprovisioned root:state-group without world write", - path.display() - ); - if metadata.is_dir() { - ensure!( - mode & 0o070 == 0o070 && (!require_setgid || mode & 0o2000 != 0), - "workload writable directory {} lacks group access or setgid inheritance", - path.display() - ); - } else { - ensure!( - metadata.is_file() && mode & 0o060 == 0o060, - "workload writable file is special or lacks group access" - ); - } - Ok(()) -} - -#[cfg(not(unix))] -fn validate_workload_writable_path( - _path: &Path, - _state_group_id: u32, - _require_setgid: bool, -) -> Result<()> { - bail!("systemd workload writable paths require Unix permissions") -} - -fn linux_process_start_time(stat_path: &Path) -> Result { - let stat = fs::read_to_string(stat_path) - .with_context(|| format!("reading process stat {}", stat_path.display()))?; - let close = stat - .rfind(')') - .context("process stat has no command terminator")?; - let fields = stat[close + 1..].split_whitespace().collect::>(); - fields - .get(19) - .context("process stat has no start-time field")? - .parse() - .context("process start-time field is not a u64") -} - -fn required_systemd_property<'a>( - values: &'a BTreeMap, - name: &str, -) -> Result<&'a str> { - let value = systemd_property(values, name)?; - ensure!(!value.is_empty(), "systemd unit has no {name}"); - Ok(value) -} - -fn systemd_property<'a>(values: &'a BTreeMap, name: &str) -> Result<&'a str> { - values - .get(name) - .map(String::as_str) - .with_context(|| format!("systemd unit did not expose {name}")) -} - -fn parse_systemd_boolean(values: &BTreeMap, name: &str) -> Result { - match systemd_property(values, name)? { - "yes" => Ok(true), - "no" => Ok(false), - _ => bail!("systemd unit exposed a non-boolean {name}"), - } -} - -fn read_process_environment(path: &Path) -> Result>> { - let bytes = fs::read(path) - .with_context(|| format!("reading process environment {}", path.display()))?; - Ok(bytes - .split(|byte| *byte == 0) - .filter(|entry| !entry.is_empty()) - .map(<[u8]>::to_vec) - .collect()) -} - -fn required_process_environment_value<'a>(entries: &'a [Vec], name: &str) -> Result<&'a str> { - let prefix = format!("{name}=").into_bytes(); - let matches = entries - .iter() - .filter_map(|entry| entry.strip_prefix(prefix.as_slice())) - .collect::>(); - ensure!( - matches.len() == 1, - "process environment has zero or duplicate {name} values" - ); - let value = std::str::from_utf8(matches[0]) - .with_context(|| format!("process environment {name} is not UTF-8"))?; - ensure!(!value.is_empty(), "process environment {name} is empty"); - Ok(value) -} - -fn select_process_environment( - entries: &[Vec], - names: &[String], -) -> Result> { - ensure!( - names.windows(2).all(|pair| pair[0] < pair[1]), - "workload environment witness names are not unique and sorted" - ); - let mut selected = BTreeMap::new(); - for name in names { - let prefix = format!("{name}=").into_bytes(); - let matches = entries - .iter() - .filter(|entry| entry.starts_with(&prefix)) - .collect::>(); - ensure!( - matches.len() == 1, - "workload process environment has missing or duplicate {name}" - ); - let value = std::str::from_utf8(&matches[0][prefix.len()..]) - .with_context(|| format!("workload environment {name} is not UTF-8"))?; - selected.insert(name.clone(), value.to_owned()); - } - Ok(selected) -} - -fn proc_command_line(command: &[OsString]) -> Vec { - let mut encoded = Vec::new(); - for argument in command { - encoded.extend_from_slice(argument.as_encoded_bytes()); - encoded.push(0); - } - encoded -} - -fn endpoint_host_port(endpoint: &str, scheme: &str) -> Result<(String, u16)> { - let authority = endpoint - .strip_prefix(scheme) - .with_context(|| format!("endpoint does not use {scheme}"))?; - ensure!( - !authority - .chars() - .any(|character| matches!(character, '/' | '?' | '#' | '@')) - && !authority.starts_with('['), - "route endpoint is not a plain host and port" - ); - let (host, port) = authority - .rsplit_once(':') - .context("route endpoint has no port")?; - ensure!( - !host.is_empty() - && host - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-')), - "route endpoint host is invalid" - ); - let port: u16 = port.parse().context("route endpoint port is not a u16")?; - ensure!(port > 0, "route endpoint port is zero"); - Ok((host.to_owned(), port)) -} - -fn nginx_identifier(route_id: &str) -> Result { - ensure!(!route_id.is_empty(), "nginx route id is empty"); - let mut identifier = String::from("idunn_"); - for byte in route_id.bytes() { - match byte { - b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' => { - identifier.push(char::from(byte)); - } - b'-' | b'.' => identifier.push('_'), - _ => bail!("route id cannot lower to an nginx identifier"), - } - } - Ok(identifier) -} - -fn atomic_replace(path: &Path, bytes: &[u8]) -> Result<()> { - #[cfg(unix)] - use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; - - ensure!(path.is_absolute(), "route path is not absolute"); - let parent = path.parent().context("route path has no parent")?; - ensure_route_authority_parent(parent)?; - match fs::symlink_metadata(path) { - Ok(_) => validate_root_owned_file(path, 0o644)?, - Err(error) if error.kind() == ErrorKind::NotFound => {} - Err(error) => return Err(error).context("inspecting route fragment"), - } - let file_name = path - .file_name() - .context("route path has no file name")? - .to_string_lossy(); - let temporary = parent.join(format!(".{file_name}.idunn-{}", Uuid::new_v4())); - let mut options = fs::OpenOptions::new(); - options.create_new(true).write(true); - #[cfg(unix)] - options.mode(0o644); - let mut file = options - .open(&temporary) - .with_context(|| format!("creating route stage {}", temporary.display()))?; - #[cfg(unix)] - file.set_permissions(fs::Permissions::from_mode(0o644))?; - file.write_all(bytes)?; - file.sync_all()?; - drop(file); - validate_root_owned_file(&temporary, 0o644)?; - if let Err(error) = fs::rename(&temporary, path) { - let _ = fs::remove_file(&temporary); - return Err(error).with_context(|| format!("publishing route {}", path.display())); - } - sync_parent_directory(path)?; - validate_root_owned_file(path, 0o644) -} - -#[cfg(unix)] -fn ensure_route_authority_parent(path: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - ensure!( - unsafe { libc::geteuid() } == 0, - "route actuation requires root Idunn" - ); - ensure!(path.is_absolute(), "route authority parent is not absolute"); - if !path.exists() { - let ancestor = path - .parent() - .context("route authority parent has no ancestor")?; - let ancestor_metadata = fs::symlink_metadata(ancestor)?; - ensure!( - ancestor.canonicalize()? == ancestor - && ancestor_metadata.is_dir() - && !ancestor_metadata.file_type().is_symlink() - && ancestor_metadata.uid() == 0 - && ancestor_metadata.permissions().mode() & 0o022 == 0, - "route authority ancestor is not canonical root-owned and nonwritable" - ); - fs::create_dir(path)?; - fs::set_permissions(path, fs::Permissions::from_mode(0o755))?; - } - let metadata = fs::symlink_metadata(path)?; - ensure!( - path.canonicalize()? == path - && metadata.is_dir() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == 0 - && metadata.permissions().mode() & 0o022 == 0, - "route authority parent is not canonical root-owned and nonwritable" - ); - Ok(()) -} - -#[cfg(not(unix))] -fn ensure_route_authority_parent(_path: &Path) -> Result<()> { - bail!("nginx route actuation requires Unix file authority") -} - -#[cfg(unix)] -fn ensure_route_preflight_root(path: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - ensure!(path.is_absolute(), "route preflight root is not absolute"); - if !path.exists() { - let parent = path - .parent() - .context("route preflight root has no parent")?; - ensure_route_authority_parent(parent)?; - fs::create_dir(path)?; - fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; - } - let metadata = fs::symlink_metadata(path)?; - ensure!( - unsafe { libc::geteuid() } == 0 - && path.canonicalize()? == path - && metadata.is_dir() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == 0 - && metadata.permissions().mode() & 0o777 == 0o700, - "route preflight root is not one canonical root-only directory" - ); - Ok(()) -} - -#[cfg(not(unix))] -fn ensure_route_preflight_root(_path: &Path) -> Result<()> { - bail!("nginx route preflight requires Unix file authority") -} - -#[cfg(unix)] -fn write_root_owned_file(path: &Path, bytes: &[u8], mode: u32) -> Result<()> { - use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; - - let mut options = OpenOptions::new(); - options.create_new(true).write(true).mode(mode); - let mut file = options.open(path)?; - file.set_permissions(fs::Permissions::from_mode(mode))?; - file.write_all(bytes)?; - file.sync_all()?; - drop(file); - sync_parent_directory(path)?; - validate_root_owned_file(path, mode) -} - -#[cfg(not(unix))] -fn write_root_owned_file(_path: &Path, _bytes: &[u8], _mode: u32) -> Result<()> { - bail!("root-owned route material requires Unix file authority") -} - -#[cfg(unix)] -fn validate_root_owned_file(path: &Path, mode: u32) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let metadata = fs::symlink_metadata(path)?; - ensure!( - path.canonicalize()? == path - && metadata.is_file() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == 0 - && metadata.permissions().mode() & 0o777 == mode - && metadata.nlink() == 1, - "route authority material is not one canonical root-owned file" - ); - Ok(()) -} - -#[cfg(not(unix))] -fn validate_root_owned_file(_path: &Path, _mode: u32) -> Result<()> { - bail!("root-owned route material requires Unix file authority") -} - -fn remove_exact_root_owned_file(path: &Path, mode: u32) -> Result<()> { - validate_root_owned_file(path, mode)?; - fs::remove_file(path)?; - sync_parent_directory(path) -} - -fn bind_mount(source: &Path, destination: &str, read_only: bool) -> Result { - ensure!(source.is_absolute(), "Docker bind source is not absolute"); - let text = source.to_str().context("Docker bind source is not UTF-8")?; - ensure!( - !text - .chars() - .any(|character| matches!(character, ',' | '\n' | '\r')), - "Docker bind source contains a forbidden mount character" - ); - let read_only = if read_only { ",readonly" } else { "" }; - Ok(OsString::from(format!( - "type=bind,src={text},dst={destination}{read_only}" - ))) -} - -fn systemd_read_only_bind_property(source: &Path, destination: &Path) -> Result { - ensure!( - source.is_absolute() && destination.is_absolute(), - "systemd bind paths are not absolute" - ); - let source = source - .to_str() - .context("systemd bind source is not UTF-8")?; - let destination = destination - .to_str() - .context("systemd bind destination is not UTF-8")?; - ensure!( - [source, destination] - .iter() - .all(|path| !path.contains([':', '\n', '\r', '\0'])), - "systemd bind path contains an unescaped property delimiter" - ); - Ok(OsString::from(format!( - "--property=BindReadOnlyPaths={source}:{destination}" - ))) -} - -fn normalized_relative(path: &Path) -> Result { - ensure!(path.is_relative(), "runner path is not relative"); - let mut parts = Vec::new(); - for component in path.components() { - match component { - std::path::Component::CurDir => {} - std::path::Component::Normal(value) => parts.push( - value - .to_str() - .context("runner path contains non-UTF-8")? - .to_owned(), - ), - _ => bail!("runner path escapes its workspace"), - } - } - Ok(parts.join("/")) -} - -fn copy_tree(source: &Path, destination: &Path) -> Result<()> { - ensure!(source.is_dir(), "source tree is not a directory"); - ensure!(!destination.exists(), "destination tree already exists"); - fs::create_dir_all(destination)?; - copy_tree_contents(source, destination) -} - -fn copy_tree_contents(source: &Path, destination: &Path) -> Result<()> { - let mut entries = fs::read_dir(source)?.collect::>>()?; - entries.sort_by_key(|entry| entry.file_name()); - for entry in entries { - let source_path = entry.path(); - let destination_path = destination.join(entry.file_name()); - let metadata = fs::symlink_metadata(&source_path)?; - if metadata.is_dir() { - fs::create_dir(&destination_path)?; - copy_tree_contents(&source_path, &destination_path)?; - } else if metadata.is_file() { - fs::copy(&source_path, &destination_path)?; - } else if metadata.file_type().is_symlink() { - copy_symlink(&source_path, &destination_path)?; - } else { - bail!("source tree contains a special filesystem entry") - } - } - Ok(()) -} - -#[cfg(unix)] -fn copy_symlink(source: &Path, destination: &Path) -> Result<()> { - std::os::unix::fs::symlink(fs::read_link(source)?, destination)?; - Ok(()) -} - -#[cfg(windows)] -fn copy_symlink(source: &Path, destination: &Path) -> Result<()> { - let target = fs::read_link(source)?; - if source.is_dir() { - std::os::windows::fs::symlink_dir(target, destination)?; - } else { - std::os::windows::fs::symlink_file(target, destination)?; - } - Ok(()) -} - -fn copy_artifact(source: &Path, destination: &Path) -> Result<()> { - let metadata = fs::symlink_metadata(source)?; - if metadata.is_dir() { - copy_tree(source, destination) - } else if metadata.is_file() { - if let Some(parent) = destination.parent() { - fs::create_dir_all(parent)?; - } - fs::copy(source, destination)?; - Ok(()) - } else { - bail!("artifact output is not a regular file or directory") - } -} - -fn digest_artifact(path: &Path) -> Result<(String, u64)> { - let metadata = fs::symlink_metadata(path)?; - if metadata.is_file() { - let bytes = fs::read(path)?; - return Ok((raw_sha256(&bytes), bytes.len().try_into()?)); - } - ensure!(metadata.is_dir(), "artifact is not a file or directory"); - let mut hasher = Sha256::new(); - let mut size = 0_u64; - digest_tree(path, path, &mut hasher, &mut size)?; - ensure!(size > 0, "artifact directory has no file content"); - Ok((format!("{:x}", hasher.finalize()), size)) -} - -fn digest_tree(root: &Path, current: &Path, hasher: &mut Sha256, size: &mut u64) -> Result<()> { - let mut entries = fs::read_dir(current)?.collect::>>()?; - entries.sort_by_key(|entry| entry.file_name()); - for entry in entries { - let path = entry.path(); - let relative = path.strip_prefix(root)?; - let relative = normalized_relative(relative)?; - let metadata = fs::symlink_metadata(&path)?; - if metadata.is_dir() { - hasher.update(b"dir\0"); - hasher.update(relative.as_bytes()); - hasher.update(b"\0"); - digest_tree(root, &path, hasher, size)?; - } else if metadata.is_file() { - let bytes = fs::read(&path)?; - hasher.update(b"file\0"); - hasher.update(relative.as_bytes()); - hasher.update(b"\0"); - hasher.update((bytes.len() as u64).to_le_bytes()); - hasher.update(&bytes); - *size = size.saturating_add(bytes.len().try_into()?); - } else if metadata.file_type().is_symlink() { - let target = fs::read_link(&path)?; - hasher.update(b"link\0"); - hasher.update(relative.as_bytes()); - hasher.update(b"\0"); - hasher.update(target.as_os_str().as_encoded_bytes()); - *size = size.saturating_add(target.as_os_str().len().try_into()?); - } else { - bail!("artifact tree contains a special filesystem entry") - } - } - Ok(()) -} - -fn raw_sha256(bytes: &[u8]) -> String { - format!("{:x}", Sha256::digest(bytes)) -} - -fn remove_tree_inside(root: &Path, target: &Path) -> Result<()> { - let root = root.canonicalize()?; - let target = target.canonicalize()?; - ensure!( - target.starts_with(&root) && target != root, - "refusing broad tree removal" - ); - fs::remove_dir_all(&target) - .with_context(|| format!("removing disposable runner workspace {}", target.display())) -} - -fn sha256_id(bytes: &[u8]) -> String { - format!("sha256-{:x}", Sha256::digest(bytes)) -} - -fn require_git_sha(value: &str, label: &str) -> Result<()> { - ensure!( - value.len() == 40 - && value - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)), - "{label} is not a lowercase SHA-1 object id" - ); - Ok(()) -} - -fn require_sha256_id(value: &str, label: &str) -> Result<()> { - let digest = value - .strip_prefix("sha256-") - .with_context(|| format!("{label} has no sha256 prefix"))?; - ensure!( - digest.len() == 64 - && digest - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)), - "{label} is not a lowercase SHA-256 id" - ); - Ok(()) -} - -fn require_driver_id(value: &str, label: &str) -> Result<()> { - ensure!( - !value.is_empty() - && value.len() <= 128 - && value - .bytes() - .all(|byte| { byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-') }), - "{label} id is invalid" - ); - Ok(()) -} - -fn ensure_source_directory_tree( - root: &Path, - directory: &Path, - identity: Option, -) -> Result<()> { - ensure!( - directory.starts_with(root), - "source directory escaped Idunn's source authority root" - ); - ensure_source_directory(root, identity)?; - let relative = directory.strip_prefix(root)?; - let mut current = root.to_owned(); - for component in relative.components() { - let std::path::Component::Normal(component) = component else { - bail!("source directory is not normalized") - }; - current.push(component); - ensure_source_directory(¤t, identity)?; - } - Ok(()) -} - -fn container_identity(value: &str) -> Result { - let (uid, gid) = value - .split_once(':') - .context("runner user is not numeric UID:GID")?; - let identity = ProcessIdentity { - uid: uid.parse().context("runner UID is not a u32")?, - gid: gid.parse().context("runner GID is not a u32")?, - }; - ensure!( - identity.uid > 0 && identity.gid > 0, - "runner identity must be unprivileged" - ); - Ok(identity) -} - -#[cfg(unix)] -fn ensure_runner_cache_root(path: &Path, identity: ProcessIdentity) -> Result<()> { - use std::os::unix::ffi::OsStrExt; - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - ensure!( - unsafe { libc::geteuid() } == 0, - "runner cache admission requires root Idunn" - ); - let parent = path.parent().context("runner cache root has no parent")?; - let parent_metadata = fs::symlink_metadata(parent) - .with_context(|| format!("inspecting runner cache parent {}", parent.display()))?; - ensure!( - parent_metadata.is_dir() - && !parent_metadata.file_type().is_symlink() - && parent_metadata.uid() == 0 - && parent_metadata.permissions().mode() & 0o022 == 0, - "runner cache parent is not root-owned and nonwritable" - ); - match fs::symlink_metadata(path) { - Ok(metadata) => ensure!( - metadata.is_dir() - && !metadata.file_type().is_symlink() - && metadata.uid() == identity.uid - && metadata.gid() == identity.gid - && metadata.permissions().mode() & 0o777 == 0o700, - "runner cache is not a dedicated exact-identity 0700 directory" - ), - Err(error) if error.kind() == ErrorKind::NotFound => { - fs::create_dir(path) - .with_context(|| format!("creating runner cache {}", path.display()))?; - let path_c = std::ffi::CString::new(path.as_os_str().as_bytes()) - .context("runner cache path contains a NUL byte")?; - if unsafe { libc::lchown(path_c.as_ptr(), identity.uid, identity.gid) } != 0 { - return Err(std::io::Error::last_os_error()) - .context("assigning runner cache owner"); - } - fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; - } - Err(error) => { - return Err(error) - .with_context(|| format!("inspecting runner cache {}", path.display())); - } - } - Ok(()) -} - -#[cfg(not(unix))] -fn ensure_runner_cache_root(_path: &Path, _identity: ProcessIdentity) -> Result<()> { - bail!("runner cache admission requires a Unix actuator") -} - -#[cfg(unix)] -fn validate_runner_secret(path: &Path, identity: ProcessIdentity) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - ensure!( - unsafe { libc::geteuid() } == 0, - "runner secret admission requires root Idunn" - ); - let parent = path.parent().context("runner secret has no parent")?; - let parent_metadata = fs::symlink_metadata(parent) - .with_context(|| format!("inspecting runner secret parent {}", parent.display()))?; - let metadata = fs::symlink_metadata(path) - .with_context(|| format!("inspecting runner secret {}", path.display()))?; - ensure!( - parent_metadata.is_dir() - && !parent_metadata.file_type().is_symlink() - && parent_metadata.uid() == 0 - && parent_metadata.permissions().mode() & 0o022 == 0, - "runner secret parent is not root-owned and nonwritable" - ); - ensure!( - metadata.is_file() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == identity.gid - && metadata.permissions().mode() & 0o777 == 0o440, - "runner secret is not root-owned, exact-group-bound, and 0440" - ); - Ok(()) -} - -#[cfg(not(unix))] -fn validate_runner_secret(_path: &Path, _identity: ProcessIdentity) -> Result<()> { - bail!("runner secret admission requires a Unix actuator") -} - -#[cfg(unix)] -fn assign_runner_tree(path: &Path, identity: ProcessIdentity) -> Result<()> { - use std::os::unix::ffi::OsStrExt; - use std::os::unix::fs::PermissionsExt; - - ensure!( - unsafe { libc::geteuid() } == 0, - "runner workspace ownership requires root Idunn" - ); - let metadata = fs::symlink_metadata(path)?; - if metadata.is_dir() { - let mut entries = fs::read_dir(path)?.collect::>>()?; - entries.sort_by_key(|entry| entry.file_name()); - for entry in entries { - assign_runner_tree(&entry.path(), identity)?; - } - fs::set_permissions(path, fs::Permissions::from_mode(0o750))?; - } else if metadata.is_file() { - let executable = metadata.permissions().mode() & 0o111 != 0; - fs::set_permissions( - path, - fs::Permissions::from_mode(if executable { 0o750 } else { 0o640 }), - )?; - } else if !metadata.file_type().is_symlink() { - bail!("runner workspace contains a special filesystem entry") - } - let path_c = std::ffi::CString::new(path.as_os_str().as_bytes()) - .context("runner workspace path contains a NUL byte")?; - let result = unsafe { libc::lchown(path_c.as_ptr(), identity.uid, identity.gid) }; - if result != 0 { - return Err(std::io::Error::last_os_error()).context("assigning runner workspace owner"); - } - Ok(()) -} - -#[cfg(not(unix))] -fn assign_runner_tree(_path: &Path, _identity: ProcessIdentity) -> Result<()> { - bail!("non-root runner identities require a Unix actuator") -} - -fn ensure_source_directory(path: &Path, identity: Option) -> Result<()> { - match fs::symlink_metadata(path) { - Ok(metadata) => { - ensure!( - metadata.is_dir() && !metadata.file_type().is_symlink(), - "source authority path {} is not a native directory", - path.display() - ); - validate_source_directory_owner(path, &metadata, identity) - } - Err(error) if error.kind() == ErrorKind::NotFound => { - let parent = path - .parent() - .context("source authority directory has no parent")?; - ensure!( - parent.is_dir(), - "source authority parent {} is absent", - parent.display() - ); - fs::create_dir(path).with_context(|| { - format!("creating source authority directory {}", path.display()) - })?; - assign_source_directory_owner(path, identity)?; - let metadata = fs::symlink_metadata(path)?; - validate_source_directory_owner(path, &metadata, identity) - } - Err(error) => Err(error) - .with_context(|| format!("inspecting source authority path {}", path.display())), - } -} - -fn authority_lock_path(path: &Path) -> PathBuf { - let mut lock = path.as_os_str().to_os_string(); - lock.push(".lock"); - PathBuf::from(lock) -} - -#[cfg(unix)] -fn validate_root_authority_path(path: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - ensure!( - unsafe { libc::geteuid() } == 0, - "process write-lease actuation requires root Idunn" - ); - let parent = path - .parent() - .context("process write-lease path has no parent")?; - let parent_metadata = fs::symlink_metadata(parent) - .with_context(|| format!("inspecting write-lease parent {}", parent.display()))?; - ensure!( - parent_metadata.is_dir() - && !parent_metadata.file_type().is_symlink() - && parent_metadata.uid() == 0 - && parent_metadata.permissions().mode() & 0o022 == 0, - "write-lease parent is not root-owned and service-nonwritable" - ); - for authority_file in [path.to_owned(), authority_lock_path(path)] { - match fs::symlink_metadata(&authority_file) { - Ok(metadata) => ensure!( - metadata.is_file() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == parent_metadata.gid() - && metadata.permissions().mode() & 0o022 == 0, - "write-lease authority file {} is not root-owned and service-nonwritable", - authority_file.display() - ), - Err(error) if error.kind() == ErrorKind::NotFound => {} - Err(error) => { - return Err(error).with_context(|| { - format!( - "inspecting write-lease authority file {}", - authority_file.display() - ) - }); - } - } - } - Ok(()) -} - -#[cfg(not(unix))] -fn validate_root_authority_path(_path: &Path) -> Result<()> { - bail!("process write-lease actuation requires a Unix authority path") -} - -#[cfg(unix)] -fn harden_root_authority_file(path: &Path) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let parent = path - .parent() - .context("process write-lease authority file has no parent")?; - let parent_metadata = fs::symlink_metadata(parent)?; - let metadata = fs::symlink_metadata(path)?; - ensure!( - metadata.is_file() - && !metadata.file_type().is_symlink() - && metadata.uid() == 0 - && metadata.gid() == parent_metadata.gid(), - "new write-lease authority file has the wrong owner" - ); - fs::set_permissions(path, fs::Permissions::from_mode(0o640))?; - Ok(()) -} - -#[cfg(not(unix))] -fn harden_root_authority_file(_path: &Path) -> Result<()> { - bail!("process write-lease actuation requires Unix permissions") -} - -#[cfg(unix)] -fn assign_source_directory_owner(path: &Path, identity: Option) -> Result<()> { - use std::os::unix::ffi::OsStrExt; - use std::os::unix::fs::PermissionsExt; - - if let Some(identity) = identity { - let path = std::ffi::CString::new(path.as_os_str().as_bytes()) - .context("source authority path contains a NUL byte")?; - let result = unsafe { libc::chown(path.as_ptr(), identity.uid, identity.gid) }; - if result != 0 { - return Err(std::io::Error::last_os_error()) - .context("assigning source authority directory owner"); - } - } - fs::set_permissions(path, fs::Permissions::from_mode(0o750))?; - Ok(()) -} - -#[cfg(not(unix))] -fn assign_source_directory_owner(_path: &Path, identity: Option) -> Result<()> { - ensure!( - identity.is_none(), - "configured source identities require a Unix actuator" - ); - Ok(()) -} - -#[cfg(unix)] -fn validate_source_directory_owner( - path: &Path, - metadata: &fs::Metadata, - identity: Option, -) -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let expected = identity.unwrap_or(ProcessIdentity { - uid: unsafe { libc::geteuid() }, - gid: unsafe { libc::getegid() }, - }); - ensure!( - metadata.uid() == expected.uid && metadata.gid() == expected.gid, - "source authority directory {} has the wrong owner", - path.display() - ); - ensure!( - metadata.permissions().mode() & 0o200 != 0, - "source authority directory {} is not owner-writable", - path.display() - ); - Ok(()) -} - -#[cfg(not(unix))] -fn validate_source_directory_owner( - _path: &Path, - _metadata: &fs::Metadata, - identity: Option, -) -> Result<()> { - ensure!( - identity.is_none(), - "configured source identities require a Unix actuator" - ); - Ok(()) -} - -fn apply_identity(command: &mut Command, identity: Option) -> Result<()> { - let Some(identity) = identity else { - return Ok(()); - }; - #[cfg(unix)] - { - use std::os::unix::process::CommandExt; - ensure!( - identity.uid > 0 && identity.gid > 0, - "configured source identity must be unprivileged" - ); - unsafe { - command.pre_exec(move || { - if libc::setgroups(0, std::ptr::null()) != 0 { - return Err(std::io::Error::last_os_error()); - } - if libc::setgid(identity.gid) != 0 { - return Err(std::io::Error::last_os_error()); - } - if libc::setuid(identity.uid) != 0 { - return Err(std::io::Error::last_os_error()); - } - Ok(()) - }); - } - Ok(()) - } - #[cfg(not(unix))] - { - let _ = command; - let _ = identity; - bail!("configured process identities require a Unix actuator") - } -} - -#[cfg(test)] -mod tests { - use super::*; - use cultnet_rs::{ - GameCultProviderHealthIdentity, IDUNN_EXPECTED_INCARNATION_SCHEMA, - IDUNN_PROCESS_WRITE_LEASE_SCHEMA, IdunnServiceIdentity, - OdinRuntimeTopologyCorrelationPurpose, OdinTopologyAuthenticationContext, - OdinTopologyIdentity, authenticate_odin_runtime_topology_correlation, - enroll_service_identity_at, verify_runtime_authority, - }; - - fn digest(byte: char) -> String { - format!("sha256-{}", byte.to_string().repeat(64)) - } - - fn parent_only_descriptor( - fd_number: u32, - fd_name: &str, - source: &str, - ) -> ParentOnlyFileDescriptorObservation { - ParentOnlyFileDescriptorObservation { - fd_number, - fd_name: fd_name.into(), - source_path: PathBuf::from(source), - access: "read-only".into(), - device: 1, - inode: u64::from(fd_number), - uid: 0, - gid: 0, - mode: 0o400, - links: 1, - size: 32, - sha256: digest('a'), - } - } - - #[test] - fn signer_sources_lower_to_exactly_two_ordered_parent_only_open_files() -> Result<()> { - let activation = parent_only_descriptor( - 3, - IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, - "/run/idunn/activation-credentials/activation.credential", - ); - let presence = parent_only_descriptor( - 4, - RUNTIME_PRESENCE_IDENTITY_FD_NAME, - "/etc/gamecult/service/runtime-presence-identity.cc", - ); - assert_eq!( - parent_only_open_file_properties(&[activation.clone(), presence.clone()])?, - vec![ - "/run/idunn/activation-credentials/activation.credential:gamecult-idunn-runtime-activation-key:read-only", - "/etc/gamecult/service/runtime-presence-identity.cc:gamecult-runtime-presence-identity:read-only", - ] - ); - assert!(parent_only_open_file_properties(&[presence, activation]).is_err()); - Ok(()) - } - - #[cfg(unix)] - fn git_at(repository: &Path, arguments: &[&str]) -> Result { - let output = Command::new("/usr/bin/git") - .arg("-C") - .arg(repository) - .args(arguments) - .env_clear() - .env("HOME", repository) - .env("PATH", "/usr/bin:/bin") - .env("GIT_CONFIG_NOSYSTEM", "1") - .env("LANG", "C.UTF-8") - .output()?; - ensure!( - output.status.success(), - "test Git failed: {}", - String::from_utf8_lossy(&output.stderr).trim() - ); - Ok(String::from_utf8(output.stdout)?.trim().to_owned()) - } - - fn expected() -> IdunnExpectedIncarnationRecord { - IdunnExpectedIncarnationRecord { - schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(), - target: "service".into(), - plan_id: digest('1'), - incarnation_id: "incarnation-1".into(), - sealed_release_id: digest('2'), - source_repository: "github.com/GameCult/Service".into(), - source_revision: "3".repeat(40), - recipe_sha256: digest('4'), - runtime_id: "service-runtime".into(), - expected_signer_identity_id: "service-signer".into(), - health_contract: "service.health.v1".into(), - artifact_sha256: digest('5'), - state_schema_generation: Some("state-v1".into()), - state_contract_sha256: Some(digest('6')), - write_lease_required: true, - route: None, - capabilities: Vec::new(), - dependencies: Vec::new(), - } - } - - fn authenticated_warming( - root: &Path, - ) -> Result<( - IdunnExpectedIncarnationRecord, - IdunnRuntimeActivationRecord, - SequenceAdmittedWarming, - ServiceIdentityTrustAnchor, - )> { - let provider = enroll_service_identity_at::( - &root.join("provider.cc"), - )?; - let idunn = enroll_service_identity_at::(&root.join("idunn.cc"))?; - let odin = enroll_service_identity_at::(&root.join("odin.cc"))?; - let mut expected = expected(); - expected.expected_signer_identity_id = provider.entry().identity_id.clone(); - let launch = IdunnRuntimeActivationLaunch::issue(&expected, digest('7'), 100, &idunn)?; - let activation = launch.activation().clone(); - launch.write_credential(std::io::sink())?; - let authority = verify_runtime_authority( - &expected, - &activation, - &idunn.trust_anchor()?, - &provider.entry().public_key, - )?; - let mut warming = OdinRuntimeTopologyCorrelationRecord { - schema_version: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into(), - target: expected.target.clone(), - expected_projection_sha256: expected.canonical_sha256()?, - expected: true, - current_activation_sha256: Some(activation.canonical_sha256()?), - signed_presence_sha256: Some(digest('9')), - observed_presence_state: Some("warming".into()), - observed_presence_publisher_sequence: Some(1), - observed_write_lease_sha256: None, - observed_capabilities: Vec::new(), - runtime_id: expected.runtime_id.clone(), - runtime_instance_id: Some(activation.runtime_instance_id.clone()), - present: true, - ready: false, - dependencies: Vec::new(), - disagreements: Vec::new(), - signer_identity_id: odin.entry().identity_id.clone(), - publisher_sequence: 1, - observed_at_unix_millis: 110, - signature_algorithm: "ed25519".into(), - signature: Vec::new(), - }; - warming.signature = odin - .sign::(&warming.unsigned_signature_payload()?) - .signature; - let warming = authenticate_odin_runtime_topology_correlation( - &warming.canonical_bytes()?, - &authority, - None, - &odin.entry().public_key, - OdinTopologyAuthenticationContext { - trusted_received_at_unix_millis: 120, - maximum_age_millis: 30, - maximum_future_skew_millis: 5, - }, - )?; - let warming = SequenceAdmittedWarming::for_test("test-transaction", warming, 120)?; - Ok((expected, activation, warming, provider.trust_anchor()?)) - } - - fn lease( - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - warming: &SequenceAdmittedWarming, - ) -> IdunnProcessWriteLeaseRecord { - IdunnProcessWriteLeaseRecord { - schema_version: IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into(), - target: expected.target.clone(), - expected_projection_sha256: expected.canonical_sha256().unwrap(), - plan_id: expected.plan_id.clone(), - incarnation_id: expected.incarnation_id.clone(), - sealed_release_id: expected.sealed_release_id.clone(), - activation_witness_sha256: activation.canonical_sha256().unwrap(), - state_schema_generation: expected.state_schema_generation.clone().unwrap(), - state_contract_sha256: expected.state_contract_sha256.clone().unwrap(), - runtime_id: expected.runtime_id.clone(), - runtime_instance_id: activation.runtime_instance_id.clone(), - warming_presence_sha256: warming.signed_presence_sha256().to_owned(), - lease_epoch: 1, - issued_at_unix_millis: 200, - } - } - - fn topology_driver(root: &Path, name: &str) -> CultCacheTopologyDriver { - CultCacheTopologyDriver { - projection_store: root.join(format!("{name}.cc")), - correlation_store: root.join(format!("{name}-correlation.cc")), - } - } - - fn project_activation( - driver: &CultCacheTopologyDriver, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result<()> { - ensure!( - activation.expected_projection_sha256 == expected.canonical_sha256()?, - "test activation belongs to another Expected" - ); - upsert_record( - &driver.projection_store, - CultCacheEnvelope { - key: expected.target.clone(), - r#type: IdunnRuntimeActivationRecord::TYPE.into(), - payload: activation.canonical_bytes()?, - stored_at: rfc3339_millis(activation.issued_at_unix_millis)?, - schema_id: Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA.into()), - }, - ) - } - - #[test] - fn nginx_rudp_route_is_rendered_as_a_udp_stream_proxy() -> Result<()> { - let driver = NginxRouteDriver::new(RouteBinding { - driver: RouteDriver::NginxStreamUdp, - route_id: "odin-rudp".into(), - stable_endpoint: "rudp://127.0.0.1:17872".into(), - private_host: "127.0.0.1".into(), - private_port_start: 27872, - private_port_end: 27879, - config_path: "/etc/nginx/idunn-stream-routes/odin-rudp.conf".into(), - reload_unit: "nginx.service".into(), - }); - let mut candidate = expected(); - candidate.route = Some(cultnet_rs::IdunnExpectedRoute { - route_id: "odin-rudp".into(), - transport: "rudp".into(), - stable_endpoint: "rudp://127.0.0.1:17872".into(), - candidate_endpoint: "rudp://127.0.0.1:27872".into(), - }); - let rendered = String::from_utf8(driver.render(&candidate)?)?; - assert!(rendered.contains("listen 127.0.0.1:17872 udp reuseport;")); - assert!(rendered.contains("server 127.0.0.1:27872;")); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn nginx_preflight_binds_exact_incumbent_configuration_without_claiming_live_route() - -> Result<()> { - use std::os::unix::fs::PermissionsExt; - - let temp = tempfile::tempdir()?; - let config = temp.path().join("route.conf"); - let nginx = temp.path().join("nginx"); - let systemd_run = temp.path().join("systemd-run"); - let systemctl = temp.path().join("systemctl"); - fs::write( - &nginx, - format!( - "#!/bin/sh\nconfig='{}'\nif [ \"$1\" = \"-t\" ]; then\n candidate=${{IDUNN_TEST_SHADOW:-$config}}\n /bin/grep -q 'server 127.0.0.1:4104' \"$candidate\"\n exit $?\nfi\nexit 64\n", - config.display(), - ), - )?; - fs::write( - &systemd_run, - "#!/bin/sh\nshadow=\nwhile [ \"$#\" -gt 0 ]; do\n case \"$1\" in\n --property=BindReadOnlyPaths=*) binding=${1#--property=BindReadOnlyPaths=}; shadow=${binding%%:*} ;; - --) shift; break ;; - esac\n shift\ndone\nIDUNN_TEST_SHADOW=\"$shadow\"; export IDUNN_TEST_SHADOW\nexec \"$@\"\n", - )?; - fs::write( - &systemctl, - "#!/bin/sh\nif [ -e \"$0.fail\" ]; then exit 65; fi\nif [ \"$1\" = \"reload\" ]; then echo reload >> \"$0.calls\"; exit 0; fi\nexit 64\n", - )?; - fs::set_permissions(&nginx, fs::Permissions::from_mode(0o755))?; - fs::set_permissions(&systemd_run, fs::Permissions::from_mode(0o755))?; - fs::set_permissions(&systemctl, fs::Permissions::from_mode(0o755))?; - - let binding = RouteBinding { - driver: RouteDriver::NginxStreamTcp, - route_id: "service-route".into(), - stable_endpoint: "http://127.0.0.1:4103".into(), - private_host: "127.0.0.1".into(), - private_port_start: 4104, - private_port_end: 4109, - config_path: config.clone(), - reload_unit: "nginx.service".into(), - }; - let driver = NginxRouteDriver { - binding, - nginx_program: nginx, - systemd_run_program: systemd_run, - systemctl_program: systemctl.clone(), - preflight_root: temp.path().join("preflight"), - }; - let mut candidate = expected(); - candidate.route = Some(cultnet_rs::IdunnExpectedRoute { - route_id: "service-route".into(), - transport: "http".into(), - stable_endpoint: "http://127.0.0.1:4103".into(), - candidate_endpoint: "http://127.0.0.1:4104".into(), - }); - let preflight = driver.preflight(&candidate, &digest('a'), None)?; - assert!(!config.exists()); - assert_eq!(fs::read_dir(&driver.preflight_root)?.count(), 0); - - let candidate_bytes = driver.render(&candidate)?; - fs::write(&config, &candidate_bytes)?; - let membership_sha256 = driver.install(&candidate, &digest('a'), &preflight, true)?; - assert_eq!( - fs::read_to_string(systemctl.with_extension("calls"))?, - "reload\n" - ); - assert!(driver.observe_membership(&candidate, &membership_sha256)?); - let admitted_bytes = fs::read(&config)?; - assert!(std::str::from_utf8(&admitted_bytes)?.contains("listen 127.0.0.1:4103;")); - let admitted = RouteObservation { - route_id: "service-route".into(), - runtime_instance_id: digest('a'), - membership_sha256, - signed_presence_sha256: digest('c'), - observed_at_unix_millis: 1, - }; - - let next_preflight = driver.preflight(&candidate, &digest('b'), Some(&admitted))?; - assert_eq!(fs::read(&config)?, admitted_bytes); - fs::write(systemctl.with_extension("fail"), b"fail\n")?; - assert!( - driver - .install(&candidate, &digest('b'), &next_preflight, false) - .is_err() - ); - assert_eq!(fs::read(&config)?, admitted_bytes); - fs::remove_file(systemctl.with_extension("fail"))?; - driver.install(&candidate, &digest('b'), &next_preflight, false)?; - fs::write(&config, b"foreign route\n")?; - assert!( - driver - .install(&candidate, &digest('b'), &next_preflight, true) - .is_err() - ); - driver.restore_admitted_membership(&candidate, &admitted.membership_sha256)?; - assert_eq!(fs::read(&config)?, admitted_bytes); - assert!(driver.observe_membership(&candidate, &admitted.membership_sha256)?); - - fs::write(&config, b"foreign route after admission\n")?; - fs::write(systemctl.with_extension("fail"), b"fail\n")?; - assert!( - driver - .restore_admitted_membership(&candidate, &admitted.membership_sha256) - .is_err() - ); - assert!(!config.exists()); - fs::remove_file(systemctl.with_extension("fail"))?; - driver.restore_admitted_membership(&candidate, &admitted.membership_sha256)?; - assert_eq!(fs::read(&config)?, admitted_bytes); - Ok(()) - } - - #[test] - fn process_environment_witness_is_sorted_exact_and_secret_free() -> Result<()> { - let entries = vec![ - b"B=two".to_vec(), - b"A=one".to_vec(), - b"UNRELATED=ignored".to_vec(), - ]; - let selected = select_process_environment(&entries, &["A".into(), "B".into()])?; - assert_eq!(selected.get("A").map(String::as_str), Some("one")); - assert!(!selected.contains_key("UNRELATED")); - assert!(select_process_environment(&entries, &["B".into(), "A".into()]).is_err()); - Ok(()) - } - - #[test] - fn topology_transport_returns_opaque_odin_bytes_without_deciding_ready() -> Result<()> { - let temp = tempfile::tempdir()?; - let correlation_store = temp.path().join("correlation.cc"); - let opaque = b"not a topology receipt".to_vec(); - upsert_record( - &correlation_store, - CultCacheEnvelope { - key: "service".into(), - r#type: OdinRuntimeTopologyCorrelationRecord::TYPE.into(), - payload: opaque.clone(), - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some(ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into()), - }, - )?; - let driver = CultCacheTopologyDriver { - projection_store: temp.path().join("projection.cc"), - correlation_store, - }; - - assert_eq!( - driver.receive("service")?, - Some(ReceivedOdinTopologyCorrelation { - target: "service".into(), - canonical_bytes: opaque, - }) - ); - Ok(()) - } - - #[test] - fn expected_withdrawal_is_exact_atomic_and_idempotent() -> Result<()> { - let temp = tempfile::tempdir()?; - let (expected, activation, warming, provider_anchor) = authenticated_warming(temp.path())?; - let lease = lease(&expected, &activation, &warming); - let driver = topology_driver(temp.path(), "projection"); - driver.publish_expected(&expected, &provider_anchor)?; - let published = SingleFileMessagePackBackingStore::new(&driver.projection_store) - .pull_all_read_only_snapshot()?; - assert_eq!(published.len(), 2); - assert!(published.iter().any(|entry| { - entry.key == expected.target && entry.r#type == IdunnExpectedIncarnationRecord::TYPE - })); - let published_anchor = published - .iter() - .find(|entry| entry.r#type == GameCultServiceTrustAnchorRecord::TYPE) - .context("atomic Expected set has no provider trust anchor")?; - assert_eq!( - service_trust_anchor_from_envelope(published_anchor)?, - runtime_presence_trust_anchor(&expected, &provider_anchor)? - ); - project_activation(&driver, &expected, &activation)?; - driver.publish_process_write_lease(&expected, &activation, &lease)?; - - let mut substituted_expected = expected.clone(); - substituted_expected.incarnation_id = "another-incarnation".into(); - upsert_record( - &driver.projection_store, - CultCacheEnvelope { - key: expected.target.clone(), - r#type: IdunnExpectedIncarnationRecord::TYPE.into(), - payload: substituted_expected.canonical_bytes()?, - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some(IDUNN_EXPECTED_INCARNATION_SCHEMA.into()), - }, - )?; - assert!( - driver - .withdraw_expected(&expected, &provider_anchor, Some(&activation), Some(&lease)) - .is_err() - ); - driver.publish_expected(&expected, &provider_anchor)?; - - let mut substituted_anchor = runtime_presence_trust_anchor(&expected, &provider_anchor)?; - substituted_anchor.runtime_id = "another-runtime".into(); - substituted_anchor.validate()?; - upsert_record( - &driver.projection_store, - CultCacheEnvelope { - key: substituted_anchor.trust_anchor_id.clone(), - r#type: GameCultServiceTrustAnchorRecord::TYPE.into(), - payload: rmp_serde::to_vec(&substituted_anchor)?, - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some(GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into()), - }, - )?; - assert!( - driver - .withdraw_expected(&expected, &provider_anchor, Some(&activation), Some(&lease)) - .is_err() - ); - driver.publish_expected(&expected, &provider_anchor)?; - - let mut substituted_activation = activation.clone(); - substituted_activation.expected_projection_sha256 = digest('a'); - upsert_record( - &driver.projection_store, - CultCacheEnvelope { - key: expected.target.clone(), - r#type: IdunnRuntimeActivationRecord::TYPE.into(), - payload: substituted_activation.canonical_bytes()?, - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA.into()), - }, - )?; - assert!( - driver - .withdraw_expected(&expected, &provider_anchor, Some(&activation), None) - .is_err() - ); - project_activation(&driver, &expected, &activation)?; - - let mut substituted_lease = lease.clone(); - substituted_lease.lease_epoch += 1; - assert!( - driver - .publish_process_write_lease(&expected, &activation, &substituted_lease) - .is_err() - ); - assert!( - driver - .withdraw_expected( - &expected, - &provider_anchor, - Some(&activation), - Some(&substituted_lease), - ) - .is_err() - ); - - upsert_record( - &driver.projection_store, - CultCacheEnvelope { - key: "unrelated".into(), - r#type: "test.unrelated".into(), - payload: vec![0x90], - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some("test.unrelated.v1".into()), - }, - )?; - driver.withdraw_expected(&expected, &provider_anchor, Some(&activation), Some(&lease))?; - let remaining = SingleFileMessagePackBackingStore::new(&driver.projection_store) - .pull_all_read_only_snapshot()?; - assert_eq!(remaining.len(), 1); - assert_eq!(remaining[0].key, "unrelated"); - driver.withdraw_expected(&expected, &provider_anchor, Some(&activation), Some(&lease))?; - Ok(()) - } - - #[test] - fn incumbent_projection_restoration_demotes_to_expected_only_and_rejects_unknown_authority() - -> Result<()> { - let temp = tempfile::tempdir()?; - let (incumbent, activation, warming, provider_anchor) = authenticated_warming(temp.path())?; - let lease = lease(&incumbent, &activation, &warming); - let driver = topology_driver(temp.path(), "restoration"); - driver.publish_expected(&incumbent, &provider_anchor)?; - project_activation(&driver, &incumbent, &activation)?; - driver.publish_process_write_lease(&incumbent, &activation, &lease)?; - - let mut candidate = incumbent.clone(); - candidate.plan_id = digest('a'); - candidate.incarnation_id = "candidate-incarnation".into(); - candidate.sealed_release_id = digest('b'); - candidate.artifact_sha256 = digest('c'); - let mut candidate_activation = activation.clone(); - candidate_activation.expected_projection_sha256 = candidate.canonical_sha256()?; - candidate_activation.runtime_instance_id = digest('d'); - driver.publish_expected(&candidate, &provider_anchor)?; - project_activation(&driver, &candidate, &candidate_activation)?; - - upsert_record( - &driver.projection_store, - CultCacheEnvelope { - key: "unrelated".into(), - r#type: "test.unrelated".into(), - payload: vec![0x90], - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some("test.unrelated.v1".into()), - }, - )?; - - assert_eq!( - driver.restore_admitted_expected_only( - &candidate, - &provider_anchor, - Some(&candidate_activation), - &incumbent, - &provider_anchor, - &activation, - Some(&lease), - )?, - incumbent.canonical_sha256()? - ); - - let restored = SingleFileMessagePackBackingStore::new(&driver.projection_store) - .pull_all_read_only_snapshot()?; - assert_eq!(restored.len(), 3); - assert_eq!( - IdunnExpectedIncarnationRecord::decode_canonical( - &restored - .iter() - .find(|entry| entry.r#type == IdunnExpectedIncarnationRecord::TYPE) - .unwrap() - .payload, - )?, - incumbent - ); - assert_eq!( - service_trust_anchor_from_envelope( - restored - .iter() - .find(|entry| entry.r#type == GameCultServiceTrustAnchorRecord::TYPE) - .unwrap(), - )?, - runtime_presence_trust_anchor(&incumbent, &provider_anchor)? - ); - assert!( - restored - .iter() - .all(|entry| entry.r#type != IdunnRuntimeActivationRecord::TYPE - && entry.r#type != IdunnProcessWriteLeaseRecord::TYPE) - ); - assert!( - restored - .iter() - .any(|entry| entry.key == "unrelated" && entry.r#type == "test.unrelated") - ); - let idempotent_bytes = fs::read(&driver.projection_store)?; - driver.restore_admitted_expected_only( - &candidate, - &provider_anchor, - Some(&candidate_activation), - &incumbent, - &provider_anchor, - &activation, - Some(&lease), - )?; - assert_eq!(fs::read(&driver.projection_store)?, idempotent_bytes); - - let admitted_anchor = runtime_presence_trust_anchor(&incumbent, &provider_anchor)?; - let mut unknown_expected = incumbent.clone(); - unknown_expected.incarnation_id = "unknown-incarnation".into(); - let mut unknown_anchor = admitted_anchor.clone(); - unknown_anchor.runtime_id = "unknown-runtime".into(); - unknown_anchor.validate()?; - let mut unknown_activation = activation.clone(); - unknown_activation.runtime_instance_id = digest('e'); - let mut unknown_lease = lease.clone(); - unknown_lease.lease_epoch += 1; - let substitutions = [ - CultCacheEnvelope { - key: incumbent.target.clone(), - r#type: IdunnExpectedIncarnationRecord::TYPE.into(), - payload: unknown_expected.canonical_bytes()?, - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some(IDUNN_EXPECTED_INCARNATION_SCHEMA.into()), - }, - CultCacheEnvelope { - key: admitted_anchor.trust_anchor_id.clone(), - r#type: GameCultServiceTrustAnchorRecord::TYPE.into(), - payload: rmp_serde::to_vec(&unknown_anchor)?, - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some(GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into()), - }, - CultCacheEnvelope { - key: incumbent.target.clone(), - r#type: IdunnRuntimeActivationRecord::TYPE.into(), - payload: unknown_activation.canonical_bytes()?, - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA.into()), - }, - CultCacheEnvelope { - key: incumbent.target.clone(), - r#type: IdunnProcessWriteLeaseRecord::TYPE.into(), - payload: unknown_lease.canonical_bytes()?, - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into()), - }, - ]; - for substitution in substitutions { - fs::write(&driver.projection_store, &idempotent_bytes)?; - upsert_record(&driver.projection_store, substitution)?; - let before = fs::read(&driver.projection_store)?; - assert!( - driver - .restore_admitted_expected_only( - &candidate, - &provider_anchor, - Some(&candidate_activation), - &incumbent, - &provider_anchor, - &activation, - Some(&lease), - ) - .is_err() - ); - assert_eq!(fs::read(&driver.projection_store)?, before); - } - Ok(()) - } - - #[cfg(unix)] - #[test] - fn service_credential_sources_require_one_root_owned_0400_inode() -> Result<()> { - use std::os::unix::fs::{PermissionsExt, symlink}; - - let temp = tempfile::tempdir()?; - let root = temp.path().join("credentials"); - fs::create_dir(&root)?; - fs::set_permissions(&root, fs::Permissions::from_mode(0o700))?; - let source = root.join("token"); - fs::write(&source, b"secret")?; - fs::set_permissions(&source, fs::Permissions::from_mode(0o400))?; - let mut sources = BTreeMap::from([("SERVICE_TOKEN".into(), source.clone())]); - - validate_service_credential_sources(&sources)?; - - fs::set_permissions(&source, fs::Permissions::from_mode(0o600))?; - assert!(validate_service_credential_sources(&sources).is_err()); - fs::set_permissions(&source, fs::Permissions::from_mode(0o400))?; - - let hardlink = root.join("token-hardlink"); - fs::hard_link(&source, &hardlink)?; - assert!(validate_service_credential_sources(&sources).is_err()); - fs::remove_file(&hardlink)?; - - let symlink_path = root.join("token-symlink"); - symlink(&source, &symlink_path)?; - sources.insert("SERVICE_TOKEN".into(), symlink_path); - assert!(validate_service_credential_sources(&sources).is_err()); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn write_lease_revoke_is_exact_and_never_deletes_a_surprise() -> Result<()> { - let temp = tempfile::tempdir()?; - let path = temp.path().join("lease.cc"); - let driver = CultCacheWriteLeaseDriver::new("service", &path); - let (expected, activation, warming, provider_anchor) = authenticated_warming(temp.path())?; - let lease = lease(&expected, &activation, &warming); - let topology = topology_driver(temp.path(), "lease-projection"); - topology.publish_expected(&expected, &provider_anchor)?; - project_activation(&topology, &expected, &activation)?; - - let lease_sha256 = driver.grant(&expected, &activation, &warming, &lease)?; - assert_eq!(lease_sha256, lease.canonical_sha256()?); - assert!(driver.observe(&expected, &activation, &warming, &lease)?); - assert!( - !SingleFileMessagePackBackingStore::new(&topology.projection_store) - .pull_all_read_only_snapshot()? - .iter() - .any(|entry| entry.r#type == IdunnProcessWriteLeaseRecord::TYPE) - ); - assert_eq!( - topology.publish_process_write_lease(&expected, &activation, &lease)?, - lease_sha256 - ); - - let mut surprise = lease.clone(); - surprise.lease_epoch = 2; - assert!(driver.revoke_exact(Some(&surprise)).is_err()); - assert!(driver.observe(&expected, &activation, &warming, &lease)?); - - SingleFileMessagePackBackingStore::new(&path).with_read_only_shared_snapshot(|_| { - let denial = driver - .revoke_exact(Some(&lease)) - .expect_err("shared lifetime holder must deny without blocking"); - assert!( - denial - .to_string() - .contains("held by a shared-lock consumer") - ); - Ok(()) - })?; - assert!(driver.observe(&expected, &activation, &warming, &lease)?); - - driver.revoke_exact(Some(&lease))?; - assert!(driver.observe_empty()?); - topology.withdraw_process_write_lease(&expected, &activation, Some(&lease))?; - assert!( - !SingleFileMessagePackBackingStore::new(&topology.projection_store) - .pull_all_read_only_snapshot()? - .iter() - .any(|entry| entry.r#type == IdunnProcessWriteLeaseRecord::TYPE) - ); - topology.withdraw_process_write_lease(&expected, &activation, Some(&lease))?; - driver.revoke_exact(Some(&lease))?; - - SingleFileMessagePackBackingStore::new(&path).with_read_only_shared_snapshot( - |snapshot| { - assert!(snapshot.is_empty()); - let denial = driver - .grant(&expected, &activation, &warming, &lease) - .expect_err("shared lifetime holder must deny grant without blocking"); - assert!( - denial - .to_string() - .contains("held by a shared-lock consumer") - ); - Ok(()) - }, - )?; - assert!(driver.observe_empty()?); - assert_eq!( - driver.grant(&expected, &activation, &warming, &lease)?, - lease.canonical_sha256()? - ); - driver.revoke_exact(Some(&lease))?; - Ok(()) - } - - #[cfg(unix)] - #[test] - fn installed_release_is_root_owned_and_nonwritable() -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let temp = tempfile::tempdir()?; - let root = temp.path().join("release"); - fs::create_dir(&root)?; - let artifact = root.join("service"); - fs::write(&artifact, b"sealed")?; - fs::set_permissions(&artifact, fs::Permissions::from_mode(0o777))?; - harden_installed_release( - &root, - &[ArtifactReceipt { - artifact_id: "service".into(), - destination: PathBuf::from("service"), - sha256: sha256_id(b"sealed"), - size_bytes: 6, - executable: true, - }], - )?; - let root_metadata = fs::symlink_metadata(&root)?; - let artifact_metadata = fs::symlink_metadata(&artifact)?; - assert_eq!(root_metadata.uid(), 0); - assert_eq!(root_metadata.permissions().mode() & 0o777, 0o555); - assert_eq!(artifact_metadata.uid(), 0); - assert_eq!(artifact_metadata.permissions().mode() & 0o777, 0o555); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn runner_cache_is_created_once_for_one_exact_identity() -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - - let temp = tempfile::tempdir()?; - fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o700))?; - let cache = temp.path().join("cache"); - let identity = ProcessIdentity { - uid: 1000, - gid: 1000, - }; - ensure_runner_cache_root(&cache, identity)?; - let metadata = fs::symlink_metadata(&cache)?; - assert_eq!((metadata.uid(), metadata.gid()), (1000, 1000)); - assert_eq!(metadata.permissions().mode() & 0o777, 0o700); - assert!(ensure_runner_cache_root(&cache, identity).is_ok()); - assert!( - ensure_runner_cache_root( - &cache, - ProcessIdentity { - uid: 1001, - gid: 1001 - } - ) - .is_err() - ); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn runner_secret_is_root_owned_and_bound_to_the_runner_group() -> Result<()> { - use std::os::unix::ffi::OsStrExt; - use std::os::unix::fs::PermissionsExt; - - let temp = tempfile::tempdir()?; - fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o700))?; - let secret = temp.path().join("token"); - fs::write(&secret, b"secret")?; - let secret_c = std::ffi::CString::new(secret.as_os_str().as_bytes())?; - ensure!(unsafe { libc::lchown(secret_c.as_ptr(), 0, 1000) } == 0); - fs::set_permissions(&secret, fs::Permissions::from_mode(0o440))?; - let identity = ProcessIdentity { - uid: 1000, - gid: 1000, - }; - validate_runner_secret(&secret, identity)?; - fs::set_permissions(&secret, fs::Permissions::from_mode(0o444))?; - assert!(validate_runner_secret(&secret, identity).is_err()); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn exact_git_archive_becomes_root_owned_immutable_source_without_git_metadata() -> Result<()> { - use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink}; - - let temp = tempfile::tempdir()?; - let repository = temp.path().join("repository"); - fs::create_dir(&repository)?; - git_at(&repository, &["init", "--initial-branch=main"])?; - git_at(&repository, &["config", "user.name", "Idunn Test"])?; - git_at( - &repository, - &["config", "user.email", "idunn-test@example.invalid"], - )?; - fs::write(repository.join("deployment.toml"), b"target = 'test'\n")?; - let script = repository.join("build.sh"); - fs::write(&script, b"#!/bin/sh\nexit 0\n")?; - fs::set_permissions(&script, fs::Permissions::from_mode(0o755))?; - fs::create_dir(repository.join("links"))?; - symlink("../deployment.toml", repository.join("links/deployment"))?; - git_at(&repository, &["add", "--all"])?; - git_at(&repository, &["commit", "-m", "fixture"])?; - let revision = git_at(&repository, &["rev-parse", "HEAD"])?; - - let parent = temp.path().join("transaction"); - fs::create_dir(&parent)?; - fs::set_permissions(&parent, fs::Permissions::from_mode(0o700))?; - let destination = parent.join("source"); - prepare_frozen_source_destination(&destination)?; - let driver = GitSourceDriver::new( - temp.path().join("source-cache"), - temp.path().join("frozen-source"), - None, - ); - driver.git_archive_into(&repository, &revision, None, &destination)?; - driver.git_archive_into( - &repository, - &revision, - Some(Path::new("vendor/fixture")), - &destination, - )?; - harden_frozen_source(&destination)?; - - assert!(!destination.join(".git").exists()); - assert_eq!( - fs::symlink_metadata(destination.join("deployment.toml"))? - .permissions() - .mode() - & 0o777, - 0o444 - ); - let script_metadata = fs::symlink_metadata(destination.join("build.sh"))?; - assert_eq!(script_metadata.uid(), 0); - assert_eq!(script_metadata.permissions().mode() & 0o777, 0o555); - assert!(destination.join("vendor/fixture/deployment.toml").is_file()); - validate_frozen_source_symlink(&destination, &destination.join("links/deployment"))?; - validate_frozen_source(&destination)?; - let digest = frozen_source_sha256(&destination)?; - let recipe = destination.join("deployment.toml"); - fs::set_permissions(&recipe, fs::Permissions::from_mode(0o644))?; - assert!(validate_frozen_source(&destination).is_err()); - fs::set_permissions(&recipe, fs::Permissions::from_mode(0o444))?; - fs::write(&recipe, b"target = 'changed'\n")?; - assert_ne!(frozen_source_sha256(&destination)?, digest); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn frozen_source_rejects_a_symlink_that_escapes_the_transaction_tree() -> Result<()> { - use std::os::unix::fs::{PermissionsExt, symlink}; - - let temp = tempfile::tempdir()?; - let parent = temp.path().join("transaction"); - fs::create_dir(&parent)?; - fs::set_permissions(&parent, fs::Permissions::from_mode(0o700))?; - let destination = parent.join("source"); - prepare_frozen_source_destination(&destination)?; - symlink("../../outside", destination.join("escape"))?; - assert!(harden_frozen_source(&destination).is_err()); - Ok(()) - } -} diff --git a/crates/idunn-daemon/src/lib.rs b/crates/idunn-daemon/src/lib.rs deleted file mode 100644 index 7899c59..0000000 --- a/crates/idunn-daemon/src/lib.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub mod control_plane; -pub mod deployment; -pub mod deployment_plan; -pub mod drivers; -pub mod provisioning; diff --git a/crates/idunn-daemon/src/main.rs b/crates/idunn-daemon/src/main.rs deleted file mode 100644 index e7bd0a5..0000000 --- a/crates/idunn-daemon/src/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() -> anyhow::Result<()> { - idunn_daemon::control_plane::run(std::env::args().skip(1)) -} diff --git a/crates/idunn-daemon/src/provisioning.rs b/crates/idunn-daemon/src/provisioning.rs deleted file mode 100644 index 8ae58a9..0000000 --- a/crates/idunn-daemon/src/provisioning.rs +++ /dev/null @@ -1,2455 +0,0 @@ -use anyhow::{Context, Result, anyhow, bail}; -use cultcache_rs::{ - CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, -}; -use cultnet_rs::{ - GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, GameCultProviderHealthIdentity, - GameCultServiceTrustAnchorRecord, IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA, - IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE, - IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, IDUNN_DEPLOYMENT_BRAKE_AUTHORITY, - IDUNN_DEPLOYMENT_BRAKE_ID, IDUNN_DEPLOYMENT_BRAKE_SCHEMA, IDUNN_DEPLOYMENT_BRAKE_SCOPE, - IDUNN_DEPLOYMENT_RELEASE_PURPOSE, IDUNN_LIFECYCLE_BRAKE_AUTHORITY, IDUNN_LIFECYCLE_BRAKE_SCHEMA, - IDUNN_LIFECYCLE_BRAKE_SCOPE, IdunnDaemonHealthTrustBindingRecord, - IdunnDeploymentBrakeObservation, IdunnDeploymentBrakeOperatorIdentity, - IdunnDeploymentBrakeRecord, IdunnDeploymentBrakeReleasePurpose, IdunnLifecycleBrakeObservation, - IdunnLifecycleBrakeRecord, IdunnServiceIdentity, OdinTopologyIdentity, ServiceIdentityProfile, - ServiceIdentityTrustAnchor, derive_service_identity_id, enroll_service_identity_at, - evaluate_idunn_continuity_restart, evaluate_idunn_deployment_brake, - export_service_identity_trust_anchor, open_service_identity_at, -}; -use std::collections::{BTreeMap, BTreeSet}; -use std::path::{Path, PathBuf}; - -trait RootDistributionDocument: DatabaseEntry { - fn root_key(&self) -> &str; -} - -impl RootDistributionDocument for IdunnDaemonHealthTrustBindingRecord { - fn root_key(&self) -> &str { - &self.binding_id - } -} - -impl RootDistributionDocument for GameCultServiceTrustAnchorRecord { - fn root_key(&self) -> &str { - &self.trust_anchor_id - } -} - -pub fn run(args: impl IntoIterator) -> Result<()> { - let mut args = args.into_iter(); - let command = args.next().ok_or_else(|| anyhow!(usage()))?; - let options = parse_options(args)?; - match command.as_str() { - "enroll-provider-health-identity" => { - let public_key = enroll_provider_health_identity(&options)?; - println!("{public_key}"); - } - "provider-health-public-key" => { - let public_key = provider_health_public_key(&options)?; - println!("{public_key}"); - } - "export-provider-health-public-anchor" => export_identity_anchor::< - GameCultProviderHealthIdentity, - >( - &options, "provider health public anchor" - )?, - "enroll-idunn-identity" => enroll_identity::(&options)?, - "export-idunn-public-anchor" => { - export_identity_anchor::(&options, "Idunn public anchor")? - } - "enroll-odin-topology-identity" => enroll_identity::(&options)?, - "export-odin-topology-public-anchor" => { - export_identity_anchor::(&options, "Odin topology public anchor")? - } - "enroll-deployment-brake-operator" => { - enroll_identity::(&options)? - } - "export-deployment-brake-operator-anchor" => { - export_identity_anchor::( - &options, - "deployment brake operator anchor", - )? - } - "deployment-brake-engage" => deployment_brake_engage(&options)?, - "deployment-brake-release" => deployment_brake_release(&options)?, - "deployment-brake-status" => deployment_brake_status(&options)?, - "lifecycle-brake-engage" => lifecycle_brake_engage(&options)?, - "lifecycle-brake-release" => lifecycle_brake_release(&options)?, - "lifecycle-brake-status" => lifecycle_brake_status(&options)?, - "create-daemon-health-trust-binding" => create_health_binding(&options)?, - "add-daemon-health-trust-binding" => add_health_binding(&options)?, - "require-daemon-health-release-binding" => require_health_binding_release(&options)?, - "rotate-daemon-health-trust-signer" => rotate_health_binding_signer(&options)?, - "validate-daemon-health-trust-binding" => { - require_only(&options, &["input"])?; - validate_health_binding_store(&path(&options, "input")?)?; - } - "create-provider-projection-trust-anchor" => create_projection_anchor(&options)?, - "validate-provider-projection-trust-anchor" => validate_projection_anchor(&options)?, - _ => bail!("unknown command {command:?}\n{}", usage()), - } - Ok(()) -} - -fn enroll_identity(options: &BTreeMap) -> Result<()> { - require_only(options, &["private-store"])?; - enroll_service_identity_at::

(&path(options, "private-store")?)?; - Ok(()) -} - -fn export_identity_anchor( - options: &BTreeMap, - label: &str, -) -> Result<()> { - require_only(options, &["private-store", "public-anchor"])?; - let private = path(options, "private-store")?; - let public = path(options, "public-anchor")?; - reject_alias(&private, &public)?; - refuse_existing(&public, label)?; - let signer = open_service_identity_at::

(&private)?; - export_service_identity_trust_anchor(&signer, &public)?; - Ok(()) -} - -fn enroll_provider_health_identity(options: &BTreeMap) -> Result { - require_only(options, &["private-store"])?; - let signer = enroll_service_identity_at::(&path( - options, - "private-store", - )?)?; - encode_public_key(&signer.entry().public_key) -} - -fn provider_health_public_key(options: &BTreeMap) -> Result { - require_only(options, &["private-store"])?; - let signer = open_service_identity_at::(&path( - options, - "private-store", - )?)?; - encode_public_key(&signer.entry().public_key) -} - -fn deployment_brake_engage(options: &BTreeMap) -> Result<()> { - require_only( - options, - &[ - "store", - "runtime-id", - "owner", - "reason", - "observed-at-unix-millis", - ], - )?; - let observed = parse_u64(options, "observed-at-unix-millis")?; - let record = IdunnDeploymentBrakeRecord { - schema_version: IDUNN_DEPLOYMENT_BRAKE_SCHEMA.into(), - brake_id: IDUNN_DEPLOYMENT_BRAKE_ID.into(), - authority: IDUNN_DEPLOYMENT_BRAKE_AUTHORITY.into(), - runtime_id: required(options, "runtime-id")?.into(), - status: "engaged".into(), - scope: IDUNN_DEPLOYMENT_BRAKE_SCOPE.into(), - reason: required(options, "reason")?.into(), - observed_at_unix_millis: observed, - expires_at_unix_millis: None, - authorization_id: None, - authorization_purpose: None, - authorized_release_id: None, - authorized_deployment_id: None, - authorized_by: None, - authorization_issued_at_unix_millis: None, - authorization_expires_at_unix_millis: None, - signature_algorithm: None, - signature: None, - private_state_exposed: false, - updated_by: required(options, "owner")?.into(), - }; - record.validate()?; - replace_brake(&path(options, "store")?, record, observed) -} - -fn deployment_brake_release(options: &BTreeMap) -> Result<()> { - require_only( - options, - &[ - "store", - "private-store", - "runtime-id", - "owner", - "reason", - "authorization-id", - "release-id", - "deployment-id", - "issued-at-unix-millis", - "expires-at-unix-millis", - ], - )?; - let issued = parse_u64(options, "issued-at-unix-millis")?; - let expires = parse_u64(options, "expires-at-unix-millis")?; - let signer = open_service_identity_at::(&path( - options, - "private-store", - )?)?; - let mut record = IdunnDeploymentBrakeRecord { - schema_version: IDUNN_DEPLOYMENT_BRAKE_SCHEMA.into(), - brake_id: IDUNN_DEPLOYMENT_BRAKE_ID.into(), - authority: IDUNN_DEPLOYMENT_BRAKE_AUTHORITY.into(), - runtime_id: required(options, "runtime-id")?.into(), - status: "released".into(), - scope: IDUNN_DEPLOYMENT_BRAKE_SCOPE.into(), - reason: required(options, "reason")?.into(), - observed_at_unix_millis: issued, - expires_at_unix_millis: Some(expires), - authorization_id: Some(required(options, "authorization-id")?.into()), - authorization_purpose: Some(IDUNN_DEPLOYMENT_RELEASE_PURPOSE.into()), - authorized_release_id: Some(required(options, "release-id")?.into()), - authorized_deployment_id: Some(required(options, "deployment-id")?.into()), - authorized_by: Some(signer.trust_anchor()?.identity_id), - authorization_issued_at_unix_millis: Some(issued), - authorization_expires_at_unix_millis: Some(expires), - signature_algorithm: Some("ed25519".into()), - signature: None, - private_state_exposed: false, - updated_by: required(options, "owner")?.into(), - }; - record.signature = Some( - signer - .sign::(&rmp_serde::to_vec(&record)?) - .signature, - ); - record.validate()?; - replace_brake(&path(options, "store")?, record, issued) -} - -fn deployment_brake_status(options: &BTreeMap) -> Result<()> { - allow_only( - options, - &[ - "store", - "operator-anchor", - "runtime-id", - "release-id", - "deployment-id", - "now-unix-millis", - ], - )?; - let exact_actuation_fields = ["release-id", "deployment-id", "now-unix-millis"]; - let exact_actuation_field_count = exact_actuation_fields - .into_iter() - .filter(|field| options.contains_key(*field)) - .count(); - if exact_actuation_field_count != 0 - && exact_actuation_field_count != exact_actuation_fields.len() - { - bail!("exact deployment-brake actuation validation requires release, deployment, and time"); - } - let record = read_brake(&path(options, "store")?)?; - if record.runtime_id != required(options, "runtime-id")? { - bail!("deployment brake belongs to another runtime") - } - if record.status == "engaged" { - if exact_actuation_field_count != 0 { - bail!("engaged deployment brake denies exact actuation validation"); - } - println!( - "engaged runtime={} scope={} owner={} reason={}", - record.runtime_id, record.scope, record.updated_by, record.reason - ); - return Ok(()); - } - let anchor = read_operator_anchor(&path(options, "operator-anchor")?)?; - evaluate_idunn_deployment_brake( - IdunnDeploymentBrakeObservation::Present(&record), - &anchor, - required(options, "runtime-id")?, - required(options, "release-id")?, - required(options, "deployment-id")?, - parse_u64(options, "now-unix-millis")?, - ) - .map_err(|d| anyhow!("deployment brake denied actuation: {d:?}"))?; - println!( - "released runtime={} release={} deployment={} owner={}", - record.runtime_id, - record.authorized_release_id.unwrap(), - record.authorized_deployment_id.unwrap(), - record.updated_by - ); - Ok(()) -} - -fn lifecycle_brake_engage(options: &BTreeMap) -> Result<()> { - require_only( - options, - &[ - "store", - "runtime-id", - "target", - "reason", - "updated-at-unix-millis", - ], - )?; - let updated = parse_u64(options, "updated-at-unix-millis")?; - let record = IdunnLifecycleBrakeRecord { - schema_version: IDUNN_LIFECYCLE_BRAKE_SCHEMA.into(), - authority: IDUNN_LIFECYCLE_BRAKE_AUTHORITY.into(), - runtime_id: required(options, "runtime-id")?.into(), - target: required(options, "target")?.into(), - scope: IDUNN_LIFECYCLE_BRAKE_SCOPE.into(), - status: "engaged".into(), - reason: required(options, "reason")?.into(), - updated_at_unix_millis: updated, - released_until_unix_millis: None, - }; - replace_lifecycle_brake(&path(options, "store")?, record) -} - -fn lifecycle_brake_release(options: &BTreeMap) -> Result<()> { - allow_only( - options, - &[ - "store", - "runtime-id", - "target", - "reason", - "updated-at-unix-millis", - "released-until-unix-millis", - ], - )?; - let updated = parse_u64(options, "updated-at-unix-millis")?; - let record = IdunnLifecycleBrakeRecord { - schema_version: IDUNN_LIFECYCLE_BRAKE_SCHEMA.into(), - authority: IDUNN_LIFECYCLE_BRAKE_AUTHORITY.into(), - runtime_id: required(options, "runtime-id")?.into(), - target: required(options, "target")?.into(), - scope: IDUNN_LIFECYCLE_BRAKE_SCOPE.into(), - status: "released".into(), - reason: required(options, "reason")?.into(), - updated_at_unix_millis: updated, - released_until_unix_millis: options - .get("released-until-unix-millis") - .map(|value| { - value - .parse() - .context("--released-until-unix-millis must be u64") - }) - .transpose()?, - }; - replace_lifecycle_brake(&path(options, "store")?, record) -} - -fn lifecycle_brake_status(options: &BTreeMap) -> Result<()> { - require_only( - options, - &["store", "runtime-id", "target", "now-unix-millis"], - )?; - let runtime_id = lifecycle_identifier(options, "runtime-id")?; - let target = lifecycle_identifier(options, "target")?; - let now = parse_u64(options, "now-unix-millis")?; - match read_lifecycle_brake(&path(options, "store")?)? { - None => { - evaluate_idunn_continuity_restart( - IdunnLifecycleBrakeObservation::Missing, - runtime_id, - target, - now, - ) - .map_err(|denial| anyhow!("lifecycle brake denied continuity restart: {denial:?}"))?; - println!("allowed runtime={runtime_id} target={target} brake=absent"); - } - Some(record) => { - evaluate_idunn_continuity_restart( - IdunnLifecycleBrakeObservation::Present(&record), - runtime_id, - target, - now, - ) - .map_err(|denial| anyhow!("lifecycle brake denied continuity restart: {denial:?}"))?; - if let Some(expires) = record.released_until_unix_millis { - println!( - "allowed runtime={} target={} brake=released expires={expires}", - record.runtime_id, record.target - ); - } else { - println!( - "allowed runtime={} target={} brake=released expires=never", - record.runtime_id, record.target - ); - } - } - } - Ok(()) -} - -fn replace_lifecycle_brake(path: &Path, record: IdunnLifecycleBrakeRecord) -> Result<()> { - record.validate()?; - let store = SingleFileMessagePackBackingStore::new(path); - let entries = store.pull_all_read_only_snapshot()?; - let current = match entries.as_slice() { - [] => None, - [entry] - if entry.r#type == IdunnLifecycleBrakeRecord::TYPE - && entry.schema_id.as_deref() == Some(IDUNN_LIFECYCLE_BRAKE_SCHEMA) => - { - let current_record = IdunnLifecycleBrakeRecord::decode_canonical(&entry.payload)?; - if entry.key != current_record.target { - bail!("lifecycle brake envelope key does not match its target"); - } - if current_record.runtime_id != record.runtime_id - || current_record.target != record.target - { - bail!("lifecycle brake store is bound to another runtime or target"); - } - if record.updated_at_unix_millis <= current_record.updated_at_unix_millis { - bail!("lifecycle brake update time must advance"); - } - Some(entry.clone()) - } - _ => bail!("lifecycle brake store is corrupt or ambiguous"), - }; - let next = typed_envelope( - &record.target, - &record, - IDUNN_LIFECYCLE_BRAKE_SCHEMA, - record.updated_at_unix_millis, - )?; - if !store.compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: IdunnLifecycleBrakeRecord::TYPE.into(), - key: record.target.clone(), - current, - }], - &[next], - )? { - bail!("lifecycle brake changed during transition"); - } - Ok(()) -} - -fn read_lifecycle_brake(path: &Path) -> Result> { - if !path.exists() { - return Ok(None); - } - let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; - let entry = match entries.as_slice() { - [] => return Ok(None), - [entry] => entry, - _ => bail!("lifecycle brake store is ambiguous"), - }; - if entry.r#type != IdunnLifecycleBrakeRecord::TYPE - || entry.schema_id.as_deref() != Some(IDUNN_LIFECYCLE_BRAKE_SCHEMA) - { - bail!("lifecycle brake store contains a foreign record"); - } - let record = IdunnLifecycleBrakeRecord::decode_canonical(&entry.payload)?; - if entry.key != record.target { - bail!("lifecycle brake envelope key does not match its target"); - } - Ok(Some(record)) -} - -fn lifecycle_identifier<'a>(options: &'a BTreeMap, name: &str) -> Result<&'a str> { - let value = required(options, name)?; - if value.trim().is_empty() || value.len() > 256 || value.chars().any(char::is_control) { - bail!("--{name} is empty, oversized, or contains control characters"); - } - Ok(value) -} - -fn replace_brake(path: &Path, record: IdunnDeploymentBrakeRecord, millis: u64) -> Result<()> { - let store = SingleFileMessagePackBackingStore::new(path); - let entries = store.pull_all_read_only_snapshot()?; - let current = match entries.as_slice() { - [] => None, - [entry] - if entry.r#type == IdunnDeploymentBrakeRecord::TYPE - && entry.key == IDUNN_DEPLOYMENT_BRAKE_ID => - { - Some(entry.clone()) - } - _ => bail!("deployment brake store is corrupt or ambiguous"), - }; - let next = typed_envelope( - IDUNN_DEPLOYMENT_BRAKE_ID, - &record, - IDUNN_DEPLOYMENT_BRAKE_SCHEMA, - millis, - )?; - if !store.compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: IdunnDeploymentBrakeRecord::TYPE.into(), - key: IDUNN_DEPLOYMENT_BRAKE_ID.into(), - current, - }], - &[next], - )? { - bail!("deployment brake changed during transition"); - } - Ok(()) -} - -fn read_brake(path: &Path) -> Result { - let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; - let [entry] = entries.as_slice() else { - bail!("deployment brake is missing or ambiguous") - }; - if entry.r#type != IdunnDeploymentBrakeRecord::TYPE - || entry.key != IDUNN_DEPLOYMENT_BRAKE_ID - || entry.schema_id.as_deref() != Some(IDUNN_DEPLOYMENT_BRAKE_SCHEMA) - { - bail!("deployment brake is foreign") - } - let record: IdunnDeploymentBrakeRecord = rmp_serde::from_slice(&entry.payload)?; - if rmp_serde::to_vec(&record)? != entry.payload { - bail!("deployment brake is noncanonical") - } - record.validate()?; - Ok(record) -} - -fn read_operator_anchor(path: &Path) -> Result { - let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; - let [entry] = entries.as_slice() else { - bail!("operator anchor is missing or ambiguous") - }; - if entry.r#type != IdunnDeploymentBrakeOperatorIdentity::TRUST_ANCHOR_TYPE - || entry.key != IdunnDeploymentBrakeOperatorIdentity::TRUST_ANCHOR_KEY - { - bail!("operator anchor is foreign") - } - Ok(rmp_serde::from_slice(&entry.payload)?) -} - -fn validate_health_binding_store(path: &Path) -> Result<()> { - let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; - validated_health_bindings(&entries)?; - Ok(()) -} - -fn validated_health_bindings( - entries: &[CultCacheEnvelope], -) -> Result> { - if entries.is_empty() { - bail!("daemon health trust store is empty"); - } - let mut keys = BTreeSet::new(); - let mut tuples = BTreeSet::new(); - let mut bindings = Vec::with_capacity(entries.len()); - for envelope in entries { - if envelope.r#type != IdunnDaemonHealthTrustBindingRecord::TYPE - || envelope.schema_id.as_deref() != Some(IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA) - { - bail!("trust store contains an alien type or schema"); - } - let binding: IdunnDaemonHealthTrustBindingRecord = - rmp_serde::from_slice(&envelope.payload)?; - if rmp_serde::to_vec(&binding)? != envelope.payload || envelope.key != binding.binding_id { - bail!("trust store contains a noncanonical or mismatched binding"); - } - binding.validate()?; - if !keys.insert(binding.binding_id.clone()) - || !tuples.insert(( - binding.daemon_id.clone(), - binding.health_contract.clone(), - binding.source_runtime_id.clone(), - )) - { - bail!("trust store contains a duplicate binding id or tuple"); - } - bindings.push(binding); - } - Ok(bindings) -} - -fn create_health_binding(options: &BTreeMap) -> Result<()> { - let record = health_binding(options)?; - write_new_typed( - &path(options, "output")?, - &record.binding_id, - &record, - IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, - record.bound_at_unix_millis, - ) -} - -fn health_binding( - options: &BTreeMap, -) -> Result { - require_only( - options, - &[ - "output", - "binding-id", - "daemon", - "health-contract", - "source-runtime", - "signer-public-key-hex", - "bound-at-unix-millis", - "release-binding-required", - ], - )?; - let public_key = decode_public_key(required(options, "signer-public-key-hex")?)?; - let record = IdunnDaemonHealthTrustBindingRecord { - schema_version: IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA.into(), - binding_id: required(options, "binding-id")?.into(), - daemon_id: required(options, "daemon")?.into(), - health_contract: required(options, "health-contract")?.into(), - source_runtime_id: required(options, "source-runtime")?.into(), - signer_identity_id: derive_service_identity_id::( - &public_key, - )?, - signer_public_key: public_key, - binding_authority: "root".into(), - bound_at_unix_millis: parse_u64(options, "bound-at-unix-millis")?, - release_binding_required: parse_bool(options, "release-binding-required")?, - private_state_exposed: false, - }; - record.validate()?; - Ok(record) -} - -fn add_health_binding(options: &BTreeMap) -> Result<()> { - let record = health_binding(options)?; - let output = path(options, "output")?; - let store = SingleFileMessagePackBackingStore::new(&output); - let existing = store.pull_all_read_only_snapshot()?; - if existing.is_empty() { - bail!("trust store must already exist; create the first binding explicitly"); - } - let mut keys = BTreeSet::new(); - let mut tuples = BTreeSet::new(); - let mut expected = Vec::with_capacity(existing.len() + 1); - for envelope in existing { - if envelope.r#type != IdunnDaemonHealthTrustBindingRecord::TYPE - || envelope.schema_id.as_deref() != Some(IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA) - { - bail!("trust store contains an alien type or schema"); - } - let binding: IdunnDaemonHealthTrustBindingRecord = - rmp_serde::from_slice(&envelope.payload)?; - if rmp_serde::to_vec(&binding)? != envelope.payload || envelope.key != binding.binding_id { - bail!("trust store contains a noncanonical or mismatched binding"); - } - binding.validate()?; - if !keys.insert(binding.binding_id.clone()) { - bail!("trust store contains duplicate binding ids"); - } - if !tuples.insert(( - binding.daemon_id, - binding.health_contract, - binding.source_runtime_id, - )) { - bail!("trust store contains duplicate daemon/contract/runtime tuples"); - } - expected.push(CultCacheExpectedEnvelope { - r#type: envelope.r#type.clone(), - key: envelope.key.clone(), - current: Some(envelope), - }); - } - if keys.contains(&record.binding_id) { - bail!("binding id already exists"); - } - if tuples.contains(&( - record.daemon_id.clone(), - record.health_contract.clone(), - record.source_runtime_id.clone(), - )) { - bail!("daemon/contract/runtime tuple already exists"); - } - expected.push(CultCacheExpectedEnvelope { - r#type: IdunnDaemonHealthTrustBindingRecord::TYPE.into(), - key: record.binding_id.clone(), - current: None, - }); - let envelope = typed_envelope( - &record.binding_id, - &record, - IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, - record.bound_at_unix_millis, - )?; - if !store.compare_exchange(&expected, &[envelope])? { - bail!("trust store changed during validated append"); - } - Ok(()) -} - -fn require_health_binding_release(options: &BTreeMap) -> Result<()> { - require_only( - options, - &[ - "store", - "binding-id", - "daemon", - "health-contract", - "source-runtime", - "signer-public-key-hex", - ], - )?; - let store_path = path(options, "store")?; - let store = SingleFileMessagePackBackingStore::new(&store_path); - let entries = store.pull_all_read_only_snapshot()?; - let signer_public_key = decode_public_key(required(options, "signer-public-key-hex")?)?; - require_health_binding_release_from_snapshot( - &store, - entries, - required(options, "binding-id")?, - required(options, "daemon")?, - required(options, "health-contract")?, - required(options, "source-runtime")?, - &signer_public_key, - ) -} - -fn require_health_binding_release_from_snapshot( - store: &SingleFileMessagePackBackingStore, - entries: Vec, - binding_id: &str, - daemon_id: &str, - health_contract: &str, - source_runtime_id: &str, - signer_public_key: &[u8], -) -> Result<()> { - let bindings = validated_health_bindings(&entries)?; - let target_index = bindings - .iter() - .position(|binding| binding.binding_id == binding_id) - .ok_or_else(|| anyhow!("named daemon health trust binding does not exist"))?; - let current = &bindings[target_index]; - if current.daemon_id != daemon_id - || current.health_contract != health_contract - || current.source_runtime_id != source_runtime_id - || current.signer_public_key != signer_public_key - { - bail!("named daemon health trust binding does not match the expected immutable fields"); - } - if current.release_binding_required { - return Ok(()); - } - - let mut next = current.clone(); - next.release_binding_required = true; - next.validate()?; - let mut replacement = entries[target_index].clone(); - replacement.payload = rmp_serde::to_vec(&next)?; - let expected = entries - .into_iter() - .map(|envelope| CultCacheExpectedEnvelope { - r#type: envelope.r#type.clone(), - key: envelope.key.clone(), - current: Some(envelope), - }) - .collect::>(); - if !store.compare_exchange(&expected, &[replacement])? { - let latest_entries = store.pull_all_read_only_snapshot()?; - let latest_bindings = validated_health_bindings(&latest_entries)?; - if let Some(latest) = latest_bindings - .iter() - .find(|binding| binding.binding_id == binding_id) - && latest.daemon_id == daemon_id - && latest.health_contract == health_contract - && latest.source_runtime_id == source_runtime_id - && latest.signer_public_key == signer_public_key - && latest.release_binding_required - { - return Ok(()); - } - bail!("daemon health trust store changed during release-binding transition"); - } - Ok(()) -} - -fn rotate_health_binding_signer(options: &BTreeMap) -> Result<()> { - require_only( - options, - &[ - "output", - "binding-id", - "signer-public-key-hex", - "bound-at-unix-millis", - ], - )?; - let output = path(options, "output")?; - validate_health_binding_store(&output)?; - let store = SingleFileMessagePackBackingStore::new(&output); - let existing = store.pull_all_read_only_snapshot()?; - let binding_id = required(options, "binding-id")?; - let public_key = decode_public_key(required(options, "signer-public-key-hex")?)?; - let bound_at = parse_u64(options, "bound-at-unix-millis")?; - let mut expected = Vec::with_capacity(existing.len()); - let mut replacement = None; - for envelope in existing { - let binding: IdunnDaemonHealthTrustBindingRecord = - rmp_serde::from_slice(&envelope.payload)?; - if binding.binding_id == binding_id { - if bound_at <= binding.bound_at_unix_millis { - bail!("rotated signer binding time must advance"); - } - if binding.signer_public_key == public_key { - bail!("rotated signer must differ from the current signer"); - } - let mut rotated = binding.clone(); - rotated.signer_identity_id = - derive_service_identity_id::(&public_key)?; - rotated.signer_public_key = public_key.clone(); - rotated.bound_at_unix_millis = bound_at; - rotated.validate()?; - replacement = Some(rotated); - } - expected.push(CultCacheExpectedEnvelope { - r#type: envelope.r#type.clone(), - key: envelope.key.clone(), - current: Some(envelope), - }); - } - let replacement = replacement.ok_or_else(|| anyhow!("binding id does not exist"))?; - let envelope = typed_envelope( - &replacement.binding_id, - &replacement, - IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, - bound_at, - )?; - if !store.compare_exchange(&expected, &[envelope])? { - bail!("trust store changed during validated signer rotation"); - } - validate_health_binding_store(&output) -} - -fn typed_envelope( - key: &str, - value: &T, - schema: &str, - millis: u64, -) -> Result { - let stored_at = chrono::DateTime::from_timestamp_millis(i64::try_from(millis)?) - .ok_or_else(|| anyhow!("document timestamp is out of range"))? - .to_rfc3339(); - Ok(CultCacheEnvelope { - key: key.into(), - r#type: T::TYPE.into(), - payload: rmp_serde::to_vec(value)?, - stored_at, - schema_id: Some(schema.into()), - }) -} - -fn create_projection_anchor(options: &BTreeMap) -> Result<()> { - require_only( - options, - &[ - "output", - "trust-anchor-id", - "runtime-id", - "idunn-public-anchor", - "bound-at-unix-millis", - "expires-at-unix-millis", - ], - )?; - let output = path(options, "output")?; - let low_path = path(options, "idunn-public-anchor")?; - reject_alias(&output, &low_path)?; - let low = read_low_level_idunn_anchor(&low_path)?; - let bound = parse_u64(options, "bound-at-unix-millis")?; - let record = GameCultServiceTrustAnchorRecord { - schema_version: GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(), - trust_anchor_id: required(options, "trust-anchor-id")?.into(), - service_id: "idunn".into(), - runtime_id: required(options, "runtime-id")?.into(), - signer_identity_id: derive_service_identity_id::(&low.public_key)?, - signer_public_key: low.public_key, - signature_algorithm: "ed25519".into(), - signing_purpose: IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE.into(), - signed_schema: IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA.into(), - binding_authority: "root".into(), - bound_at_unix_millis: bound, - expires_at_unix_millis: options - .get("expires-at-unix-millis") - .map(|value| value.parse().context("expires-at-unix-millis must be u64")) - .transpose()?, - private_state_exposed: false, - }; - record.validate()?; - write_new_typed( - &output, - &record.trust_anchor_id, - &record, - GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, - bound, - ) -} - -fn validate_projection_anchor(options: &BTreeMap) -> Result<()> { - require_only(options, &["input", "idunn-public-anchor"])?; - let input = path(options, "input")?; - let low_path = path(options, "idunn-public-anchor")?; - reject_alias(&input, &low_path)?; - let record = read_typed::( - &input, - GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, - )?; - record.validate()?; - let low = read_low_level_idunn_anchor(&low_path)?; - if record.signer_public_key != low.public_key || record.signer_identity_id != low.identity_id { - bail!("projection trust anchor does not match the supplied Idunn public anchor"); - } - Ok(()) -} - -fn write_new_typed( - path: &Path, - key: &str, - value: &T, - schema: &str, - millis: u64, -) -> Result<()> { - refuse_existing(path, "root distribution document")?; - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } - let stored_at = chrono::DateTime::from_timestamp_millis( - i64::try_from(millis).context("document timestamp is out of range")?, - ) - .ok_or_else(|| anyhow!("document timestamp is out of range"))? - .to_rfc3339(); - let envelope = CultCacheEnvelope { - key: key.into(), - r#type: T::TYPE.into(), - payload: rmp_serde::to_vec(value)?, - stored_at, - schema_id: Some(schema.into()), - }; - let created = SingleFileMessagePackBackingStore::new(path).compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: T::TYPE.into(), - key: key.into(), - current: None, - }], - &[envelope], - )?; - if !created { - bail!("root distribution document lost atomic create race; refusing replacement"); - } - Ok(()) -} - -fn read_typed(path: &Path, schema: &str) -> Result { - let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; - let [entry] = entries.as_slice() else { - bail!("root distribution file must contain exactly one document"); - }; - if entry.r#type != T::TYPE || entry.schema_id.as_deref() != Some(schema) { - bail!("root distribution document has the wrong type or schema"); - } - let value: T = rmp_serde::from_slice(&entry.payload).context("decoding typed root document")?; - if rmp_serde::to_vec(&value)? != entry.payload { - bail!("root distribution document is not canonical positional MessagePack"); - } - if entry.key != value.root_key() { - bail!("root distribution envelope key does not match its typed document"); - } - Ok(value) -} - -fn read_low_level_idunn_anchor(path: &Path) -> Result { - let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?; - let [entry] = entries.as_slice() else { - bail!("Idunn public anchor store must contain exactly one document"); - }; - if entry.r#type != IdunnServiceIdentity::TRUST_ANCHOR_TYPE - || entry.key != IdunnServiceIdentity::TRUST_ANCHOR_KEY - || entry.schema_id.as_deref() != Some(IdunnServiceIdentity::TRUST_ANCHOR_SCHEMA) - { - bail!("public anchor does not belong to the Idunn service identity profile"); - } - let anchor: ServiceIdentityTrustAnchor = rmp_serde::from_slice(&entry.payload)?; - if rmp_serde::to_vec(&anchor)? != entry.payload - || anchor.schema_version != IdunnServiceIdentity::TRUST_ANCHOR_SCHEMA - || anchor.identity_id - != derive_service_identity_id::(&anchor.public_key)? - { - bail!("Idunn public anchor is malformed or names the wrong key"); - } - Ok(anchor) -} - -fn parse_options(args: impl Iterator) -> Result> { - let mut args = args.peekable(); - let mut out = BTreeMap::new(); - while let Some(name) = args.next() { - let name = name - .strip_prefix("--") - .ok_or_else(|| anyhow!("expected --option, got {name:?}"))?; - if name.contains("seed") || name.contains("private-key") { - bail!("private seed/key input is forbidden; enroll a protected identity instead"); - } - let value = args - .next() - .ok_or_else(|| anyhow!("missing value for --{name}"))?; - if out.insert(name.into(), value).is_some() { - bail!("duplicate option --{name}"); - } - } - Ok(out) -} - -fn require_only(options: &BTreeMap, names: &[&str]) -> Result<()> { - for name in names { - required(options, name)?; - } - if let Some(name) = options.keys().find(|name| !names.contains(&name.as_str())) { - bail!("unsupported option --{name}"); - } - Ok(()) -} - -fn allow_only(options: &BTreeMap, names: &[&str]) -> Result<()> { - if let Some(name) = options.keys().find(|name| !names.contains(&name.as_str())) { - bail!("unsupported option --{name}"); - } - Ok(()) -} - -fn required<'a>(options: &'a BTreeMap, name: &str) -> Result<&'a str> { - options - .get(name) - .map(String::as_str) - .ok_or_else(|| anyhow!("missing --{name}")) -} - -fn path(options: &BTreeMap, name: &str) -> Result { - let value = required(options, name)?; - if value.trim().is_empty() { - bail!("--{name} must not be empty"); - } - Ok(PathBuf::from(value)) -} - -fn parse_u64(options: &BTreeMap, name: &str) -> Result { - required(options, name)? - .parse() - .with_context(|| format!("--{name} must be u64")) -} - -fn parse_bool(options: &BTreeMap, name: &str) -> Result { - match required(options, name)? { - "true" => Ok(true), - "false" => Ok(false), - _ => bail!("--{name} must be true or false"), - } -} - -fn decode_public_key(value: &str) -> Result> { - if value.len() != 64 - || !value - .bytes() - .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) - { - bail!("signer public key must be exactly 64 lowercase hexadecimal characters"); - } - (0..32) - .map(|index| u8::from_str_radix(&value[index * 2..index * 2 + 2], 16).map_err(Into::into)) - .collect() -} - -fn encode_public_key(value: &[u8]) -> Result { - if value.len() != 32 { - bail!("provider health public key must be exactly 32 bytes"); - } - const HEX: &[u8; 16] = b"0123456789abcdef"; - let mut encoded = String::with_capacity(64); - for byte in value { - encoded.push(HEX[(byte >> 4) as usize] as char); - encoded.push(HEX[(byte & 0x0f) as usize] as char); - } - Ok(encoded) -} - -fn refuse_existing(path: &Path, label: &str) -> Result<()> { - if path.exists() { - bail!( - "{label} {} already exists; replacement is forbidden", - path.display() - ); - } - Ok(()) -} - -fn reject_alias(first: &Path, second: &Path) -> Result<()> { - if normalized(first)? == normalized(second)? { - bail!("private/public or input/output paths must not alias"); - } - Ok(()) -} - -fn normalized(path: &Path) -> Result { - let absolute = if path.is_absolute() { - path.to_path_buf() - } else { - std::env::current_dir()?.join(path) - }; - let parent = absolute - .parent() - .ok_or_else(|| anyhow!("path has no parent"))?; - let parent = parent - .canonicalize() - .unwrap_or_else(|_| parent.to_path_buf()); - Ok(parent.join( - absolute - .file_name() - .ok_or_else(|| anyhow!("path has no filename"))?, - )) -} - -fn usage() -> &'static str { - "Usage: idunn-provision enroll-provider-health-identity --private-store \n idunn-provision provider-health-public-key --private-store \n idunn-provision export-provider-health-public-anchor --private-store --public-anchor \n idunn-provision enroll-idunn-identity --private-store \n idunn-provision export-idunn-public-anchor --private-store --public-anchor \n idunn-provision enroll-odin-topology-identity --private-store \n idunn-provision export-odin-topology-public-anchor --private-store --public-anchor \n idunn-provision enroll-deployment-brake-operator --private-store \n idunn-provision export-deployment-brake-operator-anchor --private-store --public-anchor \n idunn-provision deployment-brake-engage --store --runtime-id --owner --reason --observed-at-unix-millis \n idunn-provision deployment-brake-release --store --private-store --runtime-id --owner --reason --authorization-id --release-id --deployment-id --issued-at-unix-millis --expires-at-unix-millis \n idunn-provision deployment-brake-status --store --operator-anchor --runtime-id [--release-id --deployment-id --now-unix-millis ]\n idunn-provision lifecycle-brake-engage --store --runtime-id --target --reason --updated-at-unix-millis \n idunn-provision lifecycle-brake-release --store --runtime-id --target --reason --updated-at-unix-millis [--released-until-unix-millis ]\n idunn-provision lifecycle-brake-status --store --runtime-id --target --now-unix-millis \n idunn-provision create-daemon-health-trust-binding --output --binding-id --daemon --health-contract --source-runtime --signer-public-key-hex --bound-at-unix-millis --release-binding-required \n idunn-provision add-daemon-health-trust-binding --output --binding-id --daemon --health-contract --source-runtime --signer-public-key-hex --bound-at-unix-millis --release-binding-required \n idunn-provision require-daemon-health-release-binding --store --binding-id --daemon --health-contract --source-runtime --signer-public-key-hex \n idunn-provision rotate-daemon-health-trust-signer --output --binding-id --signer-public-key-hex --bound-at-unix-millis \n idunn-provision validate-daemon-health-trust-binding --input \n idunn-provision create-provider-projection-trust-anchor --output --trust-anchor-id --runtime-id --idunn-public-anchor --bound-at-unix-millis --expires-at-unix-millis \n idunn-provision validate-provider-projection-trust-anchor --input --idunn-public-anchor " -} - -#[cfg(test)] -mod tests { - use super::*; - use cultcache_rs::CacheBackingStore; - use tempfile::TempDir; - - fn invoke(args: &[&str]) -> Result<()> { - run(args.iter().map(|value| value.to_string())) - } - - fn replace_typed( - path: &Path, - key: &str, - schema: &str, - value: &T, - ) -> Result<()> { - std::fs::remove_file(path)?; - SingleFileMessagePackBackingStore::new(path).push(&CultCacheEnvelope { - key: key.into(), - r#type: T::TYPE.into(), - payload: rmp_serde::to_vec(value)?, - stored_at: "2026-07-19T20:00:00Z".into(), - schema_id: Some(schema.into()), - }) - } - - fn binding_args<'a>( - command: &'a str, - output: &'a str, - id: &'a str, - daemon: &'a str, - runtime: &'a str, - ) -> Vec<&'a str> { - vec![ - command, - "--output", - output, - "--binding-id", - id, - "--daemon", - daemon, - "--health-contract", - "provider.health", - "--source-runtime", - runtime, - "--signer-public-key-hex", - "1111111111111111111111111111111111111111111111111111111111111111", - "--bound-at-unix-millis", - "1784483100000", - "--release-binding-required", - "false", - ] - } - - const TEST_SIGNER_HEX: &str = - "1111111111111111111111111111111111111111111111111111111111111111"; - const WRONG_SIGNER_HEX: &str = - "2222222222222222222222222222222222222222222222222222222222222222"; - - fn write_test_binding( - command: &str, - store: &str, - id: &str, - daemon: &str, - runtime: &str, - ) -> Result<()> { - invoke(&binding_args(command, store, id, daemon, runtime)) - } - - fn require_test_binding( - store: &str, - id: &str, - daemon: &str, - contract: &str, - runtime: &str, - signer: &str, - ) -> Result<()> { - invoke(&[ - "require-daemon-health-release-binding", - "--store", - store, - "--binding-id", - id, - "--daemon", - daemon, - "--health-contract", - contract, - "--source-runtime", - runtime, - "--signer-public-key-hex", - signer, - ]) - } - - fn store_snapshot(path: &Path) -> Result> { - SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot() - } - - #[test] - fn append_health_binding_preserves_existing_and_rejects_collisions_and_aliens() -> Result<()> { - let temp = TempDir::new()?; - let store = temp.path().join("trust.cc"); - let path = store.to_str().unwrap(); - invoke(&binding_args( - "create-daemon-health-trust-binding", - path, - "one", - "daemon-one", - "runtime-one", - ))?; - let before = SingleFileMessagePackBackingStore::new(&store) - .pull_all_read_only_snapshot()? - .remove(0) - .payload; - invoke(&binding_args( - "add-daemon-health-trust-binding", - path, - "two", - "daemon-two", - "runtime-two", - ))?; - let entries = - SingleFileMessagePackBackingStore::new(&store).pull_all_read_only_snapshot()?; - assert_eq!(entries.len(), 2); - assert_eq!( - entries - .iter() - .find(|entry| entry.key == "one") - .unwrap() - .payload, - before - ); - assert!( - invoke(&binding_args( - "add-daemon-health-trust-binding", - path, - "two", - "daemon-three", - "runtime-three" - )) - .is_err() - ); - assert!( - invoke(&binding_args( - "add-daemon-health-trust-binding", - path, - "three", - "daemon-one", - "runtime-one" - )) - .is_err() - ); - SingleFileMessagePackBackingStore::new(&store).push(&CultCacheEnvelope { - key: "alien".into(), - r#type: "alien".into(), - payload: vec![], - stored_at: "2026-07-19T20:00:00Z".into(), - schema_id: Some("alien.v0".into()), - })?; - assert!( - invoke(&binding_args( - "add-daemon-health-trust-binding", - path, - "four", - "daemon-four", - "runtime-four" - )) - .is_err() - ); - Ok(()) - } - - #[test] - fn require_release_binding_changes_only_the_named_flag_and_is_idempotent() -> Result<()> { - let temp = TempDir::new()?; - let store = temp.path().join("trust.cc"); - let path = store.to_str().unwrap(); - write_test_binding( - "create-daemon-health-trust-binding", - path, - "one", - "daemon-one", - "runtime-one", - )?; - write_test_binding( - "add-daemon-health-trust-binding", - path, - "two", - "daemon-two", - "runtime-two", - )?; - let before = store_snapshot(&store)?; - - require_test_binding( - path, - "one", - "daemon-one", - "provider.health", - "runtime-one", - TEST_SIGNER_HEX, - )?; - let after = store_snapshot(&store)?; - let before_target = before.iter().find(|entry| entry.key == "one").unwrap(); - let after_target = after.iter().find(|entry| entry.key == "one").unwrap(); - let mut expected: IdunnDaemonHealthTrustBindingRecord = - rmp_serde::from_slice(&before_target.payload)?; - expected.release_binding_required = true; - assert_eq!( - rmp_serde::from_slice::(&after_target.payload)?, - expected - ); - let mut expected_envelope = before_target.clone(); - expected_envelope.payload = after_target.payload.clone(); - assert_eq!(after_target, &expected_envelope); - assert_eq!( - after.iter().find(|entry| entry.key == "two"), - before.iter().find(|entry| entry.key == "two") - ); - - require_test_binding( - path, - "one", - "daemon-one", - "provider.health", - "runtime-one", - TEST_SIGNER_HEX, - )?; - assert_eq!(store_snapshot(&store)?, after); - require_health_binding_release_from_snapshot( - &SingleFileMessagePackBackingStore::new(&store), - before, - "one", - "daemon-one", - "provider.health", - "runtime-one", - &decode_public_key(TEST_SIGNER_HEX)?, - )?; - Ok(()) - } - - #[test] - fn require_release_binding_refuses_wrong_identity_and_invalid_store_without_writing() - -> Result<()> { - let temp = TempDir::new()?; - let store = temp.path().join("trust.cc"); - let path = store.to_str().unwrap(); - write_test_binding( - "create-daemon-health-trust-binding", - path, - "one", - "daemon-one", - "runtime-one", - )?; - let before = store_snapshot(&store)?; - for (id, daemon, contract, runtime, signer) in [ - ( - "one", - "wrong", - "provider.health", - "runtime-one", - TEST_SIGNER_HEX, - ), - ("one", "daemon-one", "wrong", "runtime-one", TEST_SIGNER_HEX), - ( - "one", - "daemon-one", - "provider.health", - "wrong", - TEST_SIGNER_HEX, - ), - ( - "one", - "daemon-one", - "provider.health", - "runtime-one", - WRONG_SIGNER_HEX, - ), - ( - "missing", - "daemon-one", - "provider.health", - "runtime-one", - TEST_SIGNER_HEX, - ), - ] { - assert!(require_test_binding(path, id, daemon, contract, runtime, signer).is_err()); - } - assert!( - invoke(&[ - "require-daemon-health-release-binding", - "--store", - path, - "--binding-id", - "one", - "--daemon", - "daemon-one", - "--health-contract", - "provider.health", - "--signer-public-key-hex", - TEST_SIGNER_HEX, - ]) - .is_err() - ); - assert_eq!(store_snapshot(&store)?, before); - - SingleFileMessagePackBackingStore::new(&store).push(&CultCacheEnvelope { - key: "alien".into(), - r#type: "alien".into(), - payload: vec![], - stored_at: "2026-07-19T20:00:00Z".into(), - schema_id: Some("alien.v0".into()), - })?; - let foreign = store_snapshot(&store)?; - assert!( - require_test_binding( - path, - "one", - "daemon-one", - "provider.health", - "runtime-one", - TEST_SIGNER_HEX, - ) - .is_err() - ); - assert_eq!(store_snapshot(&store)?, foreign); - - let ambiguous = temp.path().join("ambiguous.cc"); - let ambiguous_path = ambiguous.to_str().unwrap(); - write_test_binding( - "create-daemon-health-trust-binding", - ambiguous_path, - "one", - "daemon-one", - "runtime-one", - )?; - let mut duplicate: IdunnDaemonHealthTrustBindingRecord = - rmp_serde::from_slice(&store_snapshot(&ambiguous)?.remove(0).payload)?; - duplicate.binding_id = "duplicate".into(); - SingleFileMessagePackBackingStore::new(&ambiguous).push(&typed_envelope( - &duplicate.binding_id, - &duplicate, - IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, - duplicate.bound_at_unix_millis, - )?)?; - let ambiguous_before = store_snapshot(&ambiguous)?; - assert!( - require_test_binding( - ambiguous_path, - "one", - "daemon-one", - "provider.health", - "runtime-one", - TEST_SIGNER_HEX, - ) - .is_err() - ); - assert_eq!(store_snapshot(&ambiguous)?, ambiguous_before); - Ok(()) - } - - #[test] - fn require_release_binding_cas_covers_the_whole_validated_store() -> Result<()> { - let temp = TempDir::new()?; - let store_path = temp.path().join("trust.cc"); - let path = store_path.to_str().unwrap(); - write_test_binding( - "create-daemon-health-trust-binding", - path, - "one", - "daemon-one", - "runtime-one", - )?; - write_test_binding( - "add-daemon-health-trust-binding", - path, - "two", - "daemon-two", - "runtime-two", - )?; - let stale = store_snapshot(&store_path)?; - require_test_binding( - path, - "two", - "daemon-two", - "provider.health", - "runtime-two", - TEST_SIGNER_HEX, - )?; - - let store = SingleFileMessagePackBackingStore::new(&store_path); - let error = require_health_binding_release_from_snapshot( - &store, - stale, - "one", - "daemon-one", - "provider.health", - "runtime-one", - &decode_public_key(TEST_SIGNER_HEX)?, - ) - .unwrap_err(); - assert!(error.to_string().contains("changed during release-binding")); - let records = validated_health_bindings(&store_snapshot(&store_path)?)?; - assert!( - !records - .iter() - .find(|binding| binding.binding_id == "one") - .unwrap() - .release_binding_required - ); - assert!( - records - .iter() - .find(|binding| binding.binding_id == "two") - .unwrap() - .release_binding_required - ); - Ok(()) - } - - #[test] - fn concurrent_health_binding_appends_have_one_cas_winner() -> Result<()> { - let temp = TempDir::new()?; - let store = temp.path().join("trust.cc"); - let path = store.to_str().unwrap().to_string(); - invoke(&binding_args( - "create-daemon-health-trust-binding", - &path, - "one", - "daemon-one", - "runtime-one", - ))?; - let barrier = std::sync::Arc::new(std::sync::Barrier::new(3)); - let workers = [ - ("two", "daemon-two", "runtime-two"), - ("three", "daemon-three", "runtime-three"), - ] - .map(|(id, daemon, runtime)| { - let path = path.clone(); - let barrier = barrier.clone(); - std::thread::spawn(move || { - barrier.wait(); - invoke(&binding_args( - "add-daemon-health-trust-binding", - &path, - id, - daemon, - runtime, - )) - }) - }); - barrier.wait(); - let wins = workers - .into_iter() - .map(|worker| worker.join().unwrap()) - .filter(Result::is_ok) - .count(); - assert!((1..=2).contains(&wins)); - assert_eq!( - SingleFileMessagePackBackingStore::new(&store) - .pull_all_read_only_snapshot()? - .len(), - 1 + wins - ); - Ok(()) - } - - #[test] - fn provider_health_identity_enrollment_is_profile_exact_and_immutable() -> Result<()> { - let temp = TempDir::new()?; - let private = temp.path().join("provider-health-identity.cc"); - let options = BTreeMap::from([( - "private-store".to_string(), - private.to_string_lossy().into_owned(), - )]); - - let public_key_hex = enroll_provider_health_identity(&options)?; - let signer = open_service_identity_at::(&private)?; - assert_eq!( - public_key_hex, - encode_public_key(&signer.entry().public_key)? - ); - assert_eq!( - decode_public_key(&public_key_hex)?, - signer.entry().public_key - ); - - let entries = - SingleFileMessagePackBackingStore::new(&private).pull_all_read_only_snapshot()?; - let [entry] = entries.as_slice() else { - panic!("provider health identity store must contain exactly one entry"); - }; - assert_eq!(entry.r#type, GameCultProviderHealthIdentity::PRIVATE_TYPE); - assert_eq!(entry.key, GameCultProviderHealthIdentity::PRIVATE_KEY); - assert_eq!( - entry.schema_id.as_deref(), - Some(GameCultProviderHealthIdentity::PRIVATE_SCHEMA) - ); - assert!(open_service_identity_at::(&private).is_err()); - - let before = std::fs::read(&private)?; - assert!( - invoke(&[ - "enroll-provider-health-identity", - "--private-store", - private.to_str().unwrap(), - ]) - .is_err() - ); - assert_eq!(std::fs::read(&private)?, before); - - let unauthorized = temp.path().join("unauthorized.cc"); - assert!( - invoke(&[ - "enroll-provider-health-identity", - "--private-store", - unauthorized.to_str().unwrap(), - "--release-binding-required", - "true", - ]) - .is_err() - ); - assert!(!unauthorized.exists()); - Ok(()) - } - - #[test] - fn provider_health_public_key_is_read_only_and_rejects_wrong_profile_or_options() -> Result<()> - { - let temp = TempDir::new()?; - let provider = temp.path().join("provider-health.cc"); - let provider_options = BTreeMap::from([( - "private-store".to_string(), - provider.to_string_lossy().into_owned(), - )]); - let expected = enroll_provider_health_identity(&provider_options)?; - let provider_before = std::fs::read(&provider)?; - assert_eq!(provider_health_public_key(&provider_options)?, expected); - assert_eq!(std::fs::read(&provider)?, provider_before); - - let wrong_profile = temp.path().join("idunn.cc"); - enroll_service_identity_at::(&wrong_profile)?; - let wrong_before = std::fs::read(&wrong_profile)?; - assert!( - invoke(&[ - "provider-health-public-key", - "--private-store", - wrong_profile.to_str().unwrap(), - ]) - .is_err() - ); - assert_eq!(std::fs::read(&wrong_profile)?, wrong_before); - - assert!( - invoke(&[ - "provider-health-public-key", - "--private-store", - provider.to_str().unwrap(), - "--release-binding-required", - "true", - ]) - .is_err() - ); - assert_eq!(std::fs::read(&provider)?, provider_before); - Ok(()) - } - - #[test] - fn provider_and_odin_anchor_exports_are_profile_exact_immutable_and_non_aliasing() -> Result<()> - { - let temp = TempDir::new()?; - let provider_private = temp.path().join("provider-private.cc"); - let provider_anchor = temp.path().join("provider-anchor.cc"); - invoke(&[ - "enroll-provider-health-identity", - "--private-store", - provider_private.to_str().unwrap(), - ])?; - assert!( - invoke(&[ - "export-provider-health-public-anchor", - "--private-store", - provider_private.to_str().unwrap(), - "--public-anchor", - provider_private.to_str().unwrap(), - ]) - .is_err() - ); - invoke(&[ - "export-provider-health-public-anchor", - "--private-store", - provider_private.to_str().unwrap(), - "--public-anchor", - provider_anchor.to_str().unwrap(), - ])?; - let provider_entries = store_snapshot(&provider_anchor)?; - let [provider_envelope] = provider_entries.as_slice() else { - panic!("provider anchor store must contain exactly one envelope"); - }; - assert_eq!( - provider_envelope.r#type, - GameCultProviderHealthIdentity::TRUST_ANCHOR_TYPE - ); - assert_eq!( - provider_envelope.key, - GameCultProviderHealthIdentity::TRUST_ANCHOR_KEY - ); - assert_eq!( - provider_envelope.schema_id.as_deref(), - Some(GameCultProviderHealthIdentity::TRUST_ANCHOR_SCHEMA) - ); - let provider: ServiceIdentityTrustAnchor = - rmp_serde::from_slice(&provider_envelope.payload)?; - assert_eq!(rmp_serde::to_vec(&provider)?, provider_envelope.payload); - assert_eq!( - provider.identity_id, - derive_service_identity_id::(&provider.public_key)? - ); - assert!(open_service_identity_at::(&provider_private).is_err()); - let provider_before = std::fs::read(&provider_anchor)?; - assert!( - invoke(&[ - "export-provider-health-public-anchor", - "--private-store", - provider_private.to_str().unwrap(), - "--public-anchor", - provider_anchor.to_str().unwrap(), - ]) - .is_err() - ); - assert_eq!(std::fs::read(&provider_anchor)?, provider_before); - - let odin_private = temp.path().join("odin-private.cc"); - let odin_anchor = temp.path().join("odin-anchor.cc"); - invoke(&[ - "enroll-odin-topology-identity", - "--private-store", - odin_private.to_str().unwrap(), - ])?; - assert!(open_service_identity_at::(&odin_private).is_err()); - assert!( - invoke(&[ - "export-odin-topology-public-anchor", - "--private-store", - odin_private.to_str().unwrap(), - "--public-anchor", - odin_private.to_str().unwrap(), - ]) - .is_err() - ); - invoke(&[ - "export-odin-topology-public-anchor", - "--private-store", - odin_private.to_str().unwrap(), - "--public-anchor", - odin_anchor.to_str().unwrap(), - ])?; - let odin_entries = store_snapshot(&odin_anchor)?; - let [odin_envelope] = odin_entries.as_slice() else { - panic!("Odin anchor store must contain exactly one envelope"); - }; - assert_eq!( - odin_envelope.r#type, - OdinTopologyIdentity::TRUST_ANCHOR_TYPE - ); - assert_eq!(odin_envelope.key, OdinTopologyIdentity::TRUST_ANCHOR_KEY); - assert_eq!( - odin_envelope.schema_id.as_deref(), - Some(OdinTopologyIdentity::TRUST_ANCHOR_SCHEMA) - ); - let odin: ServiceIdentityTrustAnchor = rmp_serde::from_slice(&odin_envelope.payload)?; - assert_eq!(rmp_serde::to_vec(&odin)?, odin_envelope.payload); - assert_eq!( - odin.identity_id, - derive_service_identity_id::(&odin.public_key)? - ); - assert_ne!(provider.identity_id, odin.identity_id); - let odin_before = std::fs::read(&odin_anchor)?; - assert!( - invoke(&[ - "export-odin-topology-public-anchor", - "--private-store", - odin_private.to_str().unwrap(), - "--public-anchor", - odin_anchor.to_str().unwrap(), - ]) - .is_err() - ); - assert_eq!(std::fs::read(&odin_anchor)?, odin_before); - - let wrong_profile_output = temp.path().join("wrong-profile.cc"); - assert!( - invoke(&[ - "export-provider-health-public-anchor", - "--private-store", - odin_private.to_str().unwrap(), - "--public-anchor", - wrong_profile_output.to_str().unwrap(), - ]) - .is_err() - ); - assert!(!wrong_profile_output.exists()); - Ok(()) - } - - #[test] - fn identity_enrollment_and_export_are_immutable_and_paths_cannot_alias() -> Result<()> { - let temp = TempDir::new()?; - let private = temp.path().join("identity.cc"); - let public = temp.path().join("identity-public.cc"); - invoke(&[ - "enroll-idunn-identity", - "--private-store", - private.to_str().unwrap(), - ])?; - assert!( - invoke(&[ - "enroll-idunn-identity", - "--private-store", - private.to_str().unwrap() - ]) - .is_err() - ); - assert!( - invoke(&[ - "export-idunn-public-anchor", - "--private-store", - private.to_str().unwrap(), - "--public-anchor", - private.to_str().unwrap(), - ]) - .is_err() - ); - invoke(&[ - "export-idunn-public-anchor", - "--private-store", - private.to_str().unwrap(), - "--public-anchor", - public.to_str().unwrap(), - ])?; - assert!( - invoke(&[ - "export-idunn-public-anchor", - "--private-store", - private.to_str().unwrap(), - "--public-anchor", - public.to_str().unwrap(), - ]) - .is_err() - ); - assert!( - invoke(&[ - "enroll-idunn-identity", - "--private-store", - temp.path().join("new.cc").to_str().unwrap(), - "--private-seed", - "00", - ]) - .is_err() - ); - Ok(()) - } - - #[test] - fn health_binding_derives_identity_and_rejects_overwrite_and_corruption() -> Result<()> { - let temp = TempDir::new()?; - let output = temp.path().join("provider-binding.cc"); - let key = "07".repeat(32); - let args = [ - "create-daemon-health-trust-binding", - "--output", - output.to_str().unwrap(), - "--binding-id", - "root/epiphany/health", - "--daemon", - "yggdrasil-epiphany", - "--health-contract", - "epiphany.cultnet-rudp-runtime-health", - "--source-runtime", - "epiphany-daemon-supervisor", - "--signer-public-key-hex", - &key, - "--bound-at-unix-millis", - "1784483100000", - "--release-binding-required", - "true", - ]; - invoke(&args)?; - assert!(invoke(&args).is_err()); - let mut record = read_typed::( - &output, - IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, - )?; - assert_eq!( - record.signer_identity_id, - derive_service_identity_id::( - &record.signer_public_key - )? - ); - record.signer_identity_id = "caller-chosen".into(); - replace_typed( - &output, - &record.binding_id, - IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, - &record, - )?; - assert!( - invoke(&[ - "validate-daemon-health-trust-binding", - "--input", - output.to_str().unwrap() - ]) - .is_err() - ); - - record.signer_identity_id = derive_service_identity_id::( - &record.signer_public_key, - )?; - record.schema_version = "wrong.schema.v9".into(); - replace_typed( - &output, - &record.binding_id, - IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, - &record, - )?; - assert!( - invoke(&[ - "validate-daemon-health-trust-binding", - "--input", - output.to_str().unwrap() - ]) - .is_err() - ); - Ok(()) - } - - #[test] - fn projection_anchor_is_exact_profile_and_matches_low_level_anchor() -> Result<()> { - let temp = TempDir::new()?; - let private = temp.path().join("identity.cc"); - let public = temp.path().join("public.cc"); - let root = temp.path().join("root-anchor.cc"); - invoke(&[ - "enroll-idunn-identity", - "--private-store", - private.to_str().unwrap(), - ])?; - invoke(&[ - "export-idunn-public-anchor", - "--private-store", - private.to_str().unwrap(), - "--public-anchor", - public.to_str().unwrap(), - ])?; - let create = [ - "create-provider-projection-trust-anchor", - "--output", - root.to_str().unwrap(), - "--trust-anchor-id", - "root/idunn/provider-health", - "--runtime-id", - "idunn-yggdrasil", - "--idunn-public-anchor", - public.to_str().unwrap(), - "--bound-at-unix-millis", - "1784483100000", - "--expires-at-unix-millis", - "1815000000000", - ]; - invoke(&create)?; - invoke(&[ - "validate-provider-projection-trust-anchor", - "--input", - root.to_str().unwrap(), - "--idunn-public-anchor", - public.to_str().unwrap(), - ])?; - assert!(invoke(&create).is_err()); - assert!( - invoke(&[ - "validate-provider-projection-trust-anchor", - "--input", - public.to_str().unwrap(), - "--idunn-public-anchor", - public.to_str().unwrap(), - ]) - .is_err() - ); - - let mut record = read_typed::( - &root, - GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, - )?; - record.signing_purpose = "wrong-purpose".into(); - replace_typed( - &root, - &record.trust_anchor_id, - GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, - &record, - )?; - assert!( - invoke(&[ - "validate-provider-projection-trust-anchor", - "--input", - root.to_str().unwrap(), - "--idunn-public-anchor", - public.to_str().unwrap(), - ]) - .is_err() - ); - - record.signing_purpose = - IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE.into(); - record.signer_public_key = vec![9; 32]; - replace_typed( - &root, - &record.trust_anchor_id, - GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, - &record, - )?; - assert!( - invoke(&[ - "validate-provider-projection-trust-anchor", - "--input", - root.to_str().unwrap(), - "--idunn-public-anchor", - public.to_str().unwrap(), - ]) - .is_err() - ); - Ok(()) - } - - #[test] - fn release_binding_policy_is_explicit_and_boolean() { - let temp = TempDir::new().unwrap(); - let output = temp.path().join("binding.cc"); - let base = [ - "create-daemon-health-trust-binding", - "--output", - output.to_str().unwrap(), - "--binding-id", - "root/provider/health", - "--daemon", - "provider", - "--health-contract", - "provider.health", - "--source-runtime", - "provider-runtime", - "--signer-public-key-hex", - "0707070707070707070707070707070707070707070707070707070707070707", - "--bound-at-unix-millis", - "1784483100000", - ]; - assert!(invoke(&base).is_err()); - let mut partial = base.to_vec(); - partial.extend(["--release-binding-required", "sometimes"]); - assert!(invoke(&partial).is_err()); - } - - #[test] - fn signer_rotation_changes_only_the_named_trust_binding_signer() -> Result<()> { - let temp = TempDir::new()?; - let output = temp.path().join("binding.cc"); - invoke(&[ - "create-daemon-health-trust-binding", - "--output", - output.to_str().unwrap(), - "--binding-id", - "heimdall-yggdrasil-provider-health", - "--daemon", - "yggdrasil-heimdall", - "--health-contract", - "heimdall.cultnet-rudp-provider-health", - "--source-runtime", - "heimdall-service", - "--signer-public-key-hex", - "0707070707070707070707070707070707070707070707070707070707070707", - "--bound-at-unix-millis", - "100", - "--release-binding-required", - "false", - ])?; - assert!( - invoke(&[ - "rotate-daemon-health-trust-signer", - "--output", - output.to_str().unwrap(), - "--binding-id", - "heimdall-yggdrasil-provider-health", - "--signer-public-key-hex", - "0808080808080808080808080808080808080808080808080808080808080808", - "--bound-at-unix-millis", - "100", - ]) - .is_err() - ); - invoke(&[ - "rotate-daemon-health-trust-signer", - "--output", - output.to_str().unwrap(), - "--binding-id", - "heimdall-yggdrasil-provider-health", - "--signer-public-key-hex", - "0808080808080808080808080808080808080808080808080808080808080808", - "--bound-at-unix-millis", - "101", - ])?; - let [envelope] = SingleFileMessagePackBackingStore::new(&output) - .pull_all_read_only_snapshot()? - .try_into() - .map_err(|_| anyhow!("expected one trust binding"))?; - let binding: IdunnDaemonHealthTrustBindingRecord = - rmp_serde::from_slice(&envelope.payload)?; - assert_eq!(binding.binding_id, "heimdall-yggdrasil-provider-health"); - assert_eq!(binding.daemon_id, "yggdrasil-heimdall"); - assert_eq!( - binding.health_contract, - "heimdall.cultnet-rudp-provider-health" - ); - assert_eq!(binding.source_runtime_id, "heimdall-service"); - assert_eq!(binding.signer_public_key, vec![8; 32]); - assert_eq!(binding.bound_at_unix_millis, 101); - assert!(!binding.release_binding_required); - validate_health_binding_store(&output) - } - - #[test] - fn brake_operator_can_issue_one_exact_bounded_rollout_grant() -> Result<()> { - let temp = TempDir::new()?; - let private = temp.path().join("operator-private.cc"); - let anchor = temp.path().join("operator-public.cc"); - let store = temp.path().join("brake.cc"); - invoke(&[ - "enroll-deployment-brake-operator", - "--private-store", - private.to_str().unwrap(), - ])?; - invoke(&[ - "export-deployment-brake-operator-anchor", - "--private-store", - private.to_str().unwrap(), - "--public-anchor", - anchor.to_str().unwrap(), - ])?; - invoke(&[ - "deployment-brake-engage", - "--store", - store.to_str().unwrap(), - "--runtime-id", - "yggdrasil", - "--owner", - "operator/metacrat", - "--reason", - "sleep mode", - "--observed-at-unix-millis", - "100", - ])?; - assert_eq!(read_brake(&store)?.status, "engaged"); - invoke(&[ - "deployment-brake-status", - "--store", - store.to_str().unwrap(), - "--operator-anchor", - anchor.to_str().unwrap(), - "--runtime-id", - "yggdrasil", - ])?; - assert!( - invoke(&[ - "deployment-brake-status", - "--store", - store.to_str().unwrap(), - "--operator-anchor", - anchor.to_str().unwrap(), - "--runtime-id", - "yggdrasil", - "--release-id", - "commit-4", - "--deployment-id", - "request-4", - "--now-unix-millis", - "150", - ]) - .is_err() - ); - invoke(&[ - "deployment-brake-release", - "--store", - store.to_str().unwrap(), - "--private-store", - private.to_str().unwrap(), - "--runtime-id", - "yggdrasil", - "--owner", - "operator/metacrat", - "--reason", - "one rollout", - "--authorization-id", - "auth/r4", - "--release-id", - "commit-4", - "--deployment-id", - "request-4", - "--issued-at-unix-millis", - "200", - "--expires-at-unix-millis", - "800", - ])?; - invoke(&[ - "deployment-brake-status", - "--store", - store.to_str().unwrap(), - "--operator-anchor", - anchor.to_str().unwrap(), - "--runtime-id", - "yggdrasil", - "--release-id", - "commit-4", - "--deployment-id", - "request-4", - "--now-unix-millis", - "500", - ])?; - assert!( - invoke(&[ - "deployment-brake-status", - "--store", - store.to_str().unwrap(), - "--operator-anchor", - anchor.to_str().unwrap(), - "--runtime-id", - "yggdrasil", - "--release-id", - "substituted", - "--deployment-id", - "request-4", - "--now-unix-millis", - "500" - ]) - .is_err() - ); - Ok(()) - } - - #[test] - fn lifecycle_brake_is_absence_allow_and_exact_to_runtime_target_and_expiry() -> Result<()> { - let temp = TempDir::new()?; - let missing = temp.path().join("missing-lifecycle.cc"); - invoke(&[ - "lifecycle-brake-status", - "--store", - missing.to_str().unwrap(), - "--runtime-id", - "idunn-yggdrasil", - "--target", - "ghostlight", - "--now-unix-millis", - "100", - ])?; - assert!(!missing.exists()); - - let store = temp.path().join("ghostlight-lifecycle.cc"); - invoke(&[ - "lifecycle-brake-engage", - "--store", - store.to_str().unwrap(), - "--runtime-id", - "idunn-yggdrasil", - "--target", - "ghostlight", - "--reason", - "operator maintenance", - "--updated-at-unix-millis", - "200", - ])?; - let engaged = read_lifecycle_brake(&store)?.context("lifecycle brake must exist")?; - assert_eq!(engaged.status, "engaged"); - assert_eq!(engaged.runtime_id, "idunn-yggdrasil"); - assert_eq!(engaged.target, "ghostlight"); - assert!(read_brake(&store).is_err()); - assert!( - invoke(&[ - "lifecycle-brake-status", - "--store", - store.to_str().unwrap(), - "--runtime-id", - "idunn-yggdrasil", - "--target", - "ghostlight", - "--now-unix-millis", - "201", - ]) - .is_err() - ); - - let engaged_bytes = std::fs::read(&store)?; - assert!( - invoke(&[ - "lifecycle-brake-release", - "--store", - store.to_str().unwrap(), - "--runtime-id", - "idunn-nightwing", - "--target", - "ghostlight", - "--reason", - "wrong runtime", - "--updated-at-unix-millis", - "300", - ]) - .is_err() - ); - assert!( - invoke(&[ - "lifecycle-brake-release", - "--store", - store.to_str().unwrap(), - "--runtime-id", - "idunn-yggdrasil", - "--target", - "odin", - "--reason", - "wrong target", - "--updated-at-unix-millis", - "300", - ]) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, engaged_bytes); - - invoke(&[ - "lifecycle-brake-release", - "--store", - store.to_str().unwrap(), - "--runtime-id", - "idunn-yggdrasil", - "--target", - "ghostlight", - "--reason", - "bounded continuity window", - "--updated-at-unix-millis", - "300", - "--released-until-unix-millis", - "500", - ])?; - invoke(&[ - "lifecycle-brake-status", - "--store", - store.to_str().unwrap(), - "--runtime-id", - "idunn-yggdrasil", - "--target", - "ghostlight", - "--now-unix-millis", - "499", - ])?; - for (runtime, target, now) in [ - ("idunn-nightwing", "ghostlight", "499"), - ("idunn-yggdrasil", "odin", "499"), - ("idunn-yggdrasil", "ghostlight", "500"), - ] { - assert!( - invoke(&[ - "lifecycle-brake-status", - "--store", - store.to_str().unwrap(), - "--runtime-id", - runtime, - "--target", - target, - "--now-unix-millis", - now, - ]) - .is_err() - ); - } - let released_bytes = std::fs::read(&store)?; - assert!( - invoke(&[ - "lifecycle-brake-engage", - "--store", - store.to_str().unwrap(), - "--runtime-id", - "idunn-yggdrasil", - "--target", - "ghostlight", - "--reason", - "stale replay", - "--updated-at-unix-millis", - "300", - ]) - .is_err() - ); - assert_eq!(std::fs::read(&store)?, released_bytes); - Ok(()) - } - - #[test] - fn brake_compare_exchange_rejects_stale_transition_snapshot() -> Result<()> { - let temp = TempDir::new()?; - let store_path = temp.path().join("brake.cc"); - let base = IdunnDeploymentBrakeRecord { - schema_version: IDUNN_DEPLOYMENT_BRAKE_SCHEMA.into(), - brake_id: IDUNN_DEPLOYMENT_BRAKE_ID.into(), - authority: IDUNN_DEPLOYMENT_BRAKE_AUTHORITY.into(), - runtime_id: "yggdrasil".into(), - status: "engaged".into(), - scope: IDUNN_DEPLOYMENT_BRAKE_SCOPE.into(), - reason: "first".into(), - observed_at_unix_millis: 100, - expires_at_unix_millis: None, - authorization_id: None, - authorization_purpose: None, - authorized_release_id: None, - authorized_deployment_id: None, - authorized_by: None, - authorization_issued_at_unix_millis: None, - authorization_expires_at_unix_millis: None, - signature_algorithm: None, - signature: None, - private_state_exposed: false, - updated_by: "operator/a".into(), - }; - replace_brake(&store_path, base.clone(), 100)?; - let stale = SingleFileMessagePackBackingStore::new(&store_path) - .pull_all_read_only_snapshot()? - .remove(0); - let mut changed = base.clone(); - changed.reason = "racing writer".into(); - changed.observed_at_unix_millis = 101; - replace_brake(&store_path, changed, 101)?; - let candidate = typed_envelope( - IDUNN_DEPLOYMENT_BRAKE_ID, - &base, - IDUNN_DEPLOYMENT_BRAKE_SCHEMA, - 102, - )?; - assert!( - !SingleFileMessagePackBackingStore::new(&store_path).compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: IdunnDeploymentBrakeRecord::TYPE.into(), - key: IDUNN_DEPLOYMENT_BRAKE_ID.into(), - current: Some(stale) - }], - &[candidate] - )? - ); - Ok(()) - } -} diff --git a/crates/idunn-daemon/tests/fixtures/README.md b/crates/idunn-daemon/tests/fixtures/README.md deleted file mode 100644 index 70060bf..0000000 --- a/crates/idunn-daemon/tests/fixtures/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Bifrost release-authority wire fixture - -`bifrost-release-authority-v1.payload.hex` is the exact MessagePack payload -emitted on 2026-07-16 by Bifrost's TypeScript CultCache writer -`tools/bifrost-repository-release-authority.mjs` for `GameCult/Epiphany`, -`refs/heads/main`, commit -`0123456789abcdef0123456789abcdef01234567`. - -It is checked in because the TypeScript runtime emits a camelCase MessagePack -map while Rust `DatabaseEntry` derives tuple payloads. Idunn must prove it can -decode the producer's real wire shape rather than round-tripping a fixture it -serialized itself. diff --git a/crates/idunn-daemon/tests/fixtures/bifrost-release-authority-v1.payload.hex b/crates/idunn-daemon/tests/fixtures/bifrost-release-authority-v1.payload.hex deleted file mode 100644 index e67843a..0000000 --- a/crates/idunn-daemon/tests/fixtures/bifrost-release-authority-v1.payload.hex +++ /dev/null @@ -1 +0,0 @@ -de0018aa736368656d614e616d65d924626966726f73742e7265706f7369746f72795f72656c656173655f617574686f72697479ad736368656d6156657273696f6ed927626966726f73742e7265706f7369746f72795f72656c656173655f617574686f726974792e7631ab617574686f726974794964d95272656c656173653a47616d6543756c742f4570697068616e793a726566732f68656164732f6d61696e3a30313233343536373839616263646566303132333435363738396162636465663031323334353637a9636f6d6d616e644964d92163756c746d6573682d636f6d6d616e642d6570697068616e792d72656c65617365b163726f7373696e67526563656970744964b963726f7373696e675f6570697068616e795f72656c65617365b27265706f7369746f727946756c6c4e616d65b147616d6543756c742f4570697068616e79ab757073747265616d526566af726566732f68656164732f6d61696ea9636f6d6d6974536861d92830313233343536373839616263646566303132333435363738396162636465663031323334353637a86465636973696f6ea9617574686f72697a65a6737461747573aa617574686f72697a6564b0706f6c6963794465636973696f6e4964b7706f6c6963792d6570697068616e792d72656c65617365b2617574686f726974795265666572656e6365b8626966726f73743a72656c656173653a6570697068616e79ad6163746f724964656e74697479a86d65746163726174aa736f757263654b696e64b8626966726f73742e676f7665726e616e63652e746f706963a8736f757263654964b6746f7069632d6570697068616e792d72656c65617365ad6570697068616e7952756e4964b472756e2d6570697068616e792d72656c65617365ae6570697068616e794c616e654964b168616e64732d7075626c69636174696f6eb56570697068616e794167656e744964656e74697479a86570697068616e79b265787465726e616c5265636569707455726cd95468747470733a2f2f6769746875622e636f6d2f47616d6543756c742f4570697068616e792f636f6d6d69742f30313233343536373839616263646566303132333435363738396162636465663031323334353637b165787465726e616c526563656970744964d92830313233343536373839616263646566303132333435363738396162636465663031323334353637ac617574686f72697a65644174b4323032362d30372d31365430303a30303a30305aa9657870697265734174a0a97265766f6b65644174a0b07265766f636174696f6e526561736f6ea0 diff --git a/crates/muninn-daemon/Cargo.toml b/crates/muninn-daemon/Cargo.toml index 75e16cf..9a2fc33 100644 --- a/crates/muninn-daemon/Cargo.toml +++ b/crates/muninn-daemon/Cargo.toml @@ -15,7 +15,7 @@ path = "src/main.rs" [dependencies] anyhow = "1" -cultmesh-rs = { path = "../../vendor/cultmesh-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" } cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } libc = "0.2" muninn-move-tracker = { path = "../muninn-move-tracker" } diff --git a/crates/odin-core/Cargo.toml b/crates/odin-core/Cargo.toml index 74c10f0..3d62c96 100644 --- a/crates/odin-core/Cargo.toml +++ b/crates/odin-core/Cargo.toml @@ -12,7 +12,7 @@ path = "src/lib.rs" [dependencies] anyhow = "1" cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" } -cultmesh-rs = { path = "../../vendor/cultmesh-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" } serde_json = "1" cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } serde = { version = "1", features = ["derive"] } diff --git a/crates/odin-daemon/Cargo.toml b/crates/odin-daemon/Cargo.toml index 7b78846..a7c0dac 100644 --- a/crates/odin-daemon/Cargo.toml +++ b/crates/odin-daemon/Cargo.toml @@ -13,7 +13,7 @@ path = "src/lib.rs" anyhow = "1" chrono = "0.4" cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" } -cultmesh-rs = { path = "../../vendor/cultmesh-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" } cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } fs2 = "0.4" rmp-serde = "1.3" diff --git a/crates/sleipnir-daemon/Cargo.toml b/crates/sleipnir-daemon/Cargo.toml index 71fcba5..6179ff5 100644 --- a/crates/sleipnir-daemon/Cargo.toml +++ b/crates/sleipnir-daemon/Cargo.toml @@ -11,7 +11,7 @@ path = "src/main.rs" [dependencies] anyhow = "1" -cultmesh-rs = { path = "../../vendor/cultmesh-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultmesh-rs" } cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" } odin-core = { path = "../odin-core" } diff --git a/vendor/cultmesh-rs/Cargo.lock b/vendor/cultmesh-rs/Cargo.lock deleted file mode 100644 index 7f68a9b..0000000 --- a/vendor/cultmesh-rs/Cargo.lock +++ /dev/null @@ -1,1360 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "aead" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" -dependencies = [ - "crypto-common", - "generic-array", -] - -[[package]] -name = "aes" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures", -] - -[[package]] -name = "aes-gcm" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" -dependencies = [ - "aead", - "aes", - "cipher", - "ctr", - "ghash", - "subtle", -] - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "anyhow" -version = "1.0.102" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "base64ct" -version = "1.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" - -[[package]] -name = "bitflags" -version = "2.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84d7ced0ae9557296835c32bf1b1e02b44c746701f898460fb000d7eaa84f00a" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "cc" -version = "1.2.62" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "chrono" -version = "0.4.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common", - "inout", -] - -[[package]] -name = "const-oid" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "rand_core 0.6.4", - "typenum", -] - -[[package]] -name = "ctr" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" -dependencies = [ - "cipher", -] - -[[package]] -name = "cultcache-rs" -version = "0.1.0" -dependencies = [ - "anyhow", - "chrono", - "cultcache-rs-derive", - "fs2", - "rmp-serde", - "serde", - "serde_bytes", - "serde_json", - "uuid", - "windows-sys 0.61.2", -] - -[[package]] -name = "cultcache-rs-derive" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "cultmesh-rs" -version = "0.1.0" -dependencies = [ - "anyhow", - "cultcache-rs", - "cultnet-rs", - "pretty_assertions", - "rmp-serde", - "serde", - "tempfile", -] - -[[package]] -name = "cultnet-rs" -version = "0.1.0" -dependencies = [ - "aes-gcm", - "anyhow", - "base64", - "chrono", - "cultcache-rs", - "ed25519-dalek", - "hmac", - "rand", - "rmp-serde", - "rmpv", - "serde", - "serde_bytes", - "serde_json", - "sha2", - "socket2", - "uuid", - "windows-sys 0.61.2", - "zeroize", -] - -[[package]] -name = "curve25519-dalek" -version = "4.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" -dependencies = [ - "cfg-if", - "cpufeatures", - "curve25519-dalek-derive", - "digest", - "fiat-crypto", - "rustc_version", - "subtle", - "zeroize", -] - -[[package]] -name = "curve25519-dalek-derive" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "der" -version = "0.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" -dependencies = [ - "const-oid", - "zeroize", -] - -[[package]] -name = "diff" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", - "subtle", -] - -[[package]] -name = "ed25519" -version = "2.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" -dependencies = [ - "pkcs8", - "signature", -] - -[[package]] -name = "ed25519-dalek" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" -dependencies = [ - "curve25519-dalek", - "ed25519", - "serde", - "sha2", - "subtle", - "zeroize", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "fastrand" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" - -[[package]] -name = "fiat-crypto" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" - -[[package]] -name = "find-msvc-tools" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - -[[package]] -name = "fs2" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "futures-task" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" - -[[package]] -name = "futures-util" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" -dependencies = [ - "futures-core", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "libc", - "r-efi 5.3.0", - "wasip2", -] - -[[package]] -name = "getrandom" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" -dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", - "wasip2", - "wasip3", -] - -[[package]] -name = "ghash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" -dependencies = [ - "opaque-debug", - "polyval", -] - -[[package]] -name = "hashbrown" -version = "0.15.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" -dependencies = [ - "foldhash", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - -[[package]] -name = "indexmap" -version = "2.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" -dependencies = [ - "equivalent", - "hashbrown 0.17.1", - "serde", - "serde_core", -] - -[[package]] -name = "inout" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" -dependencies = [ - "generic-array", -] - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "js-sys" -version = "0.3.99" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11" -dependencies = [ - "cfg-if", - "futures-util", - "once_cell", - "wasm-bindgen", -] - -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - -[[package]] -name = "libc" -version = "0.2.186" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "log" -version = "0.4.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "616ec5685824bcc94416c6d4a7a446eea774a31efd7062c8480ba6fd06d7a6e5" - -[[package]] -name = "memchr" -version = "2.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "pkcs8" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" -dependencies = [ - "der", - "spki", -] - -[[package]] -name = "polyval" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" -dependencies = [ - "cfg-if", - "cpufeatures", - "opaque-debug", - "universal-hash", -] - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "pretty_assertions" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" -dependencies = [ - "diff", - "yansi", -] - -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn", -] - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rand" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" -dependencies = [ - "rand_chacha", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "rmp" -version = "0.8.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" -dependencies = [ - "num-traits", -] - -[[package]] -name = "rmp-serde" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" -dependencies = [ - "rmp", - "serde", -] - -[[package]] -name = "rmpv" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417" -dependencies = [ - "rmp", - "serde", - "serde_bytes", -] - -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - -[[package]] -name = "rustix" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustversion" -version = "1.0.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_bytes" -version = "0.11.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" -dependencies = [ - "serde", - "serde_core", -] - -[[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.150" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "signature" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" -dependencies = [ - "rand_core 0.6.4", -] - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "socket2" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "spki" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" -dependencies = [ - "base64ct", - "der", -] - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "syn" -version = "2.0.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.2", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - -[[package]] -name = "universal-hash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" -dependencies = [ - "crypto-common", - "subtle", -] - -[[package]] -name = "uuid" -version = "1.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7" -dependencies = [ - "getrandom 0.4.2", - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.3+wasi-0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" -dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.122" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.122" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.122" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.122" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags", - "hashbrown 0.15.5", - "indexmap", - "semver", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck", - "indexmap", - "prettyplease", - "syn", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - -[[package]] -name = "yansi" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" - -[[package]] -name = "zerocopy" -version = "0.8.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "zeroize" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" - -[[package]] -name = "zmij" -version = "1.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/vendor/cultmesh-rs/Cargo.toml b/vendor/cultmesh-rs/Cargo.toml deleted file mode 100644 index 741c6d8..0000000 --- a/vendor/cultmesh-rs/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "cultmesh-rs" -version = "0.1.0" -edition = "2024" -publish = false - -[lib] -name = "cultmesh_rs" -path = "src/lib.rs" - -[dependencies] -anyhow = "1" -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultcache-rs" } -cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c13b6ba07e99f2535b455da74d07d88c308731f5", package = "cultnet-rs" } -serde = { version = "1", features = ["derive"] } - -[dev-dependencies] -pretty_assertions = "1.4.1" -rmp-serde = "1" -tempfile = "3" diff --git a/vendor/cultmesh-rs/src/lib.rs b/vendor/cultmesh-rs/src/lib.rs deleted file mode 100644 index 708198f..0000000 --- a/vendor/cultmesh-rs/src/lib.rs +++ /dev/null @@ -1,1557 +0,0 @@ -use anyhow::{Context, Result}; -use cultcache_rs::CultCache; -use cultcache_rs::CultCacheEnvelope; -use cultcache_rs::DatabaseEntry; -use cultcache_rs::SingleFileMessagePackBackingStore; -use cultnet_rs::CultNetDocumentPutOptions; -use cultnet_rs::CultNetDocumentRegistry; -use cultnet_rs::CultNetRudpSocketTransportConnection; -use cultnet_rs::CultNetRudpSocketTransportOptions; -use cultnet_rs::CultNetWireContract; -use cultnet_rs::decode_cultnet_message_from_slice; -use cultnet_rs::encode_cultnet_message_to_vec; -use serde::Serialize; -use std::collections::BTreeMap; -use std::collections::hash_map::RandomState; -use std::env; -use std::hash::{BuildHasher, Hasher}; -use std::net::SocketAddr; -use std::net::UdpSocket; -use std::path::Path; -use std::thread; -use std::time::Duration; -use std::time::Instant; - -mod rudp_document_server; - -pub use rudp_document_server::*; - -pub const CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID: u32 = 0x0d1d_0002; - -pub trait CultMeshDocumentSet: Clone + Send + Sync + 'static { - fn register_cache(&self, cache: &mut CultCache) -> Result<()>; - fn register_documents(&self, registry: &mut CultNetDocumentRegistry) -> Result<()>; -} - -#[macro_export] -macro_rules! cultmesh_documents { - ($name:ident { $($entry:ty => $schema_version:expr),* $(,)? }) => { - #[derive(Clone, Copy, Debug, Default)] - pub struct $name; - - impl $crate::CultMeshDocumentSet for $name { - fn register_cache( - &self, - cache: &mut cultcache_rs::CultCache, - ) -> ::anyhow::Result<()> { - $( - cache.register_entry_type::<$entry>()?; - )* - Ok(()) - } - - fn register_documents( - &self, - registry: &mut cultnet_rs::CultNetDocumentRegistry, - ) -> ::anyhow::Result<()> { - $( - registry.register( - cultnet_rs::CultNetDocumentBinding::for_entry_with_schema_id::<$entry>( - $schema_version.to_string(), - $schema_version.to_string(), - ), - ); - )* - Ok(()) - } - } - }; -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshNodeOptions { - pub runtime_id: String, - pub pull_on_start: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshRudpDocumentPublishOptions { - pub target: SocketAddr, - pub runtime_id: String, - pub connect_timeout: Duration, - pub flush_timeout: Duration, - pub poll_interval: Duration, - pub resend_delay_ms: u64, - pub source_agent_id: Option, - pub source_role: Option, - pub tags: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshRudpSnapshotOptions { - pub target: SocketAddr, - pub runtime_id: String, - /// Exact correlation id for the SnapshotRequest. Raw callers must supply - /// this; `CultMeshNode::pull_rudp_catalog_snapshot` generates one when it - /// owns the request. - pub message_id: String, - pub connect_timeout: Duration, - pub response_timeout: Duration, - pub poll_interval: Duration, - pub resend_delay_ms: u64, - pub schema_ids: Option>, - pub record_keys: Option>, -} - -impl CultMeshRudpSnapshotOptions { - pub fn odin(target: SocketAddr, runtime_id: impl Into) -> Self { - Self { - target, - runtime_id: runtime_id.into(), - ..Self::default() - } - } -} - -impl Default for CultMeshRudpSnapshotOptions { - fn default() -> Self { - Self { - target: SocketAddr::from(([0, 0, 0, 0], 0)), - runtime_id: "cultmesh-rudp-snapshot-client".to_string(), - message_id: String::new(), - connect_timeout: Duration::from_secs(3), - response_timeout: Duration::from_secs(3), - poll_interval: Duration::from_millis(10), - resend_delay_ms: 50, - schema_ids: None, - record_keys: None, - } - } -} - -impl CultMeshRudpDocumentPublishOptions { - pub fn odin(target: SocketAddr, runtime_id: impl Into) -> Self { - Self { - target, - runtime_id: runtime_id.into(), - ..Self::default() - } - } -} - -impl Default for CultMeshRudpDocumentPublishOptions { - fn default() -> Self { - Self { - target: SocketAddr::from(([0, 0, 0, 0], 0)), - runtime_id: "cultmesh-rudp-document-publisher".to_string(), - connect_timeout: Duration::from_secs(3), - flush_timeout: Duration::from_millis(300), - poll_interval: Duration::from_millis(10), - resend_delay_ms: 50, - source_agent_id: None, - source_role: None, - tags: Vec::new(), - } - } -} - -impl Default for CultMeshNodeOptions { - fn default() -> Self { - Self { - runtime_id: "cultmesh-local".to_string(), - pull_on_start: true, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshRudpEndpoint { - pub host: String, - pub port: u16, - pub addr: SocketAddr, -} - -pub struct CultMeshNode { - runtime_id: String, - cache: CultCache, - documents: CultNetDocumentRegistry, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultMeshStreamKind { - Audio, - Video, - Tensor, - Bytes, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultMeshStreamBodyTransport { - SharedMemory, - SharedD3d12Texture, - SharedD3d11Texture, - DmaBuf, - IoSurface, - AHardwareBuffer, - CultCachePage, - InlineBytes, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultMeshStreamAccess { - Read, - Write, - ReadWrite, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultMeshStreamCopyBudget { - ZeroCopyTarget, - OneCopyFallback, - OpaqueRuntime, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct CultMeshStreamClock { - pub clock_domain_id: String, - pub source_id: Option, - pub sample_rate: i32, - pub offset_to_verse_time_ns: i64, - pub confidence: f64, - pub evidence_kind: Option, -} - -impl CultMeshStreamClock { - pub fn new(clock_domain_id: impl Into) -> Result { - let clock_domain_id = require_non_empty(clock_domain_id.into(), "clock_domain_id")?; - Ok(Self { - clock_domain_id, - source_id: None, - sample_rate: 0, - offset_to_verse_time_ns: 0, - confidence: 0.0, - evidence_kind: None, - }) - } - - pub fn source_id(mut self, source_id: impl Into) -> Result { - self.source_id = Some(require_non_empty(source_id.into(), "source_id")?); - Ok(self) - } - - pub fn confidence(mut self, confidence: f64) -> Self { - self.confidence = confidence; - self - } - - pub fn evidence_kind(mut self, evidence_kind: impl Into) -> Result { - self.evidence_kind = Some(require_non_empty(evidence_kind.into(), "evidence_kind")?); - Ok(self) - } -} - -#[derive(Clone, Debug, PartialEq)] -pub struct CultMeshStreamDescriptor { - pub stream_id: String, - pub verse_id: String, - pub owner_peer_id: String, - pub kind: CultMeshStreamKind, - pub clock: CultMeshStreamClock, - pub preferred_transports: Vec, - pub label: Option, - pub required_access: CultMeshStreamAccess, - pub max_in_flight_frames: u32, - pub metadata_schema_id: Option, -} - -impl CultMeshStreamDescriptor { - pub fn new( - stream_id: impl Into, - verse_id: impl Into, - owner_peer_id: impl Into, - kind: CultMeshStreamKind, - clock: CultMeshStreamClock, - preferred_transports: Vec, - ) -> Result { - if preferred_transports.is_empty() { - anyhow::bail!("preferred_transports must not be empty"); - } - Ok(Self { - stream_id: require_non_empty(stream_id.into(), "stream_id")?, - verse_id: require_non_empty(verse_id.into(), "verse_id")?, - owner_peer_id: require_non_empty(owner_peer_id.into(), "owner_peer_id")?, - kind, - clock, - preferred_transports, - label: None, - required_access: CultMeshStreamAccess::Read, - max_in_flight_frames: 0, - metadata_schema_id: None, - }) - } - - pub fn label(mut self, label: impl Into) -> Result { - self.label = Some(require_non_empty(label.into(), "label")?); - Ok(self) - } - - pub fn max_in_flight_frames(mut self, max_in_flight_frames: u32) -> Self { - self.max_in_flight_frames = max_in_flight_frames; - self - } - - pub fn metadata_schema_id(mut self, metadata_schema_id: impl Into) -> Result { - self.metadata_schema_id = Some(require_non_empty( - metadata_schema_id.into(), - "metadata_schema_id", - )?); - Ok(self) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshStreamConsumerProfile { - pub peer_id: String, - pub verse_id: String, - pub supported_transports: Vec, - pub accepted_kinds: Vec, - pub max_in_flight_frames: u32, -} - -impl CultMeshStreamConsumerProfile { - pub fn new( - peer_id: impl Into, - verse_id: impl Into, - supported_transports: Vec, - ) -> Result { - if supported_transports.is_empty() { - anyhow::bail!("supported_transports must not be empty"); - } - Ok(Self { - peer_id: require_non_empty(peer_id.into(), "peer_id")?, - verse_id: require_non_empty(verse_id.into(), "verse_id")?, - supported_transports, - accepted_kinds: Vec::new(), - max_in_flight_frames: 0, - }) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshStreamNegotiation { - pub stream_id: String, - pub producer_peer_id: String, - pub consumer_peer_id: String, - pub transport: CultMeshStreamBodyTransport, - pub access: CultMeshStreamAccess, - pub max_in_flight_frames: u32, - pub copy_budget: CultMeshStreamCopyBudget, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshStreamFrameHandle { - pub stream_id: String, - pub sequence: u64, - pub timestamp_ns: i64, - pub duration_ns: i64, - pub transport: CultMeshStreamBodyTransport, - pub byte_length: usize, - pub resource_key: Option, - pub unavoidable_copy_count: u32, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshSharedMemoryFrameRingStats { - pub stream_id: String, - pub slot_count: usize, - pub slot_byte_length: usize, - pub published_frames: u64, - pub dropped_frames: u64, - pub blocked_writes: u64, - pub latest_sequence: u64, - pub unavoidable_copy_count: u64, -} - -pub struct CultMeshFrameReadLease<'a> { - pub handle: CultMeshStreamFrameHandle, - bytes: &'a [u8], -} - -impl CultMeshFrameReadLease<'_> { - pub fn bytes(&self) -> &[u8] { - self.bytes - } -} - -#[derive(Clone, Debug)] -pub struct CultMeshSharedMemoryFrameRing { - stream_id: String, - slot_byte_length: usize, - slots: Vec)>>, - write_cursor: usize, - latest_slot: Option, - next_sequence: u64, - published_frames: u64, - dropped_frames: u64, - blocked_writes: u64, - unavoidable_copy_count: u64, -} - -impl CultMeshSharedMemoryFrameRing { - pub fn new( - stream_id: impl Into, - slot_count: usize, - slot_byte_length: usize, - ) -> Result { - let stream_id = require_non_empty(stream_id.into(), "stream_id")?; - if slot_count == 0 { - anyhow::bail!("slot_count must be greater than zero"); - } - if slot_byte_length == 0 { - anyhow::bail!("slot_byte_length must be greater than zero"); - } - Ok(Self { - stream_id, - slot_byte_length, - slots: vec![None; slot_count], - write_cursor: 0, - latest_slot: None, - next_sequence: 0, - published_frames: 0, - dropped_frames: 0, - blocked_writes: 0, - unavoidable_copy_count: 0, - }) - } - - pub fn try_publish_copy( - &mut self, - bytes: &[u8], - timestamp_ns: i64, - duration_ns: i64, - ) -> Result> { - if bytes.len() > self.slot_byte_length { - anyhow::bail!("frame byte length exceeds slot size"); - } - if self.slots.is_empty() { - self.blocked_writes += 1; - return Ok(None); - } - - let slot_index = self.write_cursor; - if self.slots[slot_index].is_some() { - self.dropped_frames += 1; - } - let handle = CultMeshStreamFrameHandle { - stream_id: self.stream_id.clone(), - sequence: self.next_sequence, - timestamp_ns, - duration_ns, - transport: CultMeshStreamBodyTransport::SharedMemory, - byte_length: bytes.len(), - resource_key: Some(format!("{}:slot:{slot_index}", self.stream_id)), - unavoidable_copy_count: 1, - }; - self.slots[slot_index] = Some((handle.clone(), bytes.to_vec())); - self.latest_slot = Some(slot_index); - self.write_cursor = (slot_index + 1) % self.slots.len(); - self.next_sequence = self.next_sequence.saturating_add(1); - self.published_frames = self.published_frames.saturating_add(1); - self.unavoidable_copy_count = self.unavoidable_copy_count.saturating_add(1); - Ok(Some(handle)) - } - - pub fn try_acquire_latest_read(&self) -> Option> { - let slot_index = self.latest_slot?; - let (handle, bytes) = self.slots[slot_index].as_ref()?; - Some(CultMeshFrameReadLease { - handle: handle.clone(), - bytes, - }) - } - - pub fn stats(&self) -> CultMeshSharedMemoryFrameRingStats { - let latest_sequence = self - .latest_slot - .and_then(|slot| self.slots[slot].as_ref().map(|(handle, _)| handle.sequence)) - .unwrap_or(0); - CultMeshSharedMemoryFrameRingStats { - stream_id: self.stream_id.clone(), - slot_count: self.slots.len(), - slot_byte_length: self.slot_byte_length, - published_frames: self.published_frames, - dropped_frames: self.dropped_frames, - blocked_writes: self.blocked_writes, - latest_sequence, - unavoidable_copy_count: self.unavoidable_copy_count, - } - } -} - -#[derive(Clone, Debug, Default)] -pub struct CultMeshStreamCatalog { - streams: BTreeMap, - latest_frames: BTreeMap, - rings: BTreeMap, -} - -impl CultMeshStreamCatalog { - pub fn declare(&mut self, stream: CultMeshStreamDescriptor) { - self.streams.insert(stream.stream_id.clone(), stream); - } - - pub fn get(&self, stream_id: &str) -> Option<&CultMeshStreamDescriptor> { - self.streams.get(stream_id) - } - - pub fn streams(&self) -> Vec<&CultMeshStreamDescriptor> { - self.streams.values().collect() - } - - pub fn find( - &self, - verse_id: &str, - kind: Option, - ) -> Vec<&CultMeshStreamDescriptor> { - self.streams - .values() - .filter(|stream| stream.verse_id == verse_id && kind.is_none_or(|k| stream.kind == k)) - .collect() - } - - pub fn negotiate( - &self, - stream_id: &str, - consumer: &CultMeshStreamConsumerProfile, - ) -> Result { - let stream = self - .streams - .get(stream_id) - .ok_or_else(|| anyhow::anyhow!("unknown CultMesh stream '{stream_id}'"))?; - if stream.verse_id != consumer.verse_id { - anyhow::bail!("stream and consumer must belong to the same Verse"); - } - if !consumer.accepted_kinds.is_empty() && !consumer.accepted_kinds.contains(&stream.kind) { - anyhow::bail!("consumer does not accept stream kind"); - } - let transport = stream - .preferred_transports - .iter() - .copied() - .find(|candidate| consumer.supported_transports.contains(candidate)) - .ok_or_else(|| { - anyhow::anyhow!("stream and consumer have no compatible body transport") - })?; - let producer_max = if stream.max_in_flight_frames == 0 { - u32::MAX - } else { - stream.max_in_flight_frames - }; - let consumer_max = if consumer.max_in_flight_frames == 0 { - u32::MAX - } else { - consumer.max_in_flight_frames - }; - Ok(CultMeshStreamNegotiation { - stream_id: stream.stream_id.clone(), - producer_peer_id: stream.owner_peer_id.clone(), - consumer_peer_id: consumer.peer_id.clone(), - transport, - access: stream.required_access, - max_in_flight_frames: producer_max.min(consumer_max), - copy_budget: copy_budget_for(transport), - }) - } - - pub fn create_shared_memory_ring( - &mut self, - stream_id: &str, - slot_count: usize, - slot_byte_length: usize, - ) -> Result<&mut CultMeshSharedMemoryFrameRing> { - if !self.streams.contains_key(stream_id) { - anyhow::bail!("unknown CultMesh stream '{stream_id}'"); - } - self.rings.insert( - stream_id.to_string(), - CultMeshSharedMemoryFrameRing::new(stream_id, slot_count, slot_byte_length)?, - ); - Ok(self - .rings - .get_mut(stream_id) - .expect("ring was inserted for stream")) - } - - pub fn ring(&self, stream_id: &str) -> Option<&CultMeshSharedMemoryFrameRing> { - self.rings.get(stream_id) - } - - pub fn ring_mut(&mut self, stream_id: &str) -> Option<&mut CultMeshSharedMemoryFrameRing> { - self.rings.get_mut(stream_id) - } - - pub fn publish_frame(&mut self, handle: CultMeshStreamFrameHandle) -> Result<()> { - if !self.streams.contains_key(&handle.stream_id) { - anyhow::bail!("unknown CultMesh stream '{}'", handle.stream_id); - } - self.latest_frames.insert(handle.stream_id.clone(), handle); - Ok(()) - } - - pub fn latest_frame(&self, stream_id: &str) -> Option<&CultMeshStreamFrameHandle> { - self.latest_frames.get(stream_id) - } -} - -fn copy_budget_for(transport: CultMeshStreamBodyTransport) -> CultMeshStreamCopyBudget { - match transport { - CultMeshStreamBodyTransport::SharedMemory - | CultMeshStreamBodyTransport::SharedD3d12Texture - | CultMeshStreamBodyTransport::SharedD3d11Texture - | CultMeshStreamBodyTransport::DmaBuf - | CultMeshStreamBodyTransport::IoSurface - | CultMeshStreamBodyTransport::AHardwareBuffer => CultMeshStreamCopyBudget::ZeroCopyTarget, - CultMeshStreamBodyTransport::CultCachePage => CultMeshStreamCopyBudget::OneCopyFallback, - CultMeshStreamBodyTransport::InlineBytes => CultMeshStreamCopyBudget::OpaqueRuntime, - } -} - -fn require_non_empty(value: String, name: &str) -> Result { - if value.trim().is_empty() { - anyhow::bail!("{name} must be non-empty"); - } - Ok(value) -} - -impl CultMeshNode { - pub fn runtime_id(&self) -> &str { - &self.runtime_id - } - - pub fn cache(&self) -> &CultCache { - &self.cache - } - - pub fn documents(&self) -> &CultNetDocumentRegistry { - &self.documents - } - - pub fn get(&self, key: &str) -> Result> { - self.cache.get::(key) - } - - pub fn get_required(&self, key: &str) -> Result { - self.cache.get_required::(key) - } - - pub fn put(&mut self, key: impl Into, value: &T) -> Result { - self.cache.put(key, value) - } - - pub fn pull_all_backing_stores(&mut self) -> Result<()> { - self.cache.pull_all_backing_stores() - } - - pub fn delete(&mut self, key: &str) -> Result { - self.cache.delete::(key) - } - - pub fn flush(&mut self) -> Result<()> { - Ok(()) - } - - pub fn publish_document_to_rudp_catalog( - &self, - key: impl Into, - value: &T, - options: CultMeshRudpDocumentPublishOptions, - ) -> Result<()> - where - T: DatabaseEntry + Serialize, - { - let key = key.into(); - let message = self.documents.create_raw_document_put_message( - format!("{}:{}:{}", options.runtime_id, T::TYPE, key), - key, - value, - CultNetDocumentPutOptions { - source_runtime_id: Some(options.runtime_id.clone()), - source_agent_id: options.source_agent_id.clone(), - source_role: options.source_role.clone(), - tags: if options.tags.is_empty() { - None - } else { - Some(options.tags.clone()) - }, - ..CultNetDocumentPutOptions::default() - }, - )?; - publish_cultnet_message_to_rudp_catalog(&message, options) - } - - pub fn pull_rudp_catalog_snapshot( - &mut self, - mut options: CultMeshRudpSnapshotOptions, - ) -> Result { - if options.message_id.trim().is_empty() { - options.message_id = format!( - "{}:snapshot:{}:{}", - options.runtime_id, - unix_millis(), - fresh_rudp_connection_epoch() - ); - } - let response = request_raw_snapshot_from_rudp_catalog(options)?; - let cultnet_rs::CultNetMessage::SnapshotResponseRaw { documents, .. } = response else { - anyhow::bail!("expected cultnet.snapshot_response_raw.v0"); - }; - let mut applied = 0usize; - for document in documents { - let Some(document_type) = - registered_document_type_for_schema(&self.documents, &document.schema_id) - else { - continue; - }; - self.cache.put_raw_envelope(CultCacheEnvelope { - key: document.record_key, - r#type: document_type, - payload: document.payload, - stored_at: document.stored_at, - schema_id: Some(document.schema_id), - })?; - applied += 1; - } - Ok(applied) - } -} - -fn registered_document_type_for_schema( - documents: &CultNetDocumentRegistry, - schema_id: &str, -) -> Option { - let normalized = strip_schema_version_suffix(schema_id); - if normalized != schema_id { - return Some(normalized.to_string()); - } - documents - .binding_by_schema_id(schema_id) - .map(|binding| binding.document_type.clone()) - .or_else(|| documents.binding(schema_id).map(|_| schema_id.to_string())) -} - -fn strip_schema_version_suffix(value: &str) -> &str { - let Some((prefix, suffix)) = value.rsplit_once(".v") else { - return value; - }; - if suffix.chars().all(|character| character.is_ascii_digit()) { - prefix - } else { - value - } -} - -/// Request a raw CultNet snapshot without importing it into a local cache. -/// -/// The returned value is the exact validated `SnapshotResponseRaw`, including -/// its correlation `message_id`. Each call binds a fresh source port, chooses a -/// fresh connection epoch, and succeeds only after the reliable request is -/// acknowledged. -pub fn request_raw_snapshot_from_rudp_catalog( - options: CultMeshRudpSnapshotOptions, -) -> Result { - if options.runtime_id.trim().is_empty() { - anyhow::bail!("runtime_id must be non-empty"); - } - if options.message_id.trim().is_empty() { - anyhow::bail!("raw CultMesh RUDP snapshot requires a message_id"); - } - let message_id = options.message_id.clone(); - let mut client = connect_rudp_client( - options.target, - &options.runtime_id, - options.connect_timeout, - options.poll_interval, - options.resend_delay_ms, - "cultmesh-rudp-snapshot-client", - )?; - - let request = cultnet_rs::CultNetMessage::SnapshotRequest { - message_id: message_id.clone(), - schema_ids: options.schema_ids, - record_keys: options.record_keys, - }; - let payload = encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?; - let receipt = client.send_reliable("schema", payload)?; - let response_deadline = Instant::now() + options.response_timeout; - let mut snapshot_response = None; - while Instant::now() < response_deadline { - if let Some(frame) = client.receive_once()? { - if frame.channel_id == "schema" { - let message = decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - )?; - match &message { - cultnet_rs::CultNetMessage::SnapshotResponseRaw { - message_id: received, - .. - } if received == &message_id => { - snapshot_response = Some(message); - } - cultnet_rs::CultNetMessage::Error { error } => { - let _ = client.disconnect(b"snapshot-error".to_vec()); - anyhow::bail!("CultMesh RUDP snapshot failed: {error}"); - } - _ => {} - } - } - } - match client.reliable_send_status(&receipt) { - cultnet_rs::CultNetRudpReliableSendStatus::Acknowledged - if snapshot_response.is_some() => - { - let _ = client.disconnect(b"snapshot-complete".to_vec()); - return Ok(snapshot_response.expect("response was checked as present")); - } - cultnet_rs::CultNetRudpReliableSendStatus::Invalidated => { - anyhow::bail!("CultMesh RUDP snapshot request receipt was invalidated") - } - _ => {} - } - client.poll_resends()?; - thread::sleep(options.poll_interval); - } - let _ = client.disconnect(b"snapshot-timeout".to_vec()); - if snapshot_response.is_some() { - anyhow::bail!( - "timed out waiting for reliable acknowledgement of CultMesh RUDP snapshot request to {}", - options.target - ); - } - anyhow::bail!( - "timed out waiting for CultMesh RUDP snapshot from {}", - options.target - ) -} - -fn unix_millis() -> u128 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_millis() -} - -/// Publish one raw CultNet schema message to a RUDP catalog. -/// -/// Each call owns a fresh connection epoch and returns only after the catalog -/// acknowledges reliable application admission. -pub fn publish_cultnet_message_to_rudp_catalog( - message: &cultnet_rs::CultNetMessage, - options: CultMeshRudpDocumentPublishOptions, -) -> Result<()> { - if options.runtime_id.trim().is_empty() { - anyhow::bail!("runtime_id must be non-empty"); - } - let mut client = connect_rudp_client( - options.target, - &options.runtime_id, - options.connect_timeout, - options.poll_interval, - options.resend_delay_ms, - "cultmesh-rudp-document-publisher", - )?; - - let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?; - let receipt = client.send_reliable("schema", payload)?; - let flush_deadline = Instant::now() + options.flush_timeout; - while Instant::now() < flush_deadline { - let _ = client.receive_once()?; - match client.reliable_send_status(&receipt) { - cultnet_rs::CultNetRudpReliableSendStatus::Acknowledged => { - let _ = client.disconnect(b"document-acknowledged".to_vec()); - return Ok(()); - } - cultnet_rs::CultNetRudpReliableSendStatus::Invalidated => { - anyhow::bail!("CultMesh RUDP document receipt was invalidated") - } - cultnet_rs::CultNetRudpReliableSendStatus::Pending => {} - } - client.poll_resends()?; - thread::sleep(options.poll_interval); - } - let _ = client.disconnect(b"document-unacknowledged".to_vec()); - anyhow::bail!( - "timed out waiting for reliable acknowledgement from CultMesh RUDP catalog {}", - options.target - ) -} - -fn connect_rudp_client( - target: SocketAddr, - runtime_id: &str, - connect_timeout: Duration, - poll_interval: Duration, - resend_delay_ms: u64, - transport_id: &str, -) -> Result { - let bind_addr = if target.is_ipv4() { - SocketAddr::from(([0, 0, 0, 0], 0)) - } else { - SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 0], 0)) - }; - let socket = UdpSocket::bind(bind_addr)?; - socket.set_read_timeout(Some(poll_interval))?; - let mut client = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - runtime_id: runtime_id.to_string(), - socket, - mode: cultnet_rs::CultNetRudpSocketMode::Client, - remote_addr: Some(target), - connection_id: fresh_rudp_connection_epoch(), - initial_sequence: 1, - resend_delay_ms, - transport_id: Some(transport_id.to_string()), - max_payload_bytes: None, - max_fragment_bytes: Some(1200), - max_pending_reliable_packets: Some(1024), - media_reliable_expire_after_ms: None, - reconnect_policy: None, - })?; - client.connect(Vec::new())?; - let connect_deadline = Instant::now() + connect_timeout; - while !client.connected() && Instant::now() < connect_deadline { - let _ = client.receive_once()?; - client.poll_resends()?; - thread::sleep(poll_interval); - } - if !client.connected() { - anyhow::bail!("timed out connecting CultMesh RUDP client {runtime_id} to {target}"); - } - Ok(client) -} - -fn fresh_rudp_connection_epoch() -> u32 { - let mut hasher = RandomState::new().build_hasher(); - hasher.write_u128(unix_millis()); - let epoch = hasher.finish() as u32; - if epoch == 0 { 1 } else { epoch } -} - -#[derive(Clone, Copy, Debug, Default)] -pub struct CultMesh; - -impl CultMesh { - pub fn resolve_rudp_endpoint(endpoint: &str) -> Result { - let text = require_non_empty(endpoint.trim().to_string(), "endpoint")?; - if text.starts_with("rudp://") { - return parse_rudp_socket_addr(&text); - } - if text.starts_with("cultmesh://") { - let resolved = default_cultmesh_rudp_endpoint_resolver(&text)?.ok_or_else(|| { - anyhow::anyhow!("CultMesh URI {text} did not resolve to a RUDP endpoint") - })?; - return parse_rudp_socket_addr(&resolved); - } - parse_socket_addr(&text) - } - - pub fn create_node( - store_path: impl AsRef, - documents: D, - options: CultMeshNodeOptions, - ) -> Result - where - D: CultMeshDocumentSet, - { - let mut cache = CultCache::new(); - documents.register_cache(&mut cache)?; - cache - .add_generic_backing_store(SingleFileMessagePackBackingStore::new(store_path.as_ref())); - if options.pull_on_start { - cache.pull_all_backing_stores()?; - } - - let mut registry = CultNetDocumentRegistry::new(); - documents.register_documents(&mut registry)?; - - Ok(CultMeshNode { - runtime_id: options.runtime_id, - cache, - documents: registry, - }) - } - - pub fn start_node( - store_path: impl AsRef, - documents: D, - options: CultMeshNodeOptions, - ) -> Result - where - D: CultMeshDocumentSet, - { - Self::create_node(store_path, documents, options) - } - - pub fn create_stream_catalog() -> CultMeshStreamCatalog { - CultMeshStreamCatalog::default() - } -} - -pub fn create_node( - store_path: impl AsRef, - documents: D, - options: CultMeshNodeOptions, -) -> Result -where - D: CultMeshDocumentSet, -{ - CultMesh::create_node(store_path, documents, options) -} - -pub fn start_node( - store_path: impl AsRef, - documents: D, - options: CultMeshNodeOptions, -) -> Result -where - D: CultMeshDocumentSet, -{ - CultMesh::start_node(store_path, documents, options) -} - -pub fn create_stream_catalog() -> CultMeshStreamCatalog { - CultMesh::create_stream_catalog() -} - -pub fn resolve_rudp_endpoint(endpoint: &str) -> Result { - CultMesh::resolve_rudp_endpoint(endpoint) -} - -fn parse_rudp_socket_addr(value: &str) -> Result { - let text = value.trim().strip_prefix("rudp://").unwrap_or(value.trim()); - parse_socket_addr(text) -} - -fn parse_socket_addr(value: &str) -> Result { - value - .parse() - .with_context(|| format!("RUDP endpoint must be a socket address, got {value:?}")) -} - -fn default_cultmesh_rudp_endpoint_resolver(uri: &str) -> Result> { - let authority = cultmesh_uri_authority(uri)?; - let slug = authority - .chars() - .map(|ch| { - if ch.is_ascii_alphanumeric() { - ch.to_ascii_uppercase() - } else { - '_' - } - }) - .collect::() - .trim_matches('_') - .to_string(); - if slug.is_empty() { - return Ok(None); - } - - for key in [ - format!("CULTMESH_URI_{slug}_RUDP"), - format!("{slug}_CULTMESH_RUDP_ENDPOINT"), - ] { - if let Ok(value) = env::var(&key) { - let text = value.trim(); - if !text.is_empty() { - return Ok(Some(if text.starts_with("rudp://") { - text.to_string() - } else { - format!("rudp://{text}") - })); - } - } - } - Ok(None) -} - -fn cultmesh_uri_authority(uri: &str) -> Result { - let rest = uri - .strip_prefix("cultmesh://") - .ok_or_else(|| anyhow::anyhow!("CultMesh URI must start with cultmesh://"))?; - let authority = rest.split(['/', '?', '#']).next().unwrap_or("").trim(); - if authority.is_empty() { - anyhow::bail!("CultMesh URI must include an authority"); - } - Ok(authority.to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - - #[derive(Clone, Debug, PartialEq, Eq, cultcache_rs::DatabaseEntry)] - #[cultcache(type = "cultmesh.test.note", schema = "CultMeshTestNote")] - struct Note { - #[cultcache(key = 0)] - body: String, - } - - cultmesh_documents!(TestDocuments { - Note => "cultmesh.test.note.v0", - }); - - #[test] - fn node_round_trips_registered_documents() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cultmesh.cc"); - let note = Note { - body: "blessed circuit".to_string(), - }; - - let mut node = CultMesh::create_node( - &store_path, - TestDocuments, - CultMeshNodeOptions { - runtime_id: "test-runtime".to_string(), - ..CultMeshNodeOptions::default() - }, - )?; - assert_eq!(node.runtime_id(), "test-runtime"); - node.put("note", ¬e)?; - node.flush()?; - - let reloaded = CultMesh::create_node(&store_path, TestDocuments, Default::default())?; - assert_eq!(reloaded.get_required::("note")?, note); - assert!( - reloaded - .documents() - .binding_by_schema_id("cultmesh.test.note.v0") - .is_some() - ); - Ok(()) - } - - #[test] - fn node_publishes_registered_document_to_rudp_catalog() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cultmesh.cc"); - let note = Note { - body: "respect odin once".to_string(), - }; - let node = CultMesh::create_node( - &store_path, - TestDocuments, - CultMeshNodeOptions { - runtime_id: "muninn-test".to_string(), - ..CultMeshNodeOptions::default() - }, - )?; - - let socket = UdpSocket::bind("127.0.0.1:0")?; - socket.set_read_timeout(Some(Duration::from_millis(10)))?; - let target = socket.local_addr()?; - let (sender, receiver) = std::sync::mpsc::channel(); - let delivered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let delivered_by_sink = delivered.clone(); - let server = thread::spawn(move || -> Result<()> { - let mut server = CultMeshRudpDocumentServer::new( - socket, - move |receipt: CultMeshRudpRawDocumentReceipt| { - sender - .send(( - receipt.document.schema_id, - receipt.document.record_key, - receipt.document.source_runtime_id, - )) - .ok(); - delivered_by_sink.store(true, std::sync::atomic::Ordering::SeqCst); - Ok(()) - }, - |_query: &CultMeshRudpSnapshotQuery| Ok(Vec::new()), - CultMeshSystemClock::default(), - CultMeshRudpDocumentServerOptions::default(), - )?; - let deadline = Instant::now() + Duration::from_secs(2); - while Instant::now() < deadline { - server.poll_once()?; - if delivered.load(std::sync::atomic::Ordering::SeqCst) { - return Ok(()); - } - thread::sleep(Duration::from_millis(1)); - } - anyhow::bail!("timed out waiting for RUDP document put") - }); - - node.publish_document_to_rudp_catalog( - "note", - ¬e, - CultMeshRudpDocumentPublishOptions::odin(target, "muninn-test"), - )?; - let received = receiver.recv_timeout(Duration::from_secs(2))?; - server.join().expect("server thread should not panic")?; - - assert_eq!(received.0, "cultmesh.test.note.v0"); - assert_eq!(received.1, "note"); - assert_eq!(received.2.as_deref(), Some("muninn-test")); - Ok(()) - } - - #[test] - fn document_publish_fails_when_catalog_is_unreachable() -> Result<()> { - let temp = tempfile::tempdir()?; - let node = CultMesh::create_node( - temp.path().join("cultmesh.cc"), - TestDocuments, - Default::default(), - )?; - let unused = UdpSocket::bind("127.0.0.1:0")?; - let target = unused.local_addr()?; - drop(unused); - - let error = node - .publish_document_to_rudp_catalog( - "note", - &Note { - body: "no false success".into(), - }, - CultMeshRudpDocumentPublishOptions { - target, - connect_timeout: Duration::from_millis(30), - poll_interval: Duration::from_millis(2), - ..CultMeshRudpDocumentPublishOptions::default() - }, - ) - .expect_err("unreachable catalog must fail closed"); - assert!(error.to_string().contains("timed out connecting")); - Ok(()) - } - - #[test] - fn document_publish_requires_application_acknowledgement() -> Result<()> { - let temp = tempfile::tempdir()?; - let node = CultMesh::create_node( - temp.path().join("cultmesh.cc"), - TestDocuments, - Default::default(), - )?; - let socket = UdpSocket::bind("127.0.0.1:0")?; - let target = socket.local_addr()?; - let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let server_stop = stop.clone(); - let server = thread::spawn(move || -> Result<()> { - let mut server = CultMeshRudpDocumentServer::new( - socket, - |_receipt: CultMeshRudpRawDocumentReceipt| { - anyhow::bail!("injected durable sink failure") - }, - |_query: &CultMeshRudpSnapshotQuery| Ok(Vec::new()), - CultMeshSystemClock::default(), - CultMeshRudpDocumentServerOptions::default(), - )?; - while !server_stop.load(std::sync::atomic::Ordering::SeqCst) { - let _ = server.poll_once(); - thread::sleep(Duration::from_millis(1)); - } - Ok(()) - }); - - let error = node - .publish_document_to_rudp_catalog( - "note", - &Note { - body: "still not accepted".into(), - }, - CultMeshRudpDocumentPublishOptions { - target, - connect_timeout: Duration::from_millis(100), - flush_timeout: Duration::from_millis(50), - poll_interval: Duration::from_millis(2), - resend_delay_ms: 5, - ..CultMeshRudpDocumentPublishOptions::default() - }, - ) - .expect_err("unacknowledged document must fail closed"); - stop.store(true, std::sync::atomic::Ordering::SeqCst); - server.join().expect("server thread should not panic")?; - assert!(error.to_string().contains("reliable acknowledgement")); - Ok(()) - } - - #[test] - fn raw_snapshot_preserves_caller_challenge_and_raw_response() -> Result<()> { - let expected = cultnet_rs::CultNetRawDocumentRecord { - schema_id: "cultmesh.test.raw.v0".into(), - record_key: "route-proof".into(), - stored_at: "2026-09-03T00:00:00Z".into(), - payload_encoding: cultnet_rs::CultNetRawPayloadEncoding::Messagepack, - payload: vec![0xc4, 0x03, 0, 0xff, 1], - source_runtime_id: Some("odin-test".into()), - source_agent_id: None, - source_role: None, - tags: None, - }; - let socket = UdpSocket::bind("127.0.0.1:0")?; - let target = socket.local_addr()?; - let challenge = "9aa63ad8-83b5-4cc4-ae4a-91d361d5f845".to_string(); - let server_document = expected.clone(); - let server_challenge = challenge.clone(); - let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let server_stop = stop.clone(); - let server = thread::spawn(move || -> Result<()> { - let mut server = CultMeshRudpDocumentServer::new( - socket, - |_receipt: CultMeshRudpRawDocumentReceipt| Ok(()), - move |query: &CultMeshRudpSnapshotQuery| { - if query.message_id != server_challenge { - anyhow::bail!("snapshot challenge changed") - } - Ok(vec![server_document.clone()]) - }, - CultMeshSystemClock::default(), - CultMeshRudpDocumentServerOptions::default(), - )?; - while !server_stop.load(std::sync::atomic::Ordering::SeqCst) { - server.poll_once()?; - thread::sleep(Duration::from_millis(1)); - } - Ok(()) - }); - - let response = request_raw_snapshot_from_rudp_catalog(CultMeshRudpSnapshotOptions { - target, - runtime_id: "route-proof-test".into(), - message_id: challenge.clone(), - connect_timeout: Duration::from_millis(100), - response_timeout: Duration::from_millis(500), - poll_interval: Duration::from_millis(2), - resend_delay_ms: 5, - schema_ids: Some(vec!["cultmesh.test.raw.v0".into()]), - record_keys: Some(vec!["route-proof".into()]), - }); - stop.store(true, std::sync::atomic::Ordering::SeqCst); - server.join().expect("server thread should not panic")?; - let response = response?; - assert_eq!( - response, - cultnet_rs::CultNetMessage::SnapshotResponseRaw { - message_id: challenge, - documents: vec![expected], - } - ); - Ok(()) - } - - #[test] - fn raw_snapshot_rejects_response_without_request_acknowledgement() -> Result<()> { - let socket = UdpSocket::bind("127.0.0.1:0")?; - socket.set_read_timeout(Some(Duration::from_millis(200)))?; - let target = socket.local_addr()?; - let server = thread::spawn(move || -> Result<()> { - let mut wire = vec![0_u8; 65_535]; - let (received, peer) = socket.recv_from(&mut wire)?; - let connect = cultnet_rs::decode_rudp_packet(&wire[..received])?; - let mut session = - cultnet_rs::CultNetRudpSession::new(cultnet_rs::CultNetRudpSessionOptions { - connection_id: connect.connection_id, - initial_sequence: 1, - resend_delay_ms: 5, - max_pending_reliable_packets: Some(64), - }); - let accept = session.accept_connect(&connect, 1, Vec::new())?; - socket.send_to(&cultnet_rs::encode_rudp_packet(&accept)?, peer)?; - - loop { - let (received, received_peer) = socket.recv_from(&mut wire)?; - if received_peer != peer { - continue; - } - let packet = cultnet_rs::decode_rudp_packet(&wire[..received])?; - let result = session.receive(&packet, 2)?; - let Some(frame) = result.delivered.into_iter().next() else { - continue; - }; - let request = decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - )?; - let cultnet_rs::CultNetMessage::SnapshotRequest { message_id, .. } = request else { - anyhow::bail!("expected snapshot request") - }; - let payload = encode_cultnet_message_to_vec( - &cultnet_rs::CultNetMessage::SnapshotResponseRaw { - message_id, - documents: Vec::new(), - }, - CultNetWireContract::CultNetSchemaV0, - )?; - let mut packets = session.send_many( - "schema", - payload, - cultnet_rs::CultNetRudpSendOptions { - reliable: true, - ordered: true, - sequenced: false, - now_ms: 2, - reliable_expire_after_ms: None, - }, - Some(1200), - )?; - for packet in &mut packets { - packet.ack = 0; - packet.ack_mask = 0; - socket.send_to(&cultnet_rs::encode_rudp_packet(packet)?, peer)?; - } - return Ok(()); - } - }); - - let error = request_raw_snapshot_from_rudp_catalog(CultMeshRudpSnapshotOptions { - target, - runtime_id: "unacknowledged-snapshot-test".into(), - message_id: "b7987efb-69c5-4c42-9355-b6e09535ad21".into(), - connect_timeout: Duration::from_millis(100), - response_timeout: Duration::from_millis(50), - poll_interval: Duration::from_millis(2), - resend_delay_ms: 5, - schema_ids: None, - record_keys: None, - }) - .expect_err("response without request ACK must fail closed"); - server.join().expect("server thread should not panic")?; - assert!(error.to_string().contains("reliable acknowledgement")); - Ok(()) - } - - #[test] - fn resolves_rudp_endpoint_from_cultmesh_uri_bootstrap_env() -> Result<()> { - let previous = env::var("CULTMESH_URI_ODIN_RUDP").ok(); - unsafe { - env::set_var("CULTMESH_URI_ODIN_RUDP", "127.0.0.1:17871"); - } - let result = CultMesh::resolve_rudp_endpoint("cultmesh://odin/rendezvous/provider-catalog"); - unsafe { - if let Some(value) = previous { - env::set_var("CULTMESH_URI_ODIN_RUDP", value); - } else { - env::remove_var("CULTMESH_URI_ODIN_RUDP"); - } - } - - assert_eq!(result?, "127.0.0.1:17871".parse()?); - Ok(()) - } - - #[test] - fn rejects_unresolved_cultmesh_rudp_endpoint() { - let previous = env::var("CULTMESH_URI_MISSING_ODIN_RUDP").ok(); - unsafe { - env::remove_var("CULTMESH_URI_MISSING_ODIN_RUDP"); - } - let error = - CultMesh::resolve_rudp_endpoint("cultmesh://missing-odin/rendezvous/provider-catalog") - .expect_err("unresolved CultMesh URI should fail"); - unsafe { - if let Some(value) = previous { - env::set_var("CULTMESH_URI_MISSING_ODIN_RUDP", value); - } - } - assert!(error.to_string().contains("did not resolve")); - } - - #[test] - fn raw_snapshot_application_uses_registered_document_type() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("cultmesh.cc"); - let mut node = CultMesh::create_node( - &store_path, - TestDocuments, - CultMeshNodeOptions { - runtime_id: "snapshot-apply-test".to_string(), - ..CultMeshNodeOptions::default() - }, - )?; - let payload = rmp_serde::to_vec(&Note { - body: "catalog truth".to_string(), - })?; - - node.cache - .put_raw_envelope(cultcache_rs::CultCacheEnvelope { - key: "note".to_string(), - r#type: node - .documents - .binding_by_schema_id("cultmesh.test.note.v0") - .expect("test binding") - .document_type - .clone(), - payload, - stored_at: "2026-07-03T00:00:00Z".to_string(), - schema_id: Some("cultmesh.test.note.v0".to_string()), - })?; - node.flush()?; - - let reloaded = CultMesh::create_node(&store_path, TestDocuments, Default::default())?; - assert_eq!(reloaded.get_required::("note")?.body, "catalog truth"); - assert_eq!(reloaded.cache().snapshot()[0].r#type, Note::TYPE); - Ok(()) - } - - #[test] - fn stream_catalog_negotiates_and_publishes_latest_shared_memory_frame() -> Result<()> { - let mut catalog = CultMesh::create_stream_catalog(); - let stream = CultMeshStreamDescriptor::new( - "muninn:nightwing:move-evidence", - "mimir-live", - "muninn:nightwing", - CultMeshStreamKind::Bytes, - CultMeshStreamClock::new("muninn:nightwing:clock")? - .source_id("muninn:nightwing:move-evidence")? - .confidence(1.0) - .evidence_kind("muninn-move-evidence")?, - vec![ - CultMeshStreamBodyTransport::SharedMemory, - CultMeshStreamBodyTransport::CultCachePage, - ], - )? - .label("Muninn Move evidence")? - .max_in_flight_frames(4) - .metadata_schema_id("mimir.muninn_move_evidence_stream_frame.v1")?; - catalog.declare(stream); - - let consumer = CultMeshStreamConsumerProfile::new( - "mimir:starfire", - "mimir-live", - vec![CultMeshStreamBodyTransport::SharedMemory], - )?; - let negotiation = catalog.negotiate("muninn:nightwing:move-evidence", &consumer)?; - - assert_eq!( - negotiation.transport, - CultMeshStreamBodyTransport::SharedMemory - ); - assert_eq!( - negotiation.copy_budget, - CultMeshStreamCopyBudget::ZeroCopyTarget - ); - - let handle = { - let ring = - catalog.create_shared_memory_ring("muninn:nightwing:move-evidence", 4, 128)?; - ring.try_publish_copy(&[1, 2, 3], 42, 0)? - .expect("frame should publish") - }; - catalog.publish_frame(handle.clone())?; - - assert_eq!( - catalog.latest_frame("muninn:nightwing:move-evidence"), - Some(&handle) - ); - let lease = catalog - .ring("muninn:nightwing:move-evidence") - .and_then(CultMeshSharedMemoryFrameRing::try_acquire_latest_read) - .expect("latest frame should be readable"); - assert_eq!(lease.handle.sequence, 0); - assert_eq!(lease.bytes(), &[1, 2, 3]); - Ok(()) - } -} diff --git a/vendor/cultmesh-rs/src/rudp_document_server.rs b/vendor/cultmesh-rs/src/rudp_document_server.rs deleted file mode 100644 index bebeb6c..0000000 --- a/vendor/cultmesh-rs/src/rudp_document_server.rs +++ /dev/null @@ -1,647 +0,0 @@ -use anyhow::{Result, anyhow}; -use cultnet_rs::{ - CultNetMessage, CultNetRawDocumentRecord, CultNetRudpPacket, CultNetRudpPacketType, - CultNetRudpSendOptions, CultNetRudpSession, CultNetRudpSessionOptions, CultNetWireContract, - decode_cultnet_message_from_slice, decode_rudp_packet, encode_cultnet_message_to_vec, - encode_rudp_packet, -}; -use std::collections::BTreeMap; -use std::io::ErrorKind; -use std::net::{SocketAddr, UdpSocket}; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; - -const MAX_UDP_DATAGRAM_BYTES: usize = 65_535; - -/// The transport identity of one remote CultNet RUDP session. -/// -/// Connection identifiers are scoped to a remote socket address. Two clients -/// may therefore use the same connection identifier without sharing ordering, -/// acknowledgement, resend, or fragment state. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct CultMeshRudpSessionKey { - pub remote_addr: SocketAddr, - pub connection_id: u32, -} - -/// A raw document plus the receipt fact owned by the receiving process. -/// -/// `document.payload` is the exact byte vector decoded from the CultNet raw -/// record. The trusted receipt time lives beside the sender-owned record so the -/// transport never rewrites its metadata or payload. -#[derive(Clone, Debug, PartialEq)] -pub struct CultMeshRudpRawDocumentReceipt { - pub session: CultMeshRudpSessionKey, - pub message_id: String, - pub transport_sequence: u32, - pub received_at_unix_millis: u64, - pub document: CultNetRawDocumentRecord, -} - -/// The caller-visible query for a read-only raw snapshot. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshRudpSnapshotQuery { - pub session: CultMeshRudpSessionKey, - pub message_id: String, - pub requested_at_unix_millis: u64, - pub schema_ids: Option>, - pub record_keys: Option>, -} - -/// Caller-owned admission/persistence port for received raw documents. -pub trait CultMeshRudpRawDocumentSink { - fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()>; -} - -impl CultMeshRudpRawDocumentSink for F -where - F: FnMut(CultMeshRudpRawDocumentReceipt) -> Result<()>, -{ - fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()> { - self(receipt) - } -} - -/// Caller-owned catalog port for serving raw snapshot requests. -/// -/// The caller decides which records the requester may see. CultMesh preserves -/// those records as raw CultNet documents and does not interpret their schemas. -pub trait CultMeshRudpSnapshotSource { - fn raw_snapshot( - &mut self, - query: &CultMeshRudpSnapshotQuery, - ) -> Result>; -} - -impl CultMeshRudpSnapshotSource for F -where - F: FnMut(&CultMeshRudpSnapshotQuery) -> Result>, -{ - fn raw_snapshot( - &mut self, - query: &CultMeshRudpSnapshotQuery, - ) -> Result> { - self(query) - } -} - -/// Trusted local clocks for receipt facts and transport maintenance. -/// -/// Receipt time is wall time. Expiry and resend decisions use the monotonic -/// value, so a wall-clock correction cannot resurrect or pin a session. -pub trait CultMeshRudpServerClock { - fn now_unix_millis(&self) -> u64; - fn now_monotonic_millis(&self) -> u64; -} - -#[derive(Clone, Debug)] -pub struct CultMeshSystemClock { - monotonic_origin: Instant, -} - -impl Default for CultMeshSystemClock { - fn default() -> Self { - Self { - monotonic_origin: Instant::now(), - } - } -} - -impl CultMeshRudpServerClock for CultMeshSystemClock { - fn now_unix_millis(&self) -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_millis() - .try_into() - .unwrap_or(u64::MAX) - } - - fn now_monotonic_millis(&self) -> u64 { - self.monotonic_origin - .elapsed() - .as_millis() - .try_into() - .unwrap_or(u64::MAX) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshRudpDocumentServerOptions { - pub max_sessions: usize, - pub session_idle_timeout: Duration, - pub session_max_lifetime: Duration, - /// Conservative payload admission budget across all live sessions. - /// - /// Admitted ingress and queued snapshot-response bytes are charged until - /// the session ends even when CultNet releases them sooner. Together with - /// CultNet's per-session receive caps, this makes retained payload memory - /// finite without duplicating its fragment/ordering machinery here. - pub max_admitted_payload_bytes: usize, - pub max_admitted_payload_bytes_per_session: usize, - pub max_snapshot_response_bytes: usize, - pub max_snapshot_documents: usize, - pub resend_delay: Duration, - pub max_pending_reliable_packets_per_session: usize, - pub max_fragment_bytes: usize, -} - -impl Default for CultMeshRudpDocumentServerOptions { - fn default() -> Self { - Self { - max_sessions: 64, - session_idle_timeout: Duration::from_secs(30), - session_max_lifetime: Duration::from_secs(15 * 60), - max_admitted_payload_bytes: 32 * 1024 * 1024, - max_admitted_payload_bytes_per_session: 4 * 1024 * 1024, - max_snapshot_response_bytes: 1024 * 1024, - max_snapshot_documents: 4096, - resend_delay: Duration::from_millis(50), - max_pending_reliable_packets_per_session: 1024, - max_fragment_bytes: 1200, - } - } -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct CultMeshRudpMaintenance { - pub sessions_expired: usize, - pub packets_resent: usize, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CultMeshRudpApplicationOperation { - DocumentPutRaw, - SnapshotRequest, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CultMeshRudpApplicationRejection { - pub session: CultMeshRudpSessionKey, - pub operation: CultMeshRudpApplicationOperation, - pub message_id: String, - pub reason: String, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum CultMeshRudpPollOutcome { - Idle, - Handled, - ApplicationRejected(CultMeshRudpApplicationRejection), -} - -struct SessionEntry { - session: CultNetRudpSession, - created_at_monotonic_millis: u64, - last_activity_monotonic_millis: u64, - admitted_payload_bytes: usize, -} - -/// A synchronous, multi-session CultNet RUDP raw-document server. -/// -/// The server owns exactly one UDP socket. Call `poll_once` from an existing -/// daemon loop; no executor or background thread is created here. -pub struct CultMeshRudpDocumentServer { - socket: UdpSocket, - sessions: BTreeMap, - sink: S, - snapshot_source: Q, - clock: C, - options: CultMeshRudpDocumentServerOptions, -} - -impl CultMeshRudpDocumentServer -where - S: CultMeshRudpRawDocumentSink, - Q: CultMeshRudpSnapshotSource, - C: CultMeshRudpServerClock, -{ - pub fn new( - socket: UdpSocket, - sink: S, - snapshot_source: Q, - clock: C, - options: CultMeshRudpDocumentServerOptions, - ) -> Result { - validate_options(&options)?; - socket.local_addr().map_err(|error| { - anyhow!("CultMesh RUDP server requires a bound UDP socket: {error}") - })?; - socket.set_nonblocking(true)?; - Ok(Self { - socket, - sessions: BTreeMap::new(), - sink, - snapshot_source, - clock, - options, - }) - } - - pub fn local_addr(&self) -> Result { - Ok(self.socket.local_addr()?) - } - - pub fn session_count(&self) -> usize { - self.sessions.len() - } - - /// Poll transport maintenance and receive at most one UDP datagram. - /// - /// Application rejection invalidates only the responsible peer session and - /// is returned as data so a daemon can log it and keep serving. Local - /// socket and server-state failures remain errors. - pub fn poll_once(&mut self) -> Result { - self.maintain()?; - let mut wire = vec![0_u8; MAX_UDP_DATAGRAM_BYTES]; - let (received, remote_addr) = match self.socket.recv_from(&mut wire) { - Ok(value) => value, - Err(error) if error.kind() == ErrorKind::WouldBlock => { - return Ok(CultMeshRudpPollOutcome::Idle); - } - Err(error) => return Err(error.into()), - }; - wire.truncate(received); - - let packet = match decode_rudp_packet(&wire) { - Ok(packet) => packet, - Err(_) => return Ok(CultMeshRudpPollOutcome::Handled), - }; - let now_unix = self.clock.now_unix_millis(); - let now_monotonic = self.clock.now_monotonic_millis(); - let key = CultMeshRudpSessionKey { - remote_addr, - connection_id: packet.connection_id, - }; - - if packet.packet_type == CultNetRudpPacketType::Connect { - self.accept_connection(key, &packet, now_monotonic)?; - return Ok(CultMeshRudpPollOutcome::Handled); - } - - if !self.sessions.contains_key(&key) { - return Ok(CultMeshRudpPollOutcome::Handled); - } - if packet.packet_type == CultNetRudpPacketType::Data - && packet.channel_id == "schema" - && !packet.reliable - { - return Ok(CultMeshRudpPollOutcome::Handled); - } - let payload_charge = if packet.packet_type == CultNetRudpPacketType::Data { - packet.payload.len() - } else { - 0 - }; - if !self.payload_budget_allows(key, payload_charge) { - return Ok(CultMeshRudpPollOutcome::Handled); - } - - let result = { - let entry = self - .sessions - .get_mut(&key) - .expect("checked session must remain present"); - entry.last_activity_monotonic_millis = now_monotonic; - entry.admitted_payload_bytes = - entry.admitted_payload_bytes.saturating_add(payload_charge); - entry.session.receive(&packet, now_monotonic) - }; - let result = match result { - Ok(result) => result, - Err(_) => { - self.sessions.remove(&key); - return Ok(CultMeshRudpPollOutcome::Handled); - } - }; - - if let Some(reply) = result.reply { - self.send_packet(key.remote_addr, &reply)?; - } - - if result.disconnected { - self.sessions.remove(&key); - return Ok(CultMeshRudpPollOutcome::Handled); - } - - for frame in result.delivered { - if frame.channel_id != "schema" { - continue; - } - let message = match decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - ) { - Ok(message) => message, - Err(_) => continue, - }; - if let Some(rejection) = self.deliver_application_message( - key, - frame.sequence, - message, - now_unix, - now_monotonic, - )? { - self.sessions.remove(&key); - return Ok(CultMeshRudpPollOutcome::ApplicationRejected(rejection)); - } - } - - if packet.reliable { - let ack = self - .sessions - .get_mut(&key) - .ok_or_else(|| anyhow!("CultMesh RUDP session disappeared before ACK"))? - .session - .create_ack(); - self.send_packet(key.remote_addr, &ack)?; - } - Ok(CultMeshRudpPollOutcome::Handled) - } - - /// Expire idle sessions and resend reliable packets whose deadline passed. - pub fn maintain(&mut self) -> Result { - let now = self.clock.now_monotonic_millis(); - let idle_timeout_ms = duration_millis(self.options.session_idle_timeout); - let lifetime_ms = duration_millis(self.options.session_max_lifetime); - let before = self.sessions.len(); - self.sessions.retain(|_, entry| { - now.saturating_sub(entry.last_activity_monotonic_millis) <= idle_timeout_ms - && now.saturating_sub(entry.created_at_monotonic_millis) <= lifetime_ms - }); - let expired = before - self.sessions.len(); - - let mut resends = Vec::new(); - for (key, entry) in &mut self.sessions { - for packet in entry.session.due_resends(now) { - resends.push((key.remote_addr, packet)); - } - } - for (remote_addr, packet) in &resends { - self.send_packet(*remote_addr, packet)?; - } - Ok(CultMeshRudpMaintenance { - sessions_expired: expired, - packets_resent: resends.len(), - }) - } - - fn accept_connection( - &mut self, - key: CultMeshRudpSessionKey, - packet: &CultNetRudpPacket, - now: u64, - ) -> Result<()> { - if !self.sessions.contains_key(&key) { - if self.sessions.len() >= self.options.max_sessions { - return Ok(()); - } - self.sessions.insert( - key, - SessionEntry { - session: CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: key.connection_id, - initial_sequence: 1, - resend_delay_ms: duration_millis(self.options.resend_delay), - max_pending_reliable_packets: Some( - self.options.max_pending_reliable_packets_per_session, - ), - }), - created_at_monotonic_millis: now, - last_activity_monotonic_millis: now, - admitted_payload_bytes: 0, - }, - ); - } - - let accept = { - let entry = self - .sessions - .get_mut(&key) - .expect("accepted session must be present"); - // The same key is a retransmitted Connect for the existing epoch. - // A genuinely fresh client incarnation must choose a fresh id. - entry.last_activity_monotonic_millis = now; - entry.session.accept_connect(packet, now, Vec::new())? - }; - self.send_packet(key.remote_addr, &accept) - } - - fn deliver_application_message( - &mut self, - key: CultMeshRudpSessionKey, - transport_sequence: u32, - message: CultNetMessage, - now_unix: u64, - now: u64, - ) -> Result> { - match message { - CultNetMessage::DocumentPutRaw { - message_id, - document, - } => { - let receipt = CultMeshRudpRawDocumentReceipt { - session: key, - message_id: message_id.clone(), - transport_sequence, - received_at_unix_millis: now_unix, - document, - }; - if let Err(error) = self.sink.accept_raw_document(receipt) { - return Ok(Some(CultMeshRudpApplicationRejection { - session: key, - operation: CultMeshRudpApplicationOperation::DocumentPutRaw, - message_id, - reason: format!("{error:#}"), - })); - } - } - CultNetMessage::SnapshotRequest { - message_id, - schema_ids, - record_keys, - } => { - let query = CultMeshRudpSnapshotQuery { - session: key, - message_id: message_id.clone(), - requested_at_unix_millis: now_unix, - schema_ids, - record_keys, - }; - let documents = match self.snapshot_source.raw_snapshot(&query) { - Ok(documents) => documents, - Err(error) => { - return Ok(Some(CultMeshRudpApplicationRejection { - session: key, - operation: CultMeshRudpApplicationOperation::SnapshotRequest, - message_id, - reason: format!("{error:#}"), - })); - } - }; - if documents.len() > self.options.max_snapshot_documents { - return Ok(Some(CultMeshRudpApplicationRejection { - session: key, - operation: CultMeshRudpApplicationOperation::SnapshotRequest, - message_id, - reason: format!( - "snapshot returned {} documents; limit is {}", - documents.len(), - self.options.max_snapshot_documents - ), - })); - } - let response = CultNetMessage::SnapshotResponseRaw { - message_id: message_id.clone(), - documents, - }; - let payload = match encode_cultnet_message_to_vec( - &response, - CultNetWireContract::CultNetSchemaV0, - ) { - Ok(payload) => payload, - Err(error) => { - return Ok(Some(CultMeshRudpApplicationRejection { - session: key, - operation: CultMeshRudpApplicationOperation::SnapshotRequest, - message_id, - reason: format!("snapshot response could not be encoded: {error:#}"), - })); - } - }; - if payload.len() > self.options.max_snapshot_response_bytes { - return Ok(Some(CultMeshRudpApplicationRejection { - session: key, - operation: CultMeshRudpApplicationOperation::SnapshotRequest, - message_id, - reason: format!( - "snapshot response is {} bytes; limit is {}", - payload.len(), - self.options.max_snapshot_response_bytes - ), - })); - } - if !self.payload_budget_allows(key, payload.len()) { - return Ok(Some(CultMeshRudpApplicationRejection { - session: key, - operation: CultMeshRudpApplicationOperation::SnapshotRequest, - message_id, - reason: "retained payload budget is full".into(), - })); - } - let payload_bytes = payload.len(); - let entry = self - .sessions - .get_mut(&key) - .ok_or_else(|| anyhow!("CultMesh RUDP session disappeared before response"))?; - let packets = match entry.session.send_many( - "schema", - payload, - CultNetRudpSendOptions { - reliable: true, - ordered: true, - sequenced: false, - now_ms: now, - reliable_expire_after_ms: None, - }, - Some(self.options.max_fragment_bytes), - ) { - Ok(packets) => packets, - Err(error) => { - return Ok(Some(CultMeshRudpApplicationRejection { - session: key, - operation: CultMeshRudpApplicationOperation::SnapshotRequest, - message_id, - reason: format!("snapshot response could not be queued: {error:#}"), - })); - } - }; - entry.admitted_payload_bytes = - entry.admitted_payload_bytes.saturating_add(payload_bytes); - for packet in &packets { - self.send_packet(key.remote_addr, packet)?; - } - } - _ => {} - } - Ok(None) - } - - fn payload_budget_allows(&self, key: CultMeshRudpSessionKey, bytes: usize) -> bool { - let Some(session_bytes) = self - .sessions - .get(&key) - .map(|entry| entry.admitted_payload_bytes) - else { - return false; - }; - if session_bytes - .checked_add(bytes) - .is_none_or(|total| total > self.options.max_admitted_payload_bytes_per_session) - { - return false; - } - self.sessions - .values() - .try_fold(0_usize, |total, entry| { - total.checked_add(entry.admitted_payload_bytes) - }) - .and_then(|total| total.checked_add(bytes)) - .is_some_and(|total| total <= self.options.max_admitted_payload_bytes) - } - - fn send_packet(&mut self, remote_addr: SocketAddr, packet: &CultNetRudpPacket) -> Result<()> { - let wire = encode_rudp_packet(packet)?; - self.socket.send_to(&wire, remote_addr)?; - Ok(()) - } -} - -fn validate_options(options: &CultMeshRudpDocumentServerOptions) -> Result<()> { - if options.max_sessions == 0 { - return Err(anyhow!("max_sessions must be greater than zero")); - } - if options.session_idle_timeout.is_zero() { - return Err(anyhow!("session_idle_timeout must be greater than zero")); - } - if options.session_max_lifetime.is_zero() { - return Err(anyhow!("session_max_lifetime must be greater than zero")); - } - if options.max_admitted_payload_bytes == 0 { - return Err(anyhow!( - "max_admitted_payload_bytes must be greater than zero" - )); - } - if options.max_admitted_payload_bytes_per_session == 0 - || options.max_admitted_payload_bytes_per_session > options.max_admitted_payload_bytes - { - return Err(anyhow!( - "per-session admitted payload limit must be non-zero and no larger than the server limit" - )); - } - if options.max_snapshot_response_bytes == 0 - || options.max_snapshot_response_bytes > options.max_admitted_payload_bytes_per_session - { - return Err(anyhow!( - "snapshot response limit must be non-zero and fit in one session's payload budget" - )); - } - if options.max_snapshot_documents == 0 { - return Err(anyhow!("max_snapshot_documents must be greater than zero")); - } - if options.resend_delay.is_zero() { - return Err(anyhow!("resend_delay must be greater than zero")); - } - if options.max_pending_reliable_packets_per_session == 0 { - return Err(anyhow!( - "max_pending_reliable_packets_per_session must be greater than zero" - )); - } - if options.max_fragment_bytes == 0 { - return Err(anyhow!("max_fragment_bytes must be greater than zero")); - } - Ok(()) -} - -fn duration_millis(duration: Duration) -> u64 { - duration.as_millis().try_into().unwrap_or(u64::MAX) -} diff --git a/vendor/cultmesh-rs/tests/rudp_document_server.rs b/vendor/cultmesh-rs/tests/rudp_document_server.rs deleted file mode 100644 index 1e57aaf..0000000 --- a/vendor/cultmesh-rs/tests/rudp_document_server.rs +++ /dev/null @@ -1,553 +0,0 @@ -use anyhow::Result; -use cultmesh_rs::{ - CultMeshRudpApplicationOperation, CultMeshRudpDocumentServer, - CultMeshRudpDocumentServerOptions, CultMeshRudpPollOutcome, CultMeshRudpRawDocumentReceipt, - CultMeshRudpRawDocumentSink, CultMeshRudpServerClock, CultMeshRudpSnapshotQuery, - CultMeshRudpSnapshotSource, -}; -use cultnet_rs::{ - CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, - CultNetRudpReliableSendReceipt, CultNetRudpReliableSendStatus, CultNetRudpSocketMode, - CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, CultNetWireContract, - decode_cultnet_message_from_slice, encode_cultnet_message_to_vec, -}; -use pretty_assertions::assert_eq; -use std::net::{SocketAddr, UdpSocket}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; -use std::thread; -use std::time::Duration; - -#[derive(Default)] -struct SinkState { - receipts: Vec, - failures_remaining: usize, -} - -#[derive(Clone, Default)] -struct Sink(Arc>); - -impl Sink { - fn fail_once() -> Self { - Self(Arc::new(Mutex::new(SinkState { - failures_remaining: 1, - ..Default::default() - }))) - } -} - -impl CultMeshRudpRawDocumentSink for Sink { - fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()> { - let mut state = self.0.lock().unwrap(); - if state.failures_remaining > 0 { - state.failures_remaining -= 1; - anyhow::bail!("injected sink failure"); - } - state.receipts.push(receipt); - Ok(()) - } -} - -#[derive(Default)] -struct SourceState { - documents: Vec, - failures_remaining: usize, - calls: usize, -} - -#[derive(Clone, Default)] -struct Source(Arc>); - -impl Source { - fn documents(documents: Vec) -> Self { - Self(Arc::new(Mutex::new(SourceState { - documents, - ..Default::default() - }))) - } - - fn fail_once(documents: Vec) -> Self { - Self(Arc::new(Mutex::new(SourceState { - documents, - failures_remaining: 1, - calls: 0, - }))) - } -} - -impl CultMeshRudpSnapshotSource for Source { - fn raw_snapshot( - &mut self, - _: &CultMeshRudpSnapshotQuery, - ) -> Result> { - let mut state = self.0.lock().unwrap(); - state.calls += 1; - if state.failures_remaining > 0 { - state.failures_remaining -= 1; - anyhow::bail!("injected source failure"); - } - Ok(state.documents.clone()) - } -} - -#[derive(Clone)] -struct Clock { - unix: Arc, - monotonic: Arc, -} - -impl Clock { - fn new(now: u64) -> Self { - Self { - unix: Arc::new(AtomicU64::new(now)), - monotonic: Arc::new(AtomicU64::new(now)), - } - } - - fn set(&self, now: u64) { - self.unix.store(now, Ordering::SeqCst); - self.monotonic.store(now, Ordering::SeqCst); - } - - fn set_unix(&self, now: u64) { - self.unix.store(now, Ordering::SeqCst); - } - - fn set_monotonic(&self, now: u64) { - self.monotonic.store(now, Ordering::SeqCst); - } -} - -impl CultMeshRudpServerClock for Clock { - fn now_unix_millis(&self) -> u64 { - self.unix.load(Ordering::SeqCst) - } - - fn now_monotonic_millis(&self) -> u64 { - self.monotonic.load(Ordering::SeqCst) - } -} - -type Server = CultMeshRudpDocumentServer; - -fn document(key: &str, payload: Vec) -> CultNetRawDocumentRecord { - CultNetRawDocumentRecord { - schema_id: "test.raw.v1".into(), - record_key: key.into(), - stored_at: "2026-09-03T00:00:00Z".into(), - payload_encoding: CultNetRawPayloadEncoding::Messagepack, - payload, - source_runtime_id: Some(format!("runtime-{key}")), - source_agent_id: None, - source_role: None, - tags: None, - } -} - -fn server( - options: CultMeshRudpDocumentServerOptions, - clock: Clock, - sink: Sink, - source: Source, -) -> Result { - CultMeshRudpDocumentServer::new( - UdpSocket::bind("127.0.0.1:0")?, - sink, - source, - clock, - options, - ) -} - -fn client(target: SocketAddr, id: u32) -> Result { - let socket = UdpSocket::bind("127.0.0.1:0")?; - socket.set_nonblocking(true)?; - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - runtime_id: "test-client".into(), - socket, - mode: CultNetRudpSocketMode::Client, - remote_addr: Some(target), - connection_id: id, - initial_sequence: 1, - resend_delay_ms: 10, - transport_id: None, - max_payload_bytes: None, - max_fragment_bytes: Some(1200), - max_pending_reliable_packets: Some(64), - media_reliable_expire_after_ms: None, - }) -} - -fn connect( - server: &mut Server, - clients: &mut [&mut CultNetRudpSocketTransportConnection], -) -> Result<()> { - for client in &mut *clients { - client.connect(Vec::new())?; - } - for _ in 0..500 { - server.poll_once()?; - for client in &mut *clients { - client.receive_once()?; - } - if clients.iter().all(|client| client.connected()) { - for _ in 0..clients.len() { - server.poll_once()?; - } - return Ok(()); - } - thread::sleep(Duration::from_millis(1)); - } - anyhow::bail!("client connection timed out") -} - -fn send(client: &mut CultNetRudpSocketTransportConnection, message: &CultNetMessage) -> Result<()> { - client.send( - "schema", - encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?, - ) -} - -fn send_reliable( - client: &mut CultNetRudpSocketTransportConnection, - message: &CultNetMessage, -) -> Result { - client.send_reliable( - "schema", - encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?, - ) -} - -#[test] -fn same_connection_id_is_peer_scoped_and_raw_bytes_are_untouched() -> Result<()> { - let clock = Clock::new(42_000); - let sink = Sink::default(); - let mut server = server(Default::default(), clock, sink.clone(), Source::default())?; - let mut a = client(server.local_addr()?, 77)?; - let mut b = client(server.local_addr()?, 77)?; - connect(&mut server, &mut [&mut a, &mut b])?; - - let a_bytes = vec![0xc4, 0x04, 0x00, 0xff, 0x80, 0x01]; - let b_bytes = vec![0x92, 0x01, 0xc4, 0x02, 0x00, 0xff]; - send( - &mut a, - &CultNetMessage::DocumentPutRaw { - message_id: "a".into(), - document: document("a", a_bytes.clone()), - }, - )?; - send( - &mut b, - &CultNetMessage::DocumentPutRaw { - message_id: "b".into(), - document: document("b", b_bytes.clone()), - }, - )?; - for _ in 0..500 { - server.poll_once()?; - a.receive_once()?; - b.receive_once()?; - if sink.0.lock().unwrap().receipts.len() == 2 { - break; - } - } - - let receipts = sink.0.lock().unwrap(); - assert_eq!(server.session_count(), 2); - assert_eq!(receipts.receipts.len(), 2); - assert_ne!( - receipts.receipts[0].session.remote_addr, - receipts.receipts[1].session.remote_addr - ); - assert_eq!( - receipts - .receipts - .iter() - .find(|r| r.message_id == "a") - .unwrap() - .document - .payload, - a_bytes - ); - assert_eq!( - receipts - .receipts - .iter() - .find(|r| r.message_id == "b") - .unwrap() - .document - .payload, - b_bytes - ); - assert!( - receipts - .receipts - .iter() - .all(|r| r.received_at_unix_millis == 42_000) - ); - Ok(()) -} - -#[test] -fn duplicate_connect_preserves_epoch_and_fresh_epoch_is_separate() -> Result<()> { - let clock = Clock::new(45_000); - let sink = Sink::default(); - let mut server = server(Default::default(), clock, sink.clone(), Source::default())?; - let target = server.local_addr()?; - let mut incumbent = client(target, 91)?; - connect(&mut server, &mut [&mut incumbent])?; - - incumbent.connect(Vec::new())?; - server.poll_once()?; - incumbent.receive_once()?; - assert_eq!(server.session_count(), 1); - - send( - &mut incumbent, - &CultNetMessage::DocumentPutRaw { - message_id: "after-duplicate".into(), - document: document("incumbent", vec![1, 2, 3]), - }, - )?; - for _ in 0..20 { - server.poll_once()?; - if sink.0.lock().unwrap().receipts.len() == 1 { - break; - } - } - assert_eq!(sink.0.lock().unwrap().receipts.len(), 1); - - let mut fresh_epoch = client(target, 92)?; - connect(&mut server, &mut [&mut fresh_epoch])?; - assert_eq!(server.session_count(), 2); - Ok(()) -} - -#[test] -fn application_rejection_is_nonfatal_peer_scoped_and_unacknowledged() -> Result<()> { - let clock = Clock::new(48_000); - let sink = Sink::fail_once(); - let source = Source::fail_once(vec![document("snapshot", vec![4, 5, 6])]); - let mut server = server( - Default::default(), - clock.clone(), - sink.clone(), - source.clone(), - )?; - let target = server.local_addr()?; - - let mut publisher = client(target, 101)?; - let mut snapshot_client = client(target, 102)?; - let mut survivor = client(target, 103)?; - connect( - &mut server, - &mut [&mut publisher, &mut snapshot_client, &mut survivor], - )?; - let publish_receipt = send_reliable( - &mut publisher, - &CultNetMessage::DocumentPutRaw { - message_id: "rejected-put".into(), - document: document("rejected", vec![0, 255, 1]), - }, - )?; - let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = server.poll_once()? else { - panic!("sink rejection must be returned as a nonfatal poll outcome"); - }; - assert_eq!(rejection.session.connection_id, 101); - assert_eq!( - rejection.operation, - CultMeshRudpApplicationOperation::DocumentPutRaw - ); - assert_eq!(rejection.message_id, "rejected-put"); - assert!(rejection.reason.contains("injected sink failure")); - assert_eq!(server.session_count(), 2); - publisher.receive_once()?; - assert_eq!( - publisher.reliable_send_status(&publish_receipt), - CultNetRudpReliableSendStatus::Pending - ); - - let snapshot_receipt = send_reliable( - &mut snapshot_client, - &CultNetMessage::SnapshotRequest { - message_id: "rejected-snapshot".into(), - schema_ids: None, - record_keys: None, - }, - )?; - let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = server.poll_once()? else { - panic!("source rejection must be returned as a nonfatal poll outcome"); - }; - assert_eq!(rejection.session.connection_id, 102); - assert_eq!( - rejection.operation, - CultMeshRudpApplicationOperation::SnapshotRequest - ); - assert_eq!(rejection.message_id, "rejected-snapshot"); - assert!(rejection.reason.contains("injected source failure")); - assert_eq!(server.session_count(), 1); - snapshot_client.receive_once()?; - assert_eq!( - snapshot_client.reliable_send_status(&snapshot_receipt), - CultNetRudpReliableSendStatus::Pending - ); - - let survivor_receipt = send_reliable( - &mut survivor, - &CultNetMessage::DocumentPutRaw { - message_id: "accepted-after-rejections".into(), - document: document("survivor", vec![9, 8, 7]), - }, - )?; - assert_eq!(server.poll_once()?, CultMeshRudpPollOutcome::Handled); - for _ in 0..20 { - survivor.receive_once()?; - if survivor.reliable_send_status(&survivor_receipt) - == CultNetRudpReliableSendStatus::Acknowledged - { - break; - } - } - assert_eq!( - survivor.reliable_send_status(&survivor_receipt), - CultNetRudpReliableSendStatus::Acknowledged - ); - assert_eq!(sink.0.lock().unwrap().receipts.len(), 1); - assert_eq!(source.0.lock().unwrap().calls, 1); - Ok(()) -} - -#[test] -fn snapshot_response_resends_until_acknowledged() -> Result<()> { - let clock = Clock::new(51_000); - let expected = document("catalog", vec![0x81, 0xa1, 0x78, 0x2a]); - let source = Source::documents(vec![expected.clone()]); - let options = CultMeshRudpDocumentServerOptions { - resend_delay: Duration::from_millis(10), - ..Default::default() - }; - let mut server = server(options, clock.clone(), Sink::default(), source)?; - let mut client = client(server.local_addr()?, 88)?; - connect(&mut server, &mut [&mut client])?; - send( - &mut client, - &CultNetMessage::SnapshotRequest { - message_id: "snapshot".into(), - schema_ids: Some(vec!["test.raw.v1".into()]), - record_keys: Some(vec!["catalog".into()]), - }, - )?; - server.poll_once()?; - - clock.set(51_011); - assert_eq!(server.maintain()?.packets_resent, 1); - let response = loop { - if let Some(frame) = client.receive_once()? { - break decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - )?; - } - }; - assert_eq!( - response, - CultNetMessage::SnapshotResponseRaw { - message_id: "snapshot".into(), - documents: vec![expected], - } - ); - - for _ in 0..20 { - server.poll_once()?; - } - clock.set(51_022); - assert_eq!(server.maintain()?.packets_resent, 0); - Ok(()) -} - -#[test] -fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { - let clock = Clock::new(55_000); - let sink = Sink::default(); - let message = CultNetMessage::DocumentPutRaw { - message_id: "budget".into(), - document: document("budget", vec![7; 64]), - }; - let encoded = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?; - let options = CultMeshRudpDocumentServerOptions { - max_admitted_payload_bytes: encoded.len(), - max_admitted_payload_bytes_per_session: encoded.len(), - max_snapshot_response_bytes: encoded.len(), - ..Default::default() - }; - let mut budget_server = server(options, clock, sink.clone(), Source::default())?; - let target = budget_server.local_addr()?; - let mut first = client(target, 111)?; - let mut second = client(target, 112)?; - connect(&mut budget_server, &mut [&mut first, &mut second])?; - send(&mut first, &message)?; - budget_server.poll_once()?; - send(&mut second, &message)?; - budget_server.poll_once()?; - assert_eq!(sink.0.lock().unwrap().receipts.len(), 1); - - let oversized = Source::documents(vec![document("oversized", vec![8; 512])]); - let options = CultMeshRudpDocumentServerOptions { - max_snapshot_response_bytes: 128, - ..Default::default() - }; - let mut snapshot_server = server(options, Clock::new(56_000), Sink::default(), oversized)?; - let mut snapshot_client = client(snapshot_server.local_addr()?, 113)?; - connect(&mut snapshot_server, &mut [&mut snapshot_client])?; - let receipt = send_reliable( - &mut snapshot_client, - &CultNetMessage::SnapshotRequest { - message_id: "too-large".into(), - schema_ids: None, - record_keys: None, - }, - )?; - let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = snapshot_server.poll_once()? - else { - panic!("oversized snapshot must reject only its session"); - }; - assert_eq!( - rejection.operation, - CultMeshRudpApplicationOperation::SnapshotRequest - ); - assert_eq!(rejection.message_id, "too-large"); - assert!(rejection.reason.contains("snapshot response is")); - assert_eq!(snapshot_server.session_count(), 0); - snapshot_client.receive_once()?; - assert_eq!( - snapshot_client.reliable_send_status(&receipt), - CultNetRudpReliableSendStatus::Pending - ); - Ok(()) -} - -#[test] -fn session_cap_and_expiry_use_monotonic_time() -> Result<()> { - let clock = Clock::new(60_000); - let options = CultMeshRudpDocumentServerOptions { - max_sessions: 1, - session_idle_timeout: Duration::from_secs(1), - session_max_lifetime: Duration::from_millis(100), - ..Default::default() - }; - let mut server = server(options, clock.clone(), Sink::default(), Source::default())?; - let target = server.local_addr()?; - let mut admitted = client(target, 1)?; - connect(&mut server, &mut [&mut admitted])?; - let mut rejected = client(target, 1)?; - rejected.connect(Vec::new())?; - server.poll_once()?; - assert_eq!(server.session_count(), 1); - assert!(!rejected.connected()); - - clock.set_unix(1); - clock.set_monotonic(60_101); - assert_eq!(server.maintain()?.sessions_expired, 1); - assert_eq!(server.session_count(), 0); - Ok(()) -}