From 1fc0dadec3ef35d9073ade86d6d3802545c92a9f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Sep 2026 05:23:06 +0200 Subject: [PATCH] Rebuild Idunn deployment transaction authority --- src/control_plane.rs | 4171 +++++++++++++++++++++++++++++++++++++--- src/deployment.rs | 211 +- src/deployment_plan.rs | 318 ++- src/drivers.rs | 2356 ++++++++++++++++++++--- 4 files changed, 6374 insertions(+), 682 deletions(-) diff --git a/src/control_plane.rs b/src/control_plane.rs index a668807..3a4fe62 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -1,50 +1,79 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::env; -use std::fs; +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 anyhow::{anyhow, bail, ensure, Context, Result}; use cultcache_rs::{ CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, }; +use cultnet_rs::{ + authenticate_odin_runtime_topology_correlation, derive_service_identity_id, + evaluate_idunn_continuity_restart, evaluate_idunn_deployment_brake, open_service_identity_at, + verify_idunn_deployment_brake_authorization, verify_runtime_authority, + AuthenticatedOdinRuntimeTopologyCorrelation, GameCultProviderHealthIdentity, + IdunnDeploymentBrakeObservation, IdunnDeploymentBrakeOperatorIdentity, + IdunnDeploymentBrakeRecord, IdunnExpectedIncarnationRecord, IdunnLifecycleBrakeObservation, + IdunnLifecycleBrakeRecord, IdunnProcessWriteLeaseRecord, IdunnRuntimeActivationLaunch, + IdunnRuntimeActivationRecord, IdunnServiceIdentity, OdinTopologyAuthenticationContext, + OdinTopologyIdentity, ServiceIdentityProfile, ServiceIdentitySigner, + ServiceIdentityTrustAnchor, IDUNN_DEPLOYMENT_BRAKE_SCHEMA, IDUNN_LIFECYCLE_BRAKE_SCHEMA, + IDUNN_PROCESS_WRITE_LEASE_SCHEMA, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; use uuid::Uuid; -use crate::deployment::OperatorBinding; -use crate::drivers::ProcessIdentity; +use crate::deployment::{DependencyKind, OperatorBinding, StartupOrder}; +use crate::deployment_plan::{ + compile_deployment_plan, CompiledDeploymentPlan, DependencyProviderAuthority, SealedRelease, +}; +use crate::drivers::{ + CultCacheTopologyDriver, CultCacheWriteLeaseDriver, DockerRunnerDriver, FrozenSourceReceipt, + GitSourceDriver, InstalledReleaseObservation, NginxRouteDriver, ProcessIdentity, + RouteObservation, RoutePort, RoutePreflightReceipt, RunnerPort, SourcePort, + SystemdTransientWorkloadDriver, TopologyPort, WorkloadObservation, WorkloadPort, + WriteLeasePort, +}; -const DEPLOYMENT_COMMAND_SCHEMA: &str = "idunn.deployment_command.v1"; +const DEPLOYMENT_COMMAND_SCHEMA: &str = "idunn.deployment_command.v2"; +const DEPLOYMENT_TRANSACTION_SCHEMA: &str = "idunn.deployment_transaction.v1"; +const ADMITTED_GENERATION_SCHEMA: &str = "idunn.admitted_generation.v1"; +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.v1" + schema = "idunn.deployment_command.v2" )] -struct DeploymentCommandRecord { +struct DeploymentCommand { #[cultcache(key = 0)] schema_version: String, #[cultcache(key = 1)] command_id: String, #[cultcache(key = 2)] - selector: String, + kind: CommandKind, #[cultcache(key = 3)] - requested_by: String, + selector: String, #[cultcache(key = 4)] - requested_at_unix_millis: u64, + requested_by: String, #[cultcache(key = 5)] - state: String, - #[cultcache(key = 6)] - owner_instance_id: Option, - #[cultcache(key = 7)] - started_at_unix_millis: Option, - #[cultcache(key = 8)] - completed_at_unix_millis: Option, - #[cultcache(key = 9)] - detail: String, + requested_at_unix_millis: u64, } -impl DeploymentCommandRecord { +#[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, @@ -57,44 +86,1040 @@ impl DeploymentCommandRecord { self.requested_at_unix_millis > 0, "deployment command has no request time" ); - ensure!( - matches!( - self.state.as_str(), - "pending" | "running" | "succeeded" | "failed" + match self.kind { + CommandKind::Deploy => ensure!( + !self.command_id.starts_with("continuity-"), + "operator deployment uses the continuity command namespace" ), - "deployment command state is invalid" + 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(()) + } +} + +/// Opaque capability minted only after the transaction CAS advances the Odin +/// replay cursor and stores these exact bytes. Adjacent drivers may inspect the +/// authenticated receipt, but cannot construct replay admission themselves. +#[derive(Clone, Debug)] +pub struct SequenceAdmittedWarming { + transaction_id: String, + evidence: TopologyEvidence, + authenticated: AuthenticatedOdinRuntimeTopologyCorrelation, +} + +impl SequenceAdmittedWarming { + #[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)?; + Ok(Self { + transaction_id, + evidence, + authenticated, + }) + } + + pub(crate) fn authenticated(&self) -> &AuthenticatedOdinRuntimeTopologyCorrelation { + &self.authenticated + } + + pub(crate) fn transaction_id(&self) -> &str { + &self.transaction_id + } + + pub(crate) fn evidence_sha256(&self) -> &str { + &self.evidence.canonical_sha256 + } +} + +/// 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 }, +} + +impl RoutingEvidence { + fn observation(&self) -> Option<&RouteObservation> { + match self { + Self::SkippedUnrouted => None, + Self::Promoted { observation } => Some(observation), + } + } +} + +#[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_stop: CleanupEvidence, + topology_reconciliation: CleanupEvidence, + source_cleanup: CleanupEvidence, +} + +impl PreFencingAbort { + fn is_complete(&self) -> bool { + self.candidate_stop.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.v1" +)] +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_stop: 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 + } + + 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" + ); + } + } + for evidence in [&self.latest_odin_observation, &self.warming, &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(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(), abort.candidate_stop), + (true, CleanupEvidence::Pending | CleanupEvidence::Complete) + | (false, CleanupEvidence::Skipped) + ), + "abort candidate-stop evidence differs from its candidate observation" + ); + 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 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 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.v1" +)] +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, +} + +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, + }; + 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.detail.len() <= 2048 && !self.detail.contains('\0'), - "deployment command detail is invalid" + 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" ); - match self.state.as_str() { - "pending" => { - ensure!( - self.owner_instance_id.is_none() - && self.started_at_unix_millis.is_none() - && self.completed_at_unix_millis.is_none(), - "pending deployment command has execution state" - ); - } - "running" => { - ensure!( - self.owner_instance_id.is_some() - && self.started_at_unix_millis.is_some() - && self.completed_at_unix_millis.is_none(), - "running deployment command has partial ownership" - ); - } - "succeeded" | "failed" => { - ensure!( - self.owner_instance_id.is_some() - && self.started_at_unix_millis.is_some() - && self.completed_at_unix_millis.is_some(), - "terminal deployment command has partial receipt state" - ); - } - _ => unreachable!(), - } Ok(()) } } @@ -108,7 +1133,11 @@ struct RuntimeOptions { 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, } @@ -124,7 +1153,15 @@ impl Default for RuntimeOptions { "/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, } } @@ -196,6 +1233,18 @@ fn parse_serve(mut args: impl Iterator) -> Result { 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)?, @@ -203,7 +1252,10 @@ fn parse_serve(mut args: impl Iterator) -> Result { _ => bail!("unknown Idunn serve option {argument:?}"), } } - ensure!(options.poll_millis > 0, "--poll-millis must be positive"); + 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!( @@ -268,46 +1320,328 @@ fn parse_status(mut args: impl Iterator) -> Result { }) } -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 instance_id = format!("idunn-{}", Uuid::new_v4()); - loop { - if let Some(command) = claim_next(&options.state_store, &instance_id)? { - let result = execute(&options, &command); - complete(&options.state_store, &command, result)?; - } else { - thread::sleep(Duration::from_millis(options.poll_millis)); +#[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, signer_identity_id: &str) -> u64 { + let transaction_max = self + .transactions + .iter() + .filter_map(|stored| { + stored + .value + .latest_odin_observation + .as_ref() + .filter(|evidence| 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.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 execute(options: &RuntimeOptions, command: &DeploymentCommandRecord) -> Result { - let bindings = load_bindings(&options.bindings_dir)?; - let targets = resolve_selector(&bindings, &command.selector)?; +fn decode_record(envelope: &CultCacheEnvelope) -> Result +where + T: for<'de> Deserialize<'de> + Serialize, +{ + let value: T = rmp_serde::from_slice(&envelope.payload)?; ensure!( - !targets.is_empty(), - "deployment selector resolved to no targets" + rmp_serde::to_vec(&value)? == envelope.payload, + "Idunn control store contains a noncanonical record" ); - bail!( - "typed deployment drivers are not yet connected for {}", - targets.join(",") + 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 load_bindings(directory: &Path) -> Result> { +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())) @@ -324,7 +1658,9 @@ fn load_bindings(directory: &Path) -> Result> .with_context(|| format!("validating operator binding {}", path.display()))?; let target = binding.target.clone(); ensure!( - bindings.insert(target.clone(), binding).is_none(), + bindings + .insert(target.clone(), LoadedBinding { binding, bytes }) + .is_none(), "operator binding target {target} is duplicated" ); } @@ -333,14 +1669,14 @@ fn load_bindings(directory: &Path) -> Result> } fn resolve_selector( - bindings: &BTreeMap, + bindings: &BTreeMap, selector: &str, ) -> Result> { - let targets = if let Some(profile) = selector.strip_prefix("profile:") { + let mut targets = if let Some(profile) = selector.strip_prefix("profile:") { bindings .values() - .filter(|binding| binding.profiles.contains(profile)) - .map(|binding| binding.target.clone()) + .filter(|binding| binding.binding.profiles.contains(profile)) + .map(|binding| binding.binding.target.clone()) .collect::>() } else { ensure!( @@ -353,6 +1689,11 @@ fn resolve_selector( !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) } @@ -367,188 +1708,2119 @@ fn submit( fs::create_dir_all(parent)?; } let now = now_millis()?; - let record = DeploymentCommandRecord { + 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, - state: "pending".into(), - owner_instance_id: None, - started_at_unix_millis: None, - completed_at_unix_millis: None, - detail: String::new(), }; - record.validate()?; - let store = SingleFileMessagePackBackingStore::new(store_path); - let next = typed_envelope(&record, now)?; - if !store.compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: DeploymentCommandRecord::TYPE.into(), - key: record.command_id.clone(), - current: None, - }], - &[next], - )? { - bail!("deployment command id collided") - } - println!("{}", record.command_id); + 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 current = read_command(store_path, &record.command_id)? - .context("submitted deployment command disappeared")?; - match current.state.as_str() { - "succeeded" => { - println!("succeeded {}", current.detail); - return Ok(()); + 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}") } - "failed" => bail!("deployment failed: {}", current.detail), - _ if now_millis()? >= deadline => bail!("deployment command timed out"), - _ => thread::sleep(Duration::from_millis(250)), + 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 mut commands = read_commands(store_path)?; + 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(|command| command.command_id == command_id); + commands.retain(|stored| stored.value.command_id == command_id); ensure!(!commands.is_empty(), "deployment command is unknown"); } - commands.sort_by_key(|command| command.requested_at_unix_millis); - for command in commands { + 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, command.state, command.detail + command.command_id, command.selector, state, detail ); } Ok(()) } -fn claim_next(store_path: &Path, instance_id: &str) -> Result> { - let store = SingleFileMessagePackBackingStore::new(store_path); - let mut candidates = read_command_envelopes(store_path)? - .into_iter() - .filter(|(_, record)| record.state == "pending") - .collect::>(); - candidates.sort_by_key(|(_, command)| command.requested_at_unix_millis); - for (current, mut command) in candidates { - let now = now_millis()?; - command.state = "running".into(); - command.owner_instance_id = Some(instance_id.into()); - command.started_at_unix_millis = Some(now); - command.validate()?; - if store.compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: DeploymentCommandRecord::TYPE.into(), - key: command.command_id.clone(), - current: Some(current), - }], - &[typed_envelope(&command, now)?], - )? { - return Ok(Some(command)); - } +fn derived_command_status(transactions: &[&DeploymentTransaction]) -> (&'static str, String) { + if transactions.is_empty() { + return ("queued", String::new()); } - Ok(None) + 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) } -fn complete( - store_path: &Path, - running: &DeploymentCommandRecord, - result: Result, -) -> Result<()> { - let store = SingleFileMessagePackBackingStore::new(store_path); - let current = read_command_envelopes(store_path)? - .into_iter() - .find(|(_, command)| command.command_id == running.command_id) - .context("running deployment command disappeared")?; - ensure!( - current.1 == *running, - "deployment command changed while its owner was executing" - ); - let now = now_millis()?; - let mut terminal = running.clone(); - terminal.completed_at_unix_millis = Some(now); - match result { - Ok(detail) => { - terminal.state = "succeeded".into(); - terminal.detail = detail; +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)?; } - Err(error) => { - terminal.state = "failed".into(); - terminal.detail = truncate(&format!("{error:#}"), 2048); + #[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 }) } } - terminal.validate()?; +} + +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 { + let authenticated = self.authenticate_topology_bytes( + snapshot, + transaction, + &evidence.canonical_bytes, + None, + evidence.admitted_at_unix_millis, + )?; + validate_authenticated_evidence(evidence, &authenticated)?; + ensure!( + is_semantic_warming(&authenticated), + "durable Warming label is not exact semantic Warming" + ); + } + 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 { + if engine.resume_one_transaction()? { + thread::sleep(Duration::from_millis(engine.options.poll_millis)); + continue; + } + if engine.supervise_one_admitted_generation()? { + continue; + } + if 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 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; + } + match self.advance_transaction(current) { + Ok(()) => {} + Err(error) if current.value.phase < DeploymentPhase::Fencing => { + self.begin_pre_fencing_abort(current, error)?; + } + Err(error) => self.record_resumable_error(current, &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 { + return Ok(true); + } + } + Ok(false) + } + + 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.owns_target_authority()) + .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 busy = snapshot + .transactions + .iter() + .filter(|stored| stored.value.owns_target_authority()) + .map(|stored| stored.value.target.as_str()) + .collect::>(); + let mut admitted = snapshot.admitted.iter().collect::>(); + admitted.sort_by_key(|stored| stored.value.target.as_str()); + for current in admitted { + if busy.contains(current.value.target.as_str()) { + continue; + } + match self.refresh_admitted_topology(&snapshot, current) { + Ok(true) => return Ok(true), + Ok(false) => {} + Err(error) => eprintln!( + "Idunn preserved admitted {} after rejecting topology observation: {error:#}", + current.value.target + ), + } + if self + .workload + .observe( + ¤t.value.expected, + ¤t.value.activation, + ¤t.value.workload, + ) + .is_ok() + { + 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" + ); + return Ok(true); + } + Ok(false) + } + + 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(&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 expected = required(¤t.value.expected, "Expected projection")?; + let digest = self.topology().publish_expected(expected)?; + 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 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(&authenticated); + let latest = required( + &admitted.value.latest_odin_observation, + "sequence-admitted warming evidence", + )?; + if current.value.warming.as_ref() == Some(latest) { + ensure!(semantic_warming, "stored Warming receipt changed meaning"); + } else if semantic_warming { + let evidence = latest.clone(); + let _token = SequenceAdmittedWarming { + transaction_id: admitted.value.transaction_id.clone(), + evidence: evidence.clone(), + authenticated, + }; + return self.persist_same_phase(&admitted, |next| { + next.warming = Some(evidence); + Ok(()) + }); + } else { + return Ok(()); + } + } + + 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 driver = CultCacheWriteLeaseDriver::new(¤t.value.target, path); + driver.revoke_exact(Some(lease))?; + ensure!( + driver.observe_empty()?, + "incumbent write lease remained after exact fencing" + ); + } + 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" + ); + } + } + 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<()> { + if current.value.leasing.is_none() { + let now = now_millis()?; + let expected = required(¤t.value.expected, "Expected projection")?; + let evidence = if expected.write_lease_required { + let warming = self.rehydrate_warming_token(¤t.value, now)?; + ensure!( + warming.transaction_id() == current.value.transaction_id + && Some(warming.evidence_sha256()) + == current + .value + .warming + .as_ref() + .map(|value| value.canonical_sha256.as_str()), + "Warming token does not bind this transaction's durable admission" + ); + let activation = required(¤t.value.activation, "activation")?; + 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 snapshot = ControlSnapshot::read(&self.options.state_store)?; + let epoch = self + .exact_incumbent(&snapshot, ¤t.value)? + .and_then(|generation| generation.value.leasing.lease()) + .map_or(1, |lease| lease.lease_epoch.saturating_add(1)); + let warming_presence_sha256 = warming + .authenticated() + .record() + .signed_presence_sha256 + .clone() + .context("warming token has no signed presence")?; + 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, + lease_epoch: epoch, + issued_at_unix_millis: now, + }; + lease.validate()?; + let lease_sha256 = lease.canonical_sha256()?; + LeasingEvidence::Prepared { + lease, + lease_sha256, + } + } else { + LeasingEvidence::SkippedStateless + }; + return self.persist_same_phase(current, |next| { + next.leasing = Some(evidence); + next.updated_at_unix_millis = now; + Ok(()) + }); + } + + if let Some((lease, prepared_sha256)) = current + .value + .leasing + .as_ref() + .and_then(LeasingEvidence::prepared_lease) + { + let now = now_millis()?; + let expected = required(¤t.value.expected, "Expected projection")?; + let activation = required(¤t.value.activation, "activation")?; + let warming = self.rehydrate_warming_token(¤t.value, now)?; + ensure!( + warming.transaction_id() == current.value.transaction_id + && Some(warming.evidence_sha256()) + == current + .value + .warming + .as_ref() + .map(|value| value.canonical_sha256.as_str()), + "Warming token does not bind this transaction's durable admission" + ); + 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); + let granted_sha256 = driver.grant(expected, activation, &warming, lease)?; + ensure!( + granted_sha256 == prepared_sha256, + "granted write lease differs from the durable prepared lease" + ); + let lease = lease.clone(); + return self.persist_same_phase(current, |next| { + next.leasing = Some(LeasingEvidence::Granted { + lease, + lease_sha256: granted_sha256, + }); + next.updated_at_unix_millis = now; + Ok(()) + }); + } + + self.transition(current, DeploymentPhase::AwaitingReady) + } + + 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)?; + 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 now = now_millis()?; + 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); + if let Some((admitted, authenticated)) = + self.admit_latest_topology(current, current_lease)? + { + if admitted.envelope != current.envelope { + return Ok(()); + } + let latest = required( + &admitted.value.latest_odin_observation, + "latest sequence-admitted topology", + )?; + if current.value.ready.as_ref() != Some(latest) { + if is_semantic_ready(&authenticated) { + 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(()) + }); + } + return Ok(()); + } + } + let ready = self.rehydrate_ready_token(¤t.value, now, false)?; + ensure!( + ready.transaction_id() == current.value.transaction_id, + "Ready token belongs to another transaction" + ); + let evidence = if expected.route.is_some() { + let binding = current.value.plan.as_ref().unwrap().parsed_inputs()?.1; + let route_binding = binding.route.context("routed plan has no route binding")?; + let preflight = required(¤t.value.route_preflight, "route preflight")?; + let driver = NginxRouteDriver::new(route_binding); + let exact_candidate = RouteObservation { + route_id: preflight.route_id.clone(), + runtime_instance_id: preflight.candidate_runtime_instance_id.clone(), + membership_sha256: preflight.candidate_membership_sha256.clone(), + }; + ensure!( + exact_candidate.runtime_instance_id == activation.runtime_instance_id, + "route preflight belongs to another runtime instance" + ); + let observation = if driver.observe(expected, &exact_candidate)? { + exact_candidate + } else { + driver.promote(expected, &activation.runtime_instance_id, preflight)? + }; + ensure!( + driver.observe(expected, &observation)?, + "promoted route is not the exact candidate membership" + ); + RoutingEvidence::Promoted { observation } + } else { + RoutingEvidence::SkippedUnrouted + }; + return self.persist_same_phase(current, |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 now = now_millis()?; + 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 _ready = self.rehydrate_ready_token(¤t.value, now, false)?; + + if let Some(lease) = current + .value + .leasing + .as_ref() + .and_then(LeasingEvidence::lease) + { + let warming = self.rehydrate_warming_token(¤t.value, now)?; + 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)?, + "write lease changed before admission commit" + ); + } + if let Some(route) = current + .value + .routing + .as_ref() + .and_then(RoutingEvidence::observation) + { + let binding = 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(expected, route)?, + "route changed before admission commit" + ); + } + + let snapshot = ControlSnapshot::read(&self.options.state_store)?; + let incumbent = self.exact_incumbent(&snapshot, ¤t.value)?; + let odin_authority = self.current_odin_authority(&snapshot)?; + let generation = AdmittedGeneration::from_transaction(¤t.value, odin_authority, now)?; + let post_commit_cleanup = PostCommitCleanup { + incumbent: match incumbent { + Some(incumbent) => IncumbentCleanupEvidence::Pending { + generation_id: incumbent.value.generation_id.clone(), + workload: incumbent.value.workload.clone(), + }, + None => IncumbentCleanupEvidence::SkippedNoIncumbent, + }, + source: match current.value.command_kind { + CommandKind::Deploy => SourceCleanupEvidence::Pending, + CommandKind::Continuity => SourceCleanupEvidence::SkippedContinuity, + }, + }; + let mut complete = 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: current.value.transaction_id.clone(), + current: Some(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 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.owns_target_authority()) + .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 runtime_authority_parts( + &self, + plan: &CompiledDeploymentPlan, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + ) -> Result { + let binding = plan.parsed_inputs()?.1; + let provider_anchor = read_trust_anchor::( + &binding.runtime_identity.trust_anchor_store, + )?; + verify_runtime_authority( + expected, + activation, + &self.idunn_anchor, + &provider_anchor.public_key, + ) + } + + 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(&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, + ) -> Result { + let evidence = required(&transaction.warming, "durable warming evidence")?.clone(); + let snapshot = ControlSnapshot::read(&self.options.state_store)?; + let authenticated = self.authenticate_topology_bytes( + &snapshot, + transaction, + &evidence.canonical_bytes, + None, + evidence.admitted_at_unix_millis, + )?; + validate_authenticated_evidence(&evidence, &authenticated)?; + ensure!( + is_semantic_warming(&authenticated), + "durable warming evidence no longer authenticates as Warming" + ); + Ok(SequenceAdmittedWarming { + transaction_id: transaction.transaction_id.clone(), + evidence, + authenticated, + }) + } + + 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.evidence_sha256() == odin_topology_correlation_sha256 + && token.publisher_sequence() == *odin_topology_publisher_sequence, + "selected dependency authority changed before actuation" + ); + if selection.requirement.startup == StartupOrder::BeforeStart { + ensure!( + token.authenticated().record().ready, + "before-start dependency is not Ready" + ); + } + } + 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_stop: if current.value.workload.is_some() { + CleanupEvidence::Pending + } else { + CleanupEvidence::Skipped + }, + 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_stop == CleanupEvidence::Pending { + self.workload + .stop(required( + ¤t.value.workload, + "pre-fencing candidate observation", + )?) + .context("stopping exact pre-fence candidate")?; + return self.persist_same_phase(current, |next| { + next.pre_fencing_abort.as_mut().unwrap().candidate_stop = 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 expected_sha256 = topology.publish_expected(&incumbent.value.expected)?; + ensure!( + expected_sha256 == incumbent.value.expected.canonical_sha256()?, + "restored incumbent Expected receipt differs" + ); + if let Ok(observation) = self.workload.observe( + &incumbent.value.expected, + &incumbent.value.activation, + &incumbent.value.workload, + ) { + let activation_sha256 = topology.publish_observed_activation( + &incumbent.value.expected, + &incumbent.value.activation, + &observation, + )?; + ensure!( + activation_sha256 == incumbent.value.activation.canonical_sha256()?, + "restored incumbent activation receipt differs" + ); + } + } else { + self.topology() + .withdraw_expected(expected) + .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 + { + 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 prove_isolation( + candidate: &WorkloadObservation, + incumbent: Option<&WorkloadObservation>, +) -> Result { ensure!( - store.compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: DeploymentCommandRecord::TYPE.into(), - key: terminal.command_id.clone(), - current: Some(current.0), - }], - &[typed_envelope(&terminal, now)?], - )?, - "deployment command changed before its terminal receipt" + 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 read_commands(path: &Path) -> Result> { - Ok(read_command_envelopes(path)? - .into_iter() - .map(|(_, record)| record) - .collect()) +fn is_semantic_warming(authenticated: &AuthenticatedOdinRuntimeTopologyCorrelation) -> bool { + let record = authenticated.record(); + record.present + && !record.ready + && record.observed_presence_state.as_deref() == Some("warming") + && record.observed_write_lease_sha256.is_none() + && record.disagreements.is_empty() } -fn read_command(path: &Path, command_id: &str) -> Result> { - Ok(read_commands(path)? - .into_iter() - .find(|command| command.command_id == command_id)) +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_command_envelopes( - path: &Path, -) -> Result> { - if !path.exists() { - return Ok(Vec::new()); - } - SingleFileMessagePackBackingStore::new(path) - .pull_all_read_only_snapshot()? - .into_iter() - .map(|envelope| { - ensure!( - envelope.r#type == DeploymentCommandRecord::TYPE - && envelope.schema_id.as_deref() == Some(DEPLOYMENT_COMMAND_SCHEMA), - "Idunn control store contains a foreign document" - ); - let record: DeploymentCommandRecord = rmp_serde::from_slice(&envelope.payload)?; - ensure!( - rmp_serde::to_vec(&record)? == envelope.payload - && envelope.key == record.command_id, - "Idunn control store contains a noncanonical command" - ); - record.validate()?; - Ok((envelope, record)) - }) - .collect() -} - -fn typed_envelope(record: &DeploymentCommandRecord, millis: u64) -> Result { +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()?; - let stored_at = chrono::DateTime::from_timestamp_millis(i64::try_from(millis)?) - .context("deployment command timestamp is out of range")? - .to_rfc3339(); - Ok(CultCacheEnvelope { - key: record.command_id.clone(), - r#type: DeploymentCommandRecord::TYPE.into(), - payload: rmp_serde::to_vec(record)?, - stored_at, - schema_id: Some(DEPLOYMENT_COMMAND_SCHEMA.into()), - }) + 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 { @@ -559,6 +3831,18 @@ fn now_millis() -> Result { .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")) @@ -608,25 +3892,157 @@ fn require_value(value: &str, label: &str) -> Result<()> { 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 and continuity control plane\n\n\ + "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 declare build, package, launch, health, state, and capability semantics.\n\ - Operator bindings select source, runner, workload, route, brakes, and placement." + 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 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: PathBuf::from("/run/credentials/test"), + activation_credential_device: 1, + activation_credential_inode: 2, + activation_credential_uid: uid, + activation_credential_gid: uid, + activation_credential_mode: 0o400, + activation_credential_size: 32, + 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_has_no_raw_command_or_compiled_profile_authority() { + fn cli_exposes_only_declarative_commands() { for arguments in [ vec!["up", "ghostlight", "--deploy-command", "sh -c bad"], vec!["serve", "--swarm-profile", "yggdrasil-local"], @@ -652,6 +4068,268 @@ mod tests { } } + #[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 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_stop: 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 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 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()); + 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 source_identity_is_explicit_and_atomic() { let partial = parse( @@ -678,27 +4356,4 @@ mod tests { }) ); } - - #[test] - fn deployment_command_receipt_is_positional_and_fail_closed() -> Result<()> { - let record = DeploymentCommandRecord { - schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), - command_id: "up-test".into(), - selector: "ghostlight".into(), - requested_by: "operator".into(), - requested_at_unix_millis: 100, - state: "pending".into(), - owner_instance_id: None, - started_at_unix_millis: None, - completed_at_unix_millis: None, - detail: String::new(), - }; - record.validate()?; - let payload = rmp_serde::to_vec(&record)?; - assert_eq!(payload[0], 0x9a); - let mut invalid = record; - invalid.state = "succeeded".into(); - assert!(invalid.validate().is_err()); - Ok(()) - } } diff --git a/src/deployment.rs b/src/deployment.rs index d4fca8a..2dcd5b5 100644 --- a/src/deployment.rs +++ b/src/deployment.rs @@ -1,12 +1,14 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::{Component, Path, PathBuf}; -use anyhow::{Context, Result, bail, ensure}; +use anyhow::{bail, ensure, Context, Result}; 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.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"; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -172,6 +174,9 @@ pub struct MigrationDeclaration { #[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)] @@ -332,8 +337,8 @@ pub enum RunnerDriver { #[serde(deny_unknown_fields)] pub struct WorkloadBinding { pub driver: WorkloadDriver, - pub user: String, - pub group: String, + #[serde(default)] + pub state_group: Option, pub unit_prefix: String, pub release_root: PathBuf, #[serde(default)] @@ -346,8 +351,6 @@ pub struct WorkloadBinding { #[serde(default)] pub read_write_paths: BTreeSet, #[serde(default)] - pub capabilities: BTreeSet, - #[serde(default)] pub devices: BTreeSet, pub memory_mebibytes: u32, pub cpu_quota_percent: u32, @@ -590,6 +593,20 @@ impl TargetDeclaration { .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!( @@ -847,13 +864,19 @@ impl OperatorBinding { "runner {id} secret files and secret-read affordance disagree" ); } - require_identity(&self.workload.user, "workload user")?; - require_identity(&self.workload.group, "workload group")?; + let needs_state_group = + self.workload.state_root.is_some() || !self.workload.read_write_paths.is_empty(); ensure!( - !matches!(self.workload.user.as_str(), "root" | "0") - && !matches!(self.workload.group.as_str(), "root" | "0"), - "ordinary Idunn workloads cannot run as root" + 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( @@ -952,9 +975,6 @@ impl OperatorBinding { ); } } - for capability in &self.workload.capabilities { - require_value(capability, "workload capability")?; - } for name in self .workload .environment @@ -962,6 +982,11 @@ impl OperatorBinding { .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")?; @@ -996,11 +1021,11 @@ impl OperatorBinding { ); ensure!( self.placement.desired_replicas == 1, - "operator binding v1 admits exactly one replica" + "operator binding v2 admits exactly one replica" ); ensure!( self.placement.nodes.len() == 1, - "operator binding v1 admits exactly one node" + "operator binding v2 admits exactly one node" ); for node in &self.placement.nodes { require_id(node, "placement node")?; @@ -1154,8 +1179,27 @@ impl OperatorBinding { && !self .workload .secret_files - .contains_key(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT), - "operator binding cannot replace the standard Idunn runtime bundle" + .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 @@ -1165,6 +1209,12 @@ impl OperatorBinding { .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 @@ -1193,6 +1243,22 @@ impl OperatorBinding { .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" @@ -1503,7 +1569,7 @@ arguments = [ ] transport = "http" route_required = true -required_environment = ["GAMECULT_IDUNN_RUNTIME_BUNDLE", "TEST_SERVICE_BIND"] +required_environment = ["GAMECULT_IDUNN_CANDIDATE_BIND", "GAMECULT_IDUNN_PROCESS_WRITE_LEASE", "GAMECULT_IDUNN_RUNTIME_BUNDLE"] [service.health] contract = "test-service.cultnet-service-health" @@ -1534,7 +1600,7 @@ startup = "before-promotion" "#; const BINDING: &str = r#" -schema = "gamecult.idunn.operator_binding.v1" +schema = "gamecult.idunn.operator_binding.v2" target = "test-service" profiles = ["aetheria", "full-gamecult"] @@ -1561,8 +1627,7 @@ tmpfs_mebibytes = 1024 [workload] driver = "systemd-transient" -user = "test-service" -group = "test-service" +state_group = "test-service" unit_prefix = "idunn-test-service" release_root = "/srv/test-service/releases" state_root = "/var/lib/gamecult/test-service" @@ -1572,9 +1637,6 @@ hardening = "strict" memory_mebibytes = 2048 cpu_quota_percent = 200 -[workload.environment] -TEST_SERVICE_BIND = "idunn.private_endpoint" - [workload.argument_bindings] state_root = "/var/lib/gamecult/test-service" @@ -1693,13 +1755,33 @@ nodes = ["yggdrasil"] fn extra_operator_environment_is_rejected() { let recipe = TargetDeclaration::parse(RECIPE).unwrap(); let input = BINDING.replace( - "TEST_SERVICE_BIND = \"idunn.private_endpoint\"", - "TEST_SERVICE_BIND = \"idunn.private_endpoint\"\nUNDECLARED = \"no\"", + "[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 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( @@ -1709,6 +1791,28 @@ nodes = ["yggdrasil"] 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( @@ -1721,27 +1825,49 @@ nodes = ["yggdrasil"] #[test] fn workload_mount_cannot_bypass_write_lease_controlled_state() { let input = BINDING.replace( - "cpu_quota_percent = 200\n\n[workload.environment]", - "cpu_quota_percent = 200\nread_write_paths = [\"/var/lib/gamecult/test-service/world\"]\n\n[workload.environment]", + "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 v1_binding_is_explicitly_singleton() { - assert!( - OperatorBinding::parse( - &BINDING.replace("desired_replicas = 1", "desired_replicas = 2") - ) - .is_err() + 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( - "nodes = [\"yggdrasil\"]", - "nodes = [\"yggdrasil\", \"raven\"]" - )) - .is_err() + 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] @@ -1773,7 +1899,8 @@ nodes = ["yggdrasil"] .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(); @@ -1792,6 +1919,7 @@ nodes = ["yggdrasil"] "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, ""); @@ -1799,6 +1927,7 @@ nodes = ["yggdrasil"] 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", diff --git a/src/deployment_plan.rs b/src/deployment_plan.rs index f3a9571..91096f6 100644 --- a/src/deployment_plan.rs +++ b/src/deployment_plan.rs @@ -1,23 +1,24 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::PathBuf; -use anyhow::{Context, Result, bail, ensure}; +use anyhow::{bail, ensure, Context, Result}; pub use cultnet_rs::IdunnExpectedIncarnationRecord as ExpectedIncarnation; use cultnet_rs::{ - GameCultRuntimeCapability, IDUNN_EXPECTED_INCARNATION_SCHEMA, IdunnExpectedDependency, - IdunnExpectedRoute, + IdunnExpectedCapability, IdunnExpectedDependency, IdunnExpectedRoute, + IDUNN_EXPECTED_INCARNATION_SCHEMA, }; 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, + capability_compatible, CapabilityDependency, DependencyKind, ExternalCapabilityBinding, + OperatorBinding, ServiceTransport, SourceSelectionPolicy, StartupOrder, StateDeclaration, + TargetDeclaration, }; pub const SOURCE_SELECTION_FACTS_SCHEMA: &str = "idunn.source_selection_facts.v1"; -pub const COMPILED_DEPLOYMENT_PLAN_SCHEMA: &str = "idunn.compiled_deployment_plan.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)] @@ -132,13 +133,15 @@ impl SourceSelectionFacts { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] -pub enum ExpectedProviderAuthority { - ManagedIncarnation { +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, @@ -147,9 +150,9 @@ pub enum ExpectedProviderAuthority { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ExpectedProviderRef { +pub struct DependencyProviderRef { pub provider_id: String, - pub authority: ExpectedProviderAuthority, + pub authority: DependencyProviderAuthority, pub capability: String, pub schema: String, pub compatibility: String, @@ -157,29 +160,39 @@ pub struct ExpectedProviderRef { pub endpoint: Option, } -impl ExpectedProviderRef { +impl DependencyProviderRef { pub fn validate(&self) -> Result<()> { - require_token(&self.provider_id, "expected provider id")?; + require_token(&self.provider_id, "dependency provider id")?; require_contract(&self.capability, &self.schema, &self.compatibility)?; - ensure!(self.capacity > 0, "expected provider capacity is zero"); + ensure!(self.capacity > 0, "dependency provider capacity is zero"); if let Some(endpoint) = &self.endpoint { - require_value(endpoint, "expected provider endpoint")?; + require_value(endpoint, "dependency provider endpoint")?; } match &self.authority { - ExpectedProviderAuthority::ManagedIncarnation { + 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" + ); } - ExpectedProviderAuthority::ExternalOperatorBinding { binding_target } => { + DependencyProviderAuthority::ExternalOperatorBinding { binding_target } => { require_token(binding_target, "external binding target")?; ensure!( self.endpoint.is_some(), @@ -204,14 +217,14 @@ impl ExpectedProviderRef { fn is_external_binding(&self) -> bool { matches!( &self.authority, - ExpectedProviderAuthority::ExternalOperatorBinding { .. } + DependencyProviderAuthority::ExternalOperatorBinding { .. } ) } } pub fn external_binding_provider_refs( binding: &OperatorBinding, -) -> Result> { +) -> Result> { binding.validate()?; let providers = binding .external_capabilities @@ -227,10 +240,10 @@ pub fn external_binding_provider_refs( fn expected_external_provider( binding_target: &str, capability: &ExternalCapabilityBinding, -) -> ExpectedProviderRef { - ExpectedProviderRef { +) -> DependencyProviderRef { + DependencyProviderRef { provider_id: capability.provider_id.clone(), - authority: ExpectedProviderAuthority::ExternalOperatorBinding { + authority: DependencyProviderAuthority::ExternalOperatorBinding { binding_target: binding_target.to_owned(), }, capability: capability.capability.clone(), @@ -241,34 +254,61 @@ fn expected_external_provider( } } -fn managed_expected_provider_refs( - expected_incarnations: &[ExpectedIncarnation], -) -> Result> { +/// 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.candidate_endpoint.clone()); let mut providers = Vec::new(); - for expected in expected_incarnations { - expected.validate()?; - let expected_projection_sha256 = expected.canonical_sha256()?; - let endpoint = expected - .route - .as_ref() - .map(|route| route.candidate_endpoint.clone()); - for capability in &expected.capabilities { - providers.push(ExpectedProviderRef { - provider_id: expected.runtime_id.clone(), - authority: ExpectedProviderAuthority::ManagedIncarnation { - 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(), - }, - capability: capability.capability.clone(), - schema: capability.schema.clone(), - compatibility: capability.compatibility.clone(), - capacity: capability.capacity, - endpoint: endpoint.clone(), - }); - } + for capability in &observed.observed_capabilities { + providers.push(DependencyProviderRef { + provider_id: observed.runtime_id.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) } @@ -277,7 +317,7 @@ fn managed_expected_provider_refs( #[serde(deny_unknown_fields)] pub struct DependencySelection { pub requirement: CapabilityDependency, - pub provider: Option, + pub provider: Option, } impl DependencySelection { @@ -321,7 +361,7 @@ impl DependencySelection { ) = match &self.provider { None => (None, None, None, None), Some(provider) => match &provider.authority { - ExpectedProviderAuthority::ManagedIncarnation { + DependencyProviderAuthority::ManagedReady { expected_projection_sha256, .. } => ( @@ -330,7 +370,7 @@ impl DependencySelection { Some(expected_projection_sha256.clone()), provider.endpoint.clone(), ), - ExpectedProviderAuthority::ExternalOperatorBinding { .. } => ( + DependencyProviderAuthority::ExternalOperatorBinding { .. } => ( Some(provider.provider_id.clone()), Some("external-operator-binding".into()), None, @@ -355,7 +395,7 @@ impl DependencySelection { pub fn select_dependencies( declaration: &TargetDeclaration, - providers: &[ExpectedProviderRef], + providers: &[DependencyProviderRef], ) -> Result> { declaration.validate()?; let mut unique_contracts = BTreeSet::new(); @@ -368,7 +408,7 @@ pub fn select_dependencies( provider.schema.as_str(), provider.compatibility.as_str(), )), - "expected provider contract is duplicated" + "dependency provider contract is duplicated" ); } for conflict in &declaration.conflicts { @@ -508,14 +548,14 @@ impl CompiledDeploymentPlan { } #[allow(clippy::too_many_arguments)] -pub fn compile_deployment_plan( +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_expected_incarnations: &[ExpectedIncarnation], + 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")?; @@ -533,7 +573,10 @@ pub fn compile_deployment_plan( created_at_unix_millis >= source.selected_at_unix_millis, "deployment plan predates source selection" ); - let mut providers = managed_expected_provider_refs(managed_expected_incarnations)?; + 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 { @@ -697,11 +740,11 @@ impl SealedRelease { let mut capabilities = declaration .provides .iter() - .map(|capability| GameCultRuntimeCapability { + .map(|capability| IdunnExpectedCapability { capability: capability.capability.clone(), schema: capability.schema.clone(), compatibility: capability.compatibility.clone(), - capacity: capability.capacity, + minimum_capacity: capability.capacity, }) .collect::>(); capabilities.sort_by(|left, right| { @@ -951,6 +994,13 @@ fn sha256_id(bytes: &[u8]) -> String { #[cfg(test)] mod tests { use super::*; + use cultnet_rs::{ + authenticate_odin_runtime_topology_correlation, enroll_service_identity_at, + verify_runtime_authority, GameCultProviderHealthIdentity, GameCultRuntimeCapability, + IdunnRuntimeActivationLaunch, IdunnServiceIdentity, OdinRuntimeTopologyCorrelationPurpose, + OdinRuntimeTopologyCorrelationRecord, OdinTopologyAuthenticationContext, + OdinTopologyIdentity, ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA, + }; const RECIPE: &str = r#" schema = "gamecult.idunn.target_declaration.v1" @@ -981,9 +1031,12 @@ executable = true [service] executable_artifact = "daemon" +arguments = [ + { kind = "binding", name = "state_root" }, +] transport = "http" route_required = true -required_environment = ["GAMECULT_IDUNN_RUNTIME_BUNDLE", "SERVICE_BIND"] +required_environment = ["GAMECULT_IDUNN_CANDIDATE_BIND", "GAMECULT_IDUNN_RUNTIME_BUNDLE"] [service.health] contract = "service.health" @@ -1013,7 +1066,7 @@ compatibility = "v1" "#; const BINDING: &str = r#" -schema = "gamecult.idunn.operator_binding.v1" +schema = "gamecult.idunn.operator_binding.v2" target = "service" [repository] @@ -1038,8 +1091,7 @@ tmpfs_mebibytes = 512 [workload] driver = "systemd-transient" -user = "service" -group = "service" +state_group = "service" unit_prefix = "idunn-service" release_root = "/srv/service/releases" state_root = "/var/lib/gamecult/service" @@ -1049,8 +1101,8 @@ hardening = "strict" memory_mebibytes = 1024 cpu_quota_percent = 100 -[workload.environment] -SERVICE_BIND = "idunn.private_endpoint" +[workload.argument_bindings] +state_root = "/var/lib/gamecult/service" [runtime_identity] runtime_id = "service-yggdrasil" @@ -1124,17 +1176,94 @@ nodes = ["yggdrasil"] stable_endpoint: "tcp://10.77.0.1:17871".into(), candidate_endpoint: "tcp://127.0.0.1:17871".into(), }), - capabilities: vec![GameCultRuntimeCapability { + capabilities: vec![IdunnExpectedCapability { capability: "odin.verse-rendezvous".into(), schema: "odin.verse-topology.v1".into(), compatibility: "v1".into(), - capacity: 1, + minimum_capacity: 1, }], dependencies: Vec::new(), } } + fn ready_odin_provider(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.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-yggdrasil", 1)]; + plan_with(&providers) + } + + fn plan_with(providers: &[SequenceAdmittedReady]) -> CompiledDeploymentPlan { compile_deployment_plan( RECIPE.as_bytes(), BINDING.as_bytes(), @@ -1142,7 +1271,7 @@ nodes = ["yggdrasil"] "service-incarnation-1", Some(18001), 110, - &[odin()], + providers, ) .unwrap() } @@ -1170,8 +1299,9 @@ nodes = ["yggdrasil"] #[test] fn compiler_parses_the_exact_bytes_it_receipts() { - let first = plan(); - let second = plan(); + let providers = [ready_odin_provider("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()); @@ -1183,18 +1313,17 @@ nodes = ["yggdrasil"] "contract = \"service.health\"", "contract = \"service.health.v2\"", ); - assert!( - compile_deployment_plan( - changed.as_bytes(), - BINDING.as_bytes(), - source(RECIPE), - "service-incarnation-2", - Some(18002), - 111, - &[odin()], - ) - .is_err() - ); + let providers = [ready_odin_provider("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 @@ -1247,16 +1376,29 @@ nodes = ["yggdrasil"] } #[test] - fn dependency_selection_uses_expected_identity_without_readiness() { + fn dependency_selection_uses_observed_ready_capacity_and_stable_identity_order() { let declaration = TargetDeclaration::parse(RECIPE).unwrap(); - let mut later = odin(); - later.runtime_id = "odin-z".into(); - let providers = managed_expected_provider_refs(&[later, odin()]).unwrap(); + let admitted = [ + ready_odin_provider("odin-z", 4), + ready_odin_provider("odin-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!(matches!( + &selected[0].provider.as_ref().unwrap().authority, + DependencyProviderAuthority::ManagedReady { + odin_topology_publisher_sequence: 7, + .. + } + )); } #[test] @@ -1276,7 +1418,7 @@ nodes = ["yggdrasil"] let selected = select_dependencies(&declaration, &providers).unwrap(); assert!(matches!( &providers[0].authority, - ExpectedProviderAuthority::ExternalOperatorBinding { .. } + DependencyProviderAuthority::ExternalOperatorBinding { .. } )); assert_eq!(providers[0].capacity, 2); assert_eq!( @@ -1349,7 +1491,7 @@ nodes = ["yggdrasil"] "service-incarnation-sorted", Some(18002), 111, - &[odin()], + &[ready_odin_provider("odin-yggdrasil", 1)], ) .unwrap(); let release = SealedRelease::new( diff --git a/src/drivers.rs b/src/drivers.rs index cffc796..a6875ab 100644 --- a/src/drivers.rs +++ b/src/drivers.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; use std::ffi::{OsStr, OsString}; -use std::fs; -use std::io::{ErrorKind, Write}; +use std::fs::{self, OpenOptions}; +use std::io::{ErrorKind, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; use std::thread; @@ -16,8 +16,10 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use uuid::Uuid; +use crate::control_plane::SequenceAdmittedWarming; use crate::deployment::{ - ArtifactOutput, ArtifactSource, IDUNN_RUNTIME_BUNDLE_ENVIRONMENT, LaunchArgument, + ArtifactOutput, ArtifactSource, IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT, + IDUNN_RUNTIME_BUNDLE_ENVIRONMENT, IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, LaunchArgument, OperatorBinding, RouteBinding, RouteDriver, RunnerBinding, SourceSelectionPolicy, TargetDeclaration, WorkloadNetwork, }; @@ -27,11 +29,10 @@ use crate::deployment_plan::{ }; use cultnet_rs::{ IDUNN_EXPECTED_INCARNATION_SCHEMA, IDUNN_PROCESS_WRITE_LEASE_SCHEMA, - IDUNN_RUNTIME_ACTIVATION_SCHEMA, IdunnExpectedIncarnationRecord, IdunnProcessWriteLeaseRecord, - IdunnRuntimeActivationRecord, ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA, - OdinRuntimeTopologyCorrelationPurpose, OdinRuntimeTopologyCorrelationRecord, - OdinTopologyIdentity, ServiceIdentityProfile, ServiceIdentitySignature, - ServiceIdentityTrustAnchor, verify_service_identity_signature, + IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, IDUNN_RUNTIME_ACTIVATION_SCHEMA, + IdunnExpectedIncarnationRecord, IdunnProcessWriteLeaseRecord, IdunnRuntimeActivationLaunch, + IdunnRuntimeActivationRecord, IdunnRuntimeActivationSigner, + ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA, OdinRuntimeTopologyCorrelationRecord, }; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -141,24 +142,91 @@ pub struct InstalledReleaseObservation { 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, +} + #[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 user: String, - pub group: 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: PathBuf, + pub activation_credential_device: u64, + pub activation_credential_inode: u64, + pub activation_credential_uid: u32, + pub activation_credential_gid: u32, + pub activation_credential_mode: u32, + pub activation_credential_size: u64, + 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, } pub trait WorkloadPort { @@ -168,7 +236,14 @@ pub trait WorkloadPort { release: &MaterializedRelease, ) -> Result; - fn start( + fn prepare_activation( + &self, + plan: &CompiledDeploymentPlan, + expected: &IdunnExpectedIncarnationRecord, + launch: IdunnRuntimeActivationLaunch, + ) -> Result; + + fn start_prepared( &self, plan: &CompiledDeploymentPlan, release: &SealedRelease, @@ -188,37 +263,21 @@ pub trait WorkloadPort { } pub trait TopologyPort { - type ReadyReceipt: Clone; - fn publish_expected(&self, expected: &IdunnExpectedIncarnationRecord) -> Result; + fn withdraw_expected(&self, expected: &IdunnExpectedIncarnationRecord) -> Result<()>; fn publish_observed_activation( &self, expected: &IdunnExpectedIncarnationRecord, activation: &IdunnRuntimeActivationRecord, observation: &WorkloadObservation, ) -> Result; - fn present( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result>; - fn ready( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - write_lease_sha256: Option<&str>, - ) -> Result>; + fn receive(&self, target: &str) -> Result>; } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct PresenceObservation { - pub correlation_sha256: String, - pub signed_presence_sha256: Option, - pub runtime_instance_id: Option, - pub present: bool, - pub state: Option, - pub write_lease_sha256: Option, - pub disagreements: Vec, +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReceivedOdinTopologyCorrelation { + pub target: String, + pub canonical_bytes: Vec, } pub trait WriteLeasePort { @@ -228,14 +287,14 @@ pub trait WriteLeasePort { &self, expected: &IdunnExpectedIncarnationRecord, activation: &IdunnRuntimeActivationRecord, - warming: &PresenceObservation, + warming: &SequenceAdmittedWarming, lease: &IdunnProcessWriteLeaseRecord, ) -> Result; fn observe( &self, expected: &IdunnExpectedIncarnationRecord, activation: &IdunnRuntimeActivationRecord, - warming: &PresenceObservation, + warming: &SequenceAdmittedWarming, lease: &IdunnProcessWriteLeaseRecord, ) -> Result; } @@ -247,16 +306,27 @@ pub struct RouteObservation { pub membership_sha256: String, } +#[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 trait RoutePort { fn preflight( &self, expected: &IdunnExpectedIncarnationRecord, runtime_instance_id: &str, - ) -> Result<()>; + incumbent: Option<&RouteObservation>, + ) -> Result; fn promote( &self, expected: &IdunnExpectedIncarnationRecord, runtime_instance_id: &str, + preflight: &RoutePreflightReceipt, ) -> Result; fn observe( &self, @@ -1303,14 +1373,16 @@ 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("systemd-run"), - systemctl_program: PathBuf::from("systemctl"), + 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"), } } } @@ -1321,9 +1393,15 @@ impl SystemdTransientWorkloadDriver { 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() { @@ -1348,6 +1426,155 @@ impl SystemdTransientWorkloadDriver { 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 stop_submitted_unit(&self, unit: &str, expected_description: &str) -> Result<()> { + let Some(values) = self.show_unit(unit)? else { + return Ok(()); + }; + 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(values) = self.show_unit(unit)? { + ensure!( + values + .get("ActiveState") + .is_some_and(|state| { matches!(state.as_str(), "inactive" | "failed") }), + "submitted systemd unit remained active after stop" + ); + } + Ok(()) + } + + fn failed_start_error( + &self, + primary: anyhow::Error, + unit: &str, + expected_description: &str, + credential_source: &Path, + ) -> anyhow::Error { + let stop = self.stop_submitted_unit(unit, expected_description); + let remove = remove_activation_credential_source(credential_source); + match (stop, remove) { + (Ok(()), Ok(())) => primary, + (Err(stop), Ok(())) => { + primary.context(format!("stopping failed candidate also failed: {stop:#}")) + } + (Ok(()), Err(remove)) => primary.context(format!( + "deleting failed candidate activation credential also failed: {remove:#}" + )), + (Err(stop), Err(remove)) => primary.context(format!( + "failed candidate cleanup also failed (stop: {stop:#}; credential delete: {remove:#})" + )), + } + } + fn install_release( &self, plan: &CompiledDeploymentPlan, @@ -1460,6 +1687,10 @@ impl SystemdTransientWorkloadDriver { } 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"), @@ -1471,12 +1702,30 @@ impl SystemdTransientWorkloadDriver { 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=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 = @@ -1510,8 +1759,17 @@ impl SystemdTransientWorkloadDriver { 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], ) -> Result { + ensure!( + service_credential_names + .windows(2) + .all(|pair| pair[0] < pair[1]), + "service credential names are not unique and sorted" + ); let values = self .show_unit(unit)? .with_context(|| format!("systemd unit {unit} is absent"))?; @@ -1529,9 +1787,53 @@ impl SystemdTransientWorkloadDriver { .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 user = required_systemd_property(&values, "User")?.to_owned(); - let group = required_systemd_property(&values, "Group")?.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 == "[unprintable]", + "systemd workload isolation properties differ from the Idunn contract" + ); let working_directory = PathBuf::from(required_systemd_property(&values, "WorkingDirectory")?); ensure!( @@ -1550,20 +1852,91 @@ impl SystemdTransientWorkloadDriver { .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 executable = fs::read_link(process_root.join("exe")) + 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_id(&fs::read(&executable)?); + let executable_sha256 = sha256_reader(&mut executable_file)?; let process_start_time = linux_process_start_time(&process_root.join("stat"))?; - let process_control_groups = fs::read_to_string(process_root.join("cgroup"))?; + let process_security = linux_process_security(&process_root.join("status"), main_pid)?; ensure!( - process_control_groups.lines().any(|line| { - line.split_once("::") - .is_some_and(|(_, path)| path == control_group) - }), + 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"))?; @@ -1583,23 +1956,184 @@ impl SystemdTransientWorkloadDriver { runtime_bundle.is_absolute(), "runtime bundle path is not absolute" ); + let credentials_directory = PathBuf::from(required_process_environment_value( + &process_environment, + "CREDENTIALS_DIRECTORY", + )?); + ensure!( + credentials_directory == Path::new("/run/credentials").join(unit), + "systemd MainPID exposed an unexpected credential directory" + ); + let credential_path = path_inside_process_root( + &process_root.join("root"), + &credentials_directory.join(IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME), + )?; + let credential_file = open_native_read_only(&credential_path).with_context(|| { + format!( + "opening delivered activation credential {}", + credential_path.display() + ) + })?; + let credential_metadata = credential_file.metadata()?; + ensure!( + credential_metadata.is_file() && credential_metadata.len() == 32, + "delivered activation credential is not one exact 32-byte native file" + ); + let activation_signer = + IdunnRuntimeActivationSigner::from_credential_reader(credential_file)?; + ensure!( + activation_signer.identity_id() == activation_signer_identity_id + && activation_signer.public_key() == activation_signer_public_key, + "delivered activation credential differs from the Idunn-signed activation" + ); + #[cfg(unix)] + let ( + activation_credential_device, + activation_credential_inode, + activation_credential_uid, + activation_credential_gid, + activation_credential_mode, + ) = { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + ( + credential_metadata.dev(), + credential_metadata.ino(), + credential_metadata.uid(), + credential_metadata.gid(), + credential_metadata.permissions().mode() & 0o777, + ) + }; + #[cfg(not(unix))] + let ( + activation_credential_device, + activation_credential_inode, + activation_credential_uid, + activation_credential_gid, + activation_credential_mode, + ) = (0, 0, 0, 0, 0); + ensure!( + activation_credential_uid == process_security.uids[0] + && activation_credential_gid == process_security.gids[0] + && activation_credential_mode == 0o400, + "delivered activation credential is not readable only by the workload identity" + ); + let mut service_credentials = Vec::new(); + for name in service_credential_names { + let delivered_path = credentials_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 == values + && 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(), - user, - group, 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, + activation_credential_device, + activation_credential_inode, + activation_credential_uid, + activation_credential_gid, + activation_credential_mode, + activation_credential_size: credential_metadata.len(), + activation_signer_identity_id: activation_signer.identity_id(), + activation_signer_public_key: activation_signer.public_key(), + service_credentials, }) } @@ -1629,12 +2163,18 @@ impl SystemdTransientWorkloadDriver { &self, binding: &OperatorBinding, bundle: &Path, + expected: &IdunnExpectedIncarnationRecord, + unit: &str, ) -> Result> { let mut environment = binding.workload.environment.clone(); - for (name, path) in &binding.workload.secret_files { + let credentials_directory = Path::new("/run/credentials").join(unit); + for name in binding.workload.secret_files.keys() { ensure!( environment - .insert(name.clone(), path.display().to_string()) + .insert( + name.clone(), + credentials_directory.join(name).display().to_string(), + ) .is_none(), "workload environment and secret bindings collide" ); @@ -1648,6 +2188,42 @@ impl SystemdTransientWorkloadDriver { .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) } @@ -1658,9 +2234,11 @@ impl SystemdTransientWorkloadDriver { 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)?; + let environment = self.launch_environment(binding, bundle, expected, &observation.unit)?; let environment_names = environment.keys().cloned().collect::>(); let expected_description = format!( "Idunn {} {}", @@ -1670,16 +2248,51 @@ impl SystemdTransientWorkloadDriver { .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 expected_credentials_directory = Path::new("/run/credentials").join(&observation.unit); ensure!( observation.unit_description == expected_description - && observation.user == binding.workload.user - && observation.group == binding.workload.group + && 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 == "[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)?), + == sha256_id(&rmp_serde::to_vec(&environment)?) + && observation.activation_credential_size == 32 + && observation.activation_signer_identity_id + == activation.activation_signer_identity_id + && observation.activation_signer_public_key + == activation.activation_signer_public_key + && 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!( @@ -1690,12 +2303,33 @@ impl SystemdTransientWorkloadDriver { 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, + credential_source: &Path, unit: &str, ) -> Result<()> { ensure!( @@ -1716,6 +2350,8 @@ impl SystemdTransientWorkloadDriver { .contains_key(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT), "operator binding attempts to replace the Idunn runtime bundle" ); + validate_service_credential_sources(&binding.workload.secret_files)?; + 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); @@ -1730,11 +2366,21 @@ impl SystemdTransientWorkloadDriver { ); 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"), @@ -1743,10 +2389,16 @@ impl SystemdTransientWorkloadDriver { OsString::from("--property=ProtectKernelTunables=yes"), OsString::from("--property=RestrictSUIDSGID=yes"), OsString::from("--property=LockPersonality=yes"), - OsString::from("--property=UMask=0027"), + OsString::from("--property=UMask=0007"), OsString::from(format!("--property=Description={unit_description}")), - OsString::from(format!("--property=User={}", binding.workload.user)), - OsString::from(format!("--property=Group={}", binding.workload.group)), + OsString::from(format!( + "--property=InaccessiblePaths={}", + self.credential_root.display() + )), + OsString::from(format!( + "--property=LoadCredential={IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME}:{}", + credential_source.display() + )), OsString::from(format!( "--property=MemoryMax={}M", binding.workload.memory_mebibytes @@ -1758,11 +2410,10 @@ impl SystemdTransientWorkloadDriver { OsString::from(format!("--working-directory={}", installed.display())), OsString::from(format!("--property=ReadOnlyPaths={}", installed.display())), OsString::from(format!("--property=ReadOnlyPaths={}", bundle.display())), - OsString::from(format!( - "--setenv={IDUNN_RUNTIME_BUNDLE_ENVIRONMENT}={}", - bundle.display() - )), ]; + 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")); } @@ -1775,7 +2426,7 @@ impl SystemdTransientWorkloadDriver { 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={}", + "--property=ReadOnlyPaths=-{}", path.display() ))); } @@ -1803,29 +2454,12 @@ impl SystemdTransientWorkloadDriver { ))); } } - let capabilities = binding - .workload - .capabilities - .iter() - .cloned() - .collect::>() - .join(" "); - args.push(OsString::from(format!( - "--property=CapabilityBoundingSet={capabilities}" - ))); - args.push(OsString::from(format!( - "--property=AmbientCapabilities={capabilities}" - ))); - for (name, value) in &binding.workload.environment { + for (name, value) in environment { args.push(OsString::from(format!("--setenv={name}={value}"))); } for (name, path) in &binding.workload.secret_files { args.push(OsString::from(format!( - "--property=ReadOnlyPaths={}", - path.display() - ))); - args.push(OsString::from(format!( - "--setenv={name}={}", + "--property=LoadCredential={name}:{}", path.display() ))); } @@ -1844,7 +2478,64 @@ impl WorkloadPort for SystemdTransientWorkloadDriver { self.install_release(plan, release) } - fn start( + 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, @@ -1864,6 +2555,7 @@ impl WorkloadPort for SystemdTransientWorkloadDriver { "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); @@ -1872,58 +2564,160 @@ impl WorkloadPort for SystemdTransientWorkloadDriver { &activation.runtime_instance_id, )?; let bundle = self.prepare_runtime_bundle(&binding, expected, activation)?; + let service_credential_names = binding + .workload + .secret_files + .keys() + .cloned() + .collect::>(); let environment_names = self - .launch_environment(&binding, &bundle)? + .launch_environment(&binding, &bundle, expected, &unit)? .into_keys() .collect::>(); - if self.show_unit(&unit)?.is_some() { - let observation = self.observe_unit( - &unit, - &executable, - &activation.runtime_instance_id, - &environment_names, - )?; - self.validate_launch_observation( - &observation, + let unit_description = format!( + "Idunn {} {}", + binding.target, activation.runtime_instance_id + ); + let credential_source = self.activation_credential_source(activation)?; + let unit_exists = self.show_unit(&unit)?.is_some(); + match fs::symlink_metadata(&credential_source) { + Ok(_) => { + if let Err(error) = + self.validate_prepared_activation_credential(activation, &credential_source) + { + return if unit_exists { + Err(self.failed_start_error( + error, + &unit, + &unit_description, + &credential_source, + )) + } else { + match remove_activation_credential_source(&credential_source) { + Ok(()) => Err(error), + Err(cleanup) => Err(error.context(format!( + "deleting mismatched prepared credential also failed: {cleanup:#}" + ))), + } + }; + } + } + Err(error) if error.kind() == ErrorKind::NotFound && unit_exists => {} + Err(error) if error.kind() == ErrorKind::NotFound => { + bail!( + "prepared activation has neither a credential source nor an existing exact unit" + ) + } + Err(error) => { + return Err(error).with_context(|| { + format!( + "inspecting prepared activation credential {}", + credential_source.display() + ) + }); + } + } + if !unit_exists { + if let Err(error) = self.start_transient( &declaration, &binding, &installed.root, &bundle, - )?; - ensure!( - observation.executable_sha256 == expected.artifact_sha256, - "running workload executable differs from Expected" - ); - return Ok(observation); + expected, + &credential_source, + &unit, + ) { + return Err(self.failed_start_error( + error, + &unit, + &unit_description, + &credential_source, + )); + } } - self.start_transient(&declaration, &binding, &installed.root, &bundle, &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, ) { Ok(observation) => { - self.validate_launch_observation( + let validation = self.validate_launch_observation( &observation, &declaration, &binding, &installed.root, &bundle, - )?; - ensure!( - observation.executable_sha256 == expected.artifact_sha256, - "started workload executable differs from Expected" + expected, + &activation, ); - return Ok(observation); + match validation.and_then(|()| { + ensure!( + observation.executable_sha256 == expected.artifact_sha256, + "started workload executable differs from Expected" + ); + Ok(()) + }) { + Ok(()) => { + if let Err(error) = + remove_activation_credential_source(&credential_source) + { + return Err(self.failed_start_error( + error.context( + "deleting observed one-shot activation credential source", + ), + &unit, + &unit_description, + &credential_source, + )); + } + let after_unlink = self.observe_unit( + &unit, + &executable, + &activation.runtime_instance_id, + &activation.activation_signer_identity_id, + &activation.activation_signer_public_key, + &environment_names, + &service_credential_names, + ); + return match after_unlink { + Ok(after_unlink) if after_unlink == observation => Ok(after_unlink), + Ok(_) => Err(self.failed_start_error( + anyhow::anyhow!( + "workload identity changed after activation source deletion" + ), + &unit, + &unit_description, + &credential_source, + )), + Err(error) => Err(self.failed_start_error( + error.context( + "reobserving copied activation credential after source deletion", + ), + &unit, + &unit_description, + &credential_source, + )), + }; + } + 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"))) + Err(self.failed_start_error( + last_error.unwrap_or_else(|| anyhow::anyhow!("systemd did not expose the candidate")), + &unit, + &unit_description, + &credential_source, + )) } fn observe( @@ -1942,14 +2736,41 @@ impl WorkloadPort for SystemdTransientWorkloadDriver { let observed = self.observe_unit( &prior.unit, &prior.executable, - &prior.runtime_instance_id, + &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::>(), )?; ensure!( observed == *prior && observed.executable_sha256 == expected.artifact_sha256, "native workload identity changed after observation" ); - Ok(observed) + 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::>(), + )?; + ensure!( + after_unlink == observed, + "native workload identity changed after recovered credential cleanup" + ); + Ok(after_unlink) } fn stop(&self, observation: &WorkloadObservation) -> Result<()> { @@ -1963,7 +2784,14 @@ impl WorkloadPort for SystemdTransientWorkloadDriver { &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::>(), )?; ensure!( current == *observation, @@ -1972,6 +2800,7 @@ impl WorkloadPort for SystemdTransientWorkloadDriver { } 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" ); @@ -2051,7 +2880,7 @@ impl CultCacheWriteLeaseDriver { &self, expected: &IdunnExpectedIncarnationRecord, activation: &IdunnRuntimeActivationRecord, - warming: &PresenceObservation, + warming: &SequenceAdmittedWarming, lease: &IdunnProcessWriteLeaseRecord, ) -> Result<()> { expected.validate()?; @@ -2059,6 +2888,7 @@ impl CultCacheWriteLeaseDriver { lease.validate()?; let expected_sha256 = expected.canonical_sha256()?; let activation_sha256 = activation.canonical_sha256()?; + let warming = warming.authenticated().record(); let warming_presence_sha256 = warming .signed_presence_sha256 .as_deref() @@ -2085,10 +2915,11 @@ impl CultCacheWriteLeaseDriver { .context("write-lease Expected has no state contract")? && lease.warming_presence_sha256 == warming_presence_sha256 && warming.present - && warming.state.as_deref() == Some("warming") + && !warming.ready + && warming.observed_presence_state.as_deref() == Some("warming") && warming.runtime_instance_id.as_deref() == Some(activation.runtime_instance_id.as_str()) - && warming.write_lease_sha256.is_none() + && warming.observed_write_lease_sha256.is_none() && warming.disagreements.is_empty(), "process write lease does not bind the exact warming candidate" ); @@ -2129,7 +2960,7 @@ impl WriteLeasePort for CultCacheWriteLeaseDriver { &self, expected: &IdunnExpectedIncarnationRecord, activation: &IdunnRuntimeActivationRecord, - warming: &PresenceObservation, + warming: &SequenceAdmittedWarming, lease: &IdunnProcessWriteLeaseRecord, ) -> Result { self.validate_grant(expected, activation, warming, lease)?; @@ -2161,7 +2992,7 @@ impl WriteLeasePort for CultCacheWriteLeaseDriver { &self, expected: &IdunnExpectedIncarnationRecord, activation: &IdunnRuntimeActivationRecord, - warming: &PresenceObservation, + warming: &SequenceAdmittedWarming, lease: &IdunnProcessWriteLeaseRecord, ) -> Result { self.validate_grant(expected, activation, warming, lease)?; @@ -2177,82 +3008,9 @@ impl WriteLeasePort for CultCacheWriteLeaseDriver { pub struct CultCacheTopologyDriver { pub projection_store: PathBuf, pub correlation_store: PathBuf, - pub odin_trust_anchor_store: PathBuf, -} - -impl CultCacheTopologyDriver { - fn anchor(&self) -> Result { - let entries = SingleFileMessagePackBackingStore::new(&self.odin_trust_anchor_store) - .pull_all_read_only_snapshot() - .with_context(|| { - format!( - "reading Odin topology trust anchor {}", - self.odin_trust_anchor_store.display() - ) - })?; - let [envelope] = entries.as_slice() else { - bail!("Odin topology trust-anchor store is missing or ambiguous") - }; - ensure!( - envelope.r#type == ::TRUST_ANCHOR_TYPE - && envelope.schema_id.as_deref() - == Some(::TRUST_ANCHOR_SCHEMA) - && envelope.key - == ::TRUST_ANCHOR_KEY, - "Odin topology trust anchor belongs to another signing profile" - ); - rmp_serde::from_slice(&envelope.payload).context("decoding Odin topology trust anchor") - } - - fn correlation( - &self, - expected: &IdunnExpectedIncarnationRecord, - current_write_lease_sha256: Option<&str>, - ) -> Result> { - 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 == expected.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" - ); - let (receipt, unsigned) = - OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload( - &envelope.payload, - )?; - ensure!( - envelope.key == receipt.target, - "Odin correlation key is not its target" - ); - receipt.validate_against_expected(expected, current_write_lease_sha256)?; - let proof = ServiceIdentitySignature { - identity_id: receipt.signer_identity_id.clone(), - signature: receipt.signature.clone(), - }; - verify_service_identity_signature::< - OdinTopologyIdentity, - OdinRuntimeTopologyCorrelationPurpose, - >(&self.anchor()?, &unsigned, &proof)?; - Ok(Some(receipt)) - } } impl TopologyPort for CultCacheTopologyDriver { - type ReadyReceipt = OdinRuntimeTopologyCorrelationRecord; - fn publish_expected(&self, expected: &IdunnExpectedIncarnationRecord) -> Result { expected.validate()?; upsert_record( @@ -2268,6 +3026,61 @@ impl TopologyPort for CultCacheTopologyDriver { expected.canonical_sha256() } + fn withdraw_expected(&self, expected: &IdunnExpectedIncarnationRecord) -> Result<()> { + expected.validate()?; + if !self.projection_store.exists() { + return Ok(()); + } + let expected_sha256 = expected.canonical_sha256()?; + 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_activation = false; + let mut retained = Vec::with_capacity(entries.len()); + for envelope in &entries { + 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 activation = + IdunnRuntimeActivationRecord::decode_canonical(&envelope.payload)?; + ensure!( + !found_activation + && envelope.schema_id.as_deref() + == Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA) + && activation.expected_projection_sha256 == expected_sha256 + && activation.runtime_id == expected.runtime_id, + "refusing to withdraw a substituted runtime activation" + ); + found_activation = true; + continue; + } + retained.push(envelope.clone()); + } + if !found_expected && !found_activation { + 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, @@ -2295,59 +3108,31 @@ impl TopologyPort for CultCacheTopologyDriver { activation.canonical_sha256() } - fn present( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - ) -> Result> { - expected.validate()?; - activation.validate()?; - let Some(receipt) = self.correlation(expected, None)? else { + fn receive(&self, target: &str) -> Result> { + require_driver_id(target, "topology target")?; + if !self.correlation_store.exists() { return Ok(None); - }; - let activation_sha256 = activation.canonical_sha256()?; - let exact_activation = receipt.current_activation_sha256.as_deref() - == Some(activation_sha256.as_str()) - && receipt.runtime_instance_id.as_deref() - == Some(activation.runtime_instance_id.as_str()); - let mut disagreements = receipt - .disagreements - .iter() - .map(|disagreement| disagreement.code.clone()) - .collect::>(); - if !exact_activation { - disagreements.push("idunn-current-activation-mismatch".into()); } - disagreements.sort(); - disagreements.dedup(); - Ok(Some(PresenceObservation { - correlation_sha256: receipt.canonical_sha256()?, - signed_presence_sha256: receipt.signed_presence_sha256.clone(), - runtime_instance_id: receipt.runtime_instance_id.clone(), - present: receipt.present && exact_activation, - state: receipt.observed_presence_state.clone(), - write_lease_sha256: receipt.observed_write_lease_sha256.clone(), - disagreements, - })) - } - - fn ready( - &self, - expected: &IdunnExpectedIncarnationRecord, - activation: &IdunnRuntimeActivationRecord, - write_lease_sha256: Option<&str>, - ) -> Result> { - expected.validate()?; - activation.validate()?; - let Some(receipt) = self.correlation(expected, write_lease_sha256)? else { + 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); }; - let activation_sha256 = activation.canonical_sha256()?; - let exact_activation = receipt.current_activation_sha256.as_deref() - == Some(activation_sha256.as_str()) - && receipt.runtime_instance_id.as_deref() - == Some(activation.runtime_instance_id.as_str()); - Ok((receipt.ready && exact_activation).then_some(receipt)) + 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(), + })) } } @@ -2357,15 +3142,19 @@ impl TopologyPort for CultCacheTopologyDriver { 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("nginx"), - systemctl_program: PathBuf::from("systemctl"), + 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"), } } @@ -2374,9 +3163,15 @@ impl NginxRouteDriver { 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() { @@ -2442,6 +3237,31 @@ impl NginxRouteDriver { .is_some_and(|section| section.as_bytes() == rendered)) } + fn current_and_loaded(&self) -> Result<(Option>, Option>)> { + let current = 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"), + }; + let output = self.command(&self.nginx_program, [OsString::from("-T")])?; + let dump = std::str::from_utf8(&output.stdout) + .context("nginx loaded configuration is not UTF-8")?; + let loaded = nginx_config_section(dump, &self.binding.config_path)? + .map(|section| section.as_bytes().to_vec()); + Ok((current, loaded)) + } + + 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( @@ -2454,15 +3274,47 @@ impl NginxRouteDriver { Ok(()) } - fn restore(&self, prior: Option<&[u8]>) -> Result<()> { - match prior { - Some(bytes) => atomic_replace(&self.binding.config_path, bytes)?, - None => match fs::remove_file(&self.binding.config_path) { - Ok(()) => {} - Err(error) if error.kind() == ErrorKind::NotFound => {} - Err(error) => return Err(error).context("removing unadmitted route fragment"), - }, + 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() } @@ -2486,38 +3338,63 @@ impl RoutePort for NginxRouteDriver { &self, expected: &IdunnExpectedIncarnationRecord, runtime_instance_id: &str, - ) -> Result<()> { + incumbent: Option<&RouteObservation>, + ) -> Result { let rendered = self.render(expected, runtime_instance_id)?; ensure!(!rendered.is_empty(), "candidate route rendered empty"); - self.command(&self.nginx_program, [OsString::from("-t")])?; - let current = 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 preflight baseline"), - }; - let output = self.command(&self.nginx_program, [OsString::from("-T")])?; - let dump = std::str::from_utf8(&output.stdout) - .context("nginx loaded configuration is not UTF-8")?; - let loaded = nginx_config_section(dump, &self.binding.config_path)?; - match (current.as_deref(), loaded) { - (None, None) => {} - (Some(current), Some(loaded)) if current == loaded.as_bytes() => {} - _ => bail!("nginx route baseline differs from its loaded configuration"), + let (current, loaded) = self.current_and_loaded()?; + ensure!( + current == loaded, + "nginx route baseline differs from its loaded 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" + ), } - Ok(()) + self.validate_candidate_in_private_mount(&rendered)?; + let after = self.current_and_loaded()?; + ensure!( + after.0 == current && after.1 == current, + "nginx route baseline changed during candidate validation" + ); + Ok(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, + }) } fn promote( &self, expected: &IdunnExpectedIncarnationRecord, runtime_instance_id: &str, + preflight: &RoutePreflightReceipt, ) -> Result { let rendered = self.render(expected, runtime_instance_id)?; - let prior = 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 current route fragment"), - }; + 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, loaded) = self.current_and_loaded()?; + let prior_sha256 = prior.as_ref().map(|bytes| sha256_id(bytes)); + ensure!( + prior == loaded && prior_sha256 == preflight.incumbent_membership_sha256, + "route baseline changed after preflight" + ); atomic_replace(&self.binding.config_path, &rendered)?; if let Err(error) = self.reload() { self.fail_after_rollback( @@ -3078,6 +3955,433 @@ fn harden_runtime_bundle(_bundle: &Path) -> Result<()> { bail!("systemd runtime bundles require Unix permissions") } +#[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()))?; @@ -3096,11 +4400,24 @@ 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) - .filter(|value| !value.is_empty()) .map(String::as_str) - .with_context(|| format!("systemd unit has no {name}")) + .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>> { @@ -3113,6 +4430,22 @@ fn read_process_environment(path: &Path) -> Result>> { .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], @@ -3208,28 +4541,167 @@ fn nginx_config_section<'a>(dump: &'a str, config_path: &Path) -> Result 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")?; - fs::create_dir_all(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 file = fs::OpenOptions::new() - .create_new(true) - .write(true) + 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")?; @@ -3245,6 +4717,28 @@ fn bind_mount(source: &Path, destination: &str, read_only: bool) -> Result 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(); @@ -3809,8 +5303,11 @@ fn apply_identity(command: &mut Command, identity: Option) -> R mod tests { use super::*; use cultnet_rs::{ - IDUNN_EXPECTED_INCARNATION_SCHEMA, IDUNN_PROCESS_WRITE_LEASE_SCHEMA, - IDUNN_RUNTIME_ACTIVATION_SCHEMA, + 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 { @@ -3860,31 +5357,74 @@ mod tests { } } - fn activation(expected: &IdunnExpectedIncarnationRecord) -> IdunnRuntimeActivationRecord { - IdunnRuntimeActivationRecord { - schema_version: IDUNN_RUNTIME_ACTIVATION_SCHEMA.into(), - expected_projection_sha256: expected.canonical_sha256().unwrap(), - runtime_instance_id: digest('7'), - issued_at_unix_millis: 100, - } - } - - fn warming(activation: &IdunnRuntimeActivationRecord) -> PresenceObservation { - PresenceObservation { - correlation_sha256: digest('8'), + fn authenticated_warming( + root: &Path, + ) -> Result<( + IdunnExpectedIncarnationRecord, + IdunnRuntimeActivationRecord, + SequenceAdmittedWarming, + )> { + 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, - state: Some("warming".into()), - write_lease_sha256: None, + 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)) } fn lease( expected: &IdunnExpectedIncarnationRecord, activation: &IdunnRuntimeActivationRecord, - warming: &PresenceObservation, + warming: &SequenceAdmittedWarming, ) -> IdunnProcessWriteLeaseRecord { IdunnProcessWriteLeaseRecord { schema_version: IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into(), @@ -3898,7 +5438,12 @@ mod tests { 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.clone().unwrap(), + warming_presence_sha256: warming + .authenticated() + .record() + .signed_presence_sha256 + .clone() + .unwrap(), lease_epoch: 1, issued_at_unix_millis: 200, } @@ -3922,6 +5467,89 @@ mod tests { Ok(()) } + #[cfg(unix)] + #[test] + fn nginx_preflight_validates_candidate_and_binds_the_loaded_incumbent() -> Result<()> { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir()?; + let config = temp.path().join("route.conf"); + let loaded = temp.path().join("loaded.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='{}'\nloaded='{}'\nif [ \"$1\" = \"-T\" ]; then\n if [ -f \"$loaded\" ]; then\n printf '# configuration file %s:\\n' \"$config\"\n /bin/cat \"$loaded\"\n fi\n exit 0\nfi\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(), + loaded.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, + format!( + "#!/bin/sh\nif [ \"$1\" = \"reload\" ]; then\n /bin/cp '{}' '{}'\n exit 0\nfi\nexit 64\n", + config.display(), + loaded.display(), + ), + )?; + 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::NginxHttp, + 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, + 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!(!loaded.exists()); + assert_eq!(fs::read_dir(&driver.preflight_root)?.count(), 0); + + let admitted = driver.promote(&candidate, &digest('a'), &preflight)?; + assert!(driver.observe(&candidate, &admitted)?); + let admitted_bytes = fs::read(&config)?; + assert_eq!(fs::read(&loaded)?, admitted_bytes); + + let next_preflight = driver.preflight(&candidate, &digest('b'), Some(&admitted))?; + assert_eq!(fs::read(&config)?, admitted_bytes); + fs::write(&config, b"foreign route\n")?; + assert!( + driver + .promote(&candidate, &digest('b'), &next_preflight) + .is_err() + ); + assert_eq!(fs::read(&loaded)?, admitted_bytes); + Ok(()) + } + #[test] fn process_environment_witness_is_sorted_exact_and_secret_free() -> Result<()> { let entries = vec![ @@ -3936,15 +5564,153 @@ mod tests { 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, _) = authenticated_warming(temp.path())?; + let projection_store = temp.path().join("projection.cc"); + let driver = CultCacheTopologyDriver { + projection_store: projection_store.clone(), + correlation_store: temp.path().join("correlation.cc"), + }; + driver.publish_expected(&expected)?; + upsert_record( + &projection_store, + CultCacheEnvelope { + key: expected.target.clone(), + r#type: IdunnRuntimeActivationRecord::TYPE.into(), + payload: activation.canonical_bytes()?, + stored_at: "2026-09-03T00:00:00Z".into(), + schema_id: Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA.into()), + }, + )?; + upsert_record( + &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)?; + let remaining = SingleFileMessagePackBackingStore::new(&projection_store) + .pull_all_read_only_snapshot()?; + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].key, "unrelated"); + driver.withdraw_expected(&expected)?; + + let substituted_store = temp.path().join("substituted-expected.cc"); + let substituted_driver = CultCacheTopologyDriver { + projection_store: substituted_store.clone(), + correlation_store: temp.path().join("substituted-correlation.cc"), + }; + substituted_driver.publish_expected(&expected)?; + let mut substituted_expected = expected.clone(); + substituted_expected.incarnation_id = "another-incarnation".into(); + assert!( + substituted_driver + .withdraw_expected(&substituted_expected) + .is_err() + ); + + let substituted_activation_store = temp.path().join("substituted-activation.cc"); + let substituted_activation_driver = CultCacheTopologyDriver { + projection_store: substituted_activation_store.clone(), + correlation_store: temp.path().join("substituted-activation-correlation.cc"), + }; + substituted_activation_driver.publish_expected(&expected)?; + let mut substituted_activation = activation; + substituted_activation.expected_projection_sha256 = digest('a'); + upsert_record( + &substituted_activation_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!( + substituted_activation_driver + .withdraw_expected(&expected) + .is_err() + ); + 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 = expected(); - let activation = activation(&expected); - let warming = warming(&activation); + let (expected, activation, warming) = authenticated_warming(temp.path())?; let lease = lease(&expected, &activation, &warming); let lease_sha256 = driver.grant(&expected, &activation, &warming, &lease)?; assert_eq!(lease_sha256, lease.canonical_sha256()?);