diff --git a/Cargo.toml b/Cargo.toml index ec23e39..4288137 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ sha2 = "0.10" chrono = "0.4" serde = { version = "1", features = ["derive"] } ed25519-dalek = "2.2" +toml = "0.8" uuid = { version = "1", features = ["v4"] } [dev-dependencies] diff --git a/src/deployment.rs b/src/deployment.rs new file mode 100644 index 0000000..56fae5b --- /dev/null +++ b/src/deployment.rs @@ -0,0 +1,1666 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Component, Path, PathBuf}; + +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize}; + +pub const TARGET_DECLARATION_SCHEMA: &str = "gamecult.idunn.target_declaration.v1"; +pub const OPERATOR_BINDING_SCHEMA: &str = "gamecult.idunn.operator_binding.v1"; +pub const PINNED_TAR_MEMBER_SCHEMA: &str = "gamecult.idunn.pinned_tar_member.v1"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TargetDeclaration { + pub schema: String, + pub target: String, + pub source_stamp_environment: String, + #[serde(default)] + pub required_gitlinks: BTreeSet, + #[serde(default)] + pub steps: Vec, + #[serde(default)] + pub external_artifacts: Vec, + pub artifacts: Vec, + pub service: ServiceDeclaration, + pub state: StateDeclaration, + #[serde(default)] + pub provides: Vec, + #[serde(default)] + pub dependencies: Vec, + #[serde(default)] + pub conflicts: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum RunnerAffordance { + SourceRead, + ArtifactWrite, + DependencyNetwork, + BuildCache, + PrivateCapabilityAccess, + SecretRead, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RecipeStep { + pub id: String, + pub phase: RecipePhase, + pub runner: String, + pub argv: Vec, + #[serde(default = "default_working_directory")] + pub working_directory: PathBuf, + #[serde(default)] + pub required_environment: BTreeSet, +} + +fn default_working_directory() -> PathBuf { + PathBuf::from(".") +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum RecipePhase { + Prepare, + Test, + Build, + Acceptance, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExternalArtifact { + pub id: String, + pub runner: String, + pub manifest: PathBuf, + pub destination: PathBuf, + #[serde(default)] + pub executable: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PinnedTarMemberManifest { + pub schema: String, + pub url: String, + pub archive_sha256: String, + pub member: PathBuf, + pub member_sha256: String, +} + +impl PinnedTarMemberManifest { + pub fn parse(input: &str) -> Result { + let manifest: Self = + toml::from_str(input).context("decoding strict pinned tar-member manifest")?; + ensure!( + manifest.schema == PINNED_TAR_MEMBER_SCHEMA, + "unsupported pinned artifact schema" + ); + https_host(&manifest.url)?; + require_sha256(&manifest.archive_sha256, "archive sha256")?; + require_relative_path(&manifest.member, "archive member", false)?; + require_sha256(&manifest.member_sha256, "member sha256")?; + Ok(manifest) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ArtifactOutput { + pub id: String, + pub source_kind: ArtifactSource, + pub runner: Option, + pub source: PathBuf, + pub destination: PathBuf, + #[serde(default)] + pub executable: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ArtifactSource { + RunnerOutput, + WorktreeTree, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ServiceDeclaration { + pub executable_artifact: String, + #[serde(default)] + pub required_adjacent_artifacts: BTreeSet, + #[serde(default)] + pub arguments: Vec, + pub transport: ServiceTransport, + #[serde(default)] + pub route_required: bool, + pub health: HealthDeclaration, + #[serde(default)] + pub required_environment: BTreeSet, + #[serde(default)] + pub optional_environment: BTreeSet, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HealthDeclaration { + pub contract: String, + pub staged: HealthState, + pub ready: HealthState, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HealthState { + pub state: String, + pub detail: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ServiceTransport { + Http, + Tcp, + Rudp, + Private, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] +pub enum LaunchArgument { + Literal { value: String }, + Binding { name: String }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StateDeclaration { + pub generation: String, + pub slots: Vec, + pub migration: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StateSlot { + pub id: String, + pub relative_path: PathBuf, + pub kind: StateKind, + pub schema: String, + pub writer: StateWriter, + pub recovery: StateRecovery, + pub startup: StateStartup, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MigrationDeclaration { + pub executable_artifact: String, + pub from_generations: BTreeSet, + pub to_generation: String, + #[serde(default)] + pub arguments: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum StateKind { + CultcacheFile, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum StateWriter { + ProcessBoundSingleWriter, + None, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum StateRecovery { + Preserve, + Rebuildable, + ExternalAuthority, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum StateStartup { + CreateOrOpenAfterAdmission, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProvidedCapability { + pub capability: String, + pub schema: String, + pub compatibility: String, + #[serde(default = "one")] + pub capacity: u32, +} + +fn one() -> u32 { + 1 +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CapabilityDependency { + pub kind: DependencyKind, + pub capability: String, + pub schema: String, + pub compatibility: String, + #[serde(default = "one")] + pub minimum_capacity: u32, + #[serde(default)] + pub startup: StartupOrder, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum DependencyKind { + Bootstrap, + Required, + Optional, + SharedInfrastructure, + Private, + ExternalOperatorBinding, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum StartupOrder { + #[default] + BeforePromotion, + BeforeStart, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CapabilityConflict { + pub capability: String, + pub reason: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperatorBinding { + pub schema: String, + pub target: String, + pub repository: RepositoryBinding, + pub runners: BTreeMap, + pub workload: WorkloadBinding, + pub route: Option, + pub admission: AdmissionBinding, + pub brakes: BrakeBinding, + pub state_transition: StateTransitionBinding, + pub rollout: RolloutBinding, + pub placement: PlacementBinding, + #[serde(default)] + pub external_capabilities: Vec, + #[serde(default)] + pub profiles: BTreeSet, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RepositoryBinding { + pub origin: String, + pub admitted_ref: String, + pub minimum_revision: String, + pub selection: SourceSelectionPolicy, + pub pinned_revision: Option, + pub release_authority_store: Option, + pub checkout: PathBuf, + pub recipe_path: PathBuf, + #[serde(default)] + pub gitlinks: BTreeMap, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum SourceSelectionPolicy { + PinnedObject, + RefHead, + SignedRelease, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GitlinkBinding { + pub origin: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RunnerBinding { + pub driver: RunnerDriver, + pub image: String, + #[serde(default)] + pub affordances: BTreeSet, + pub cache_root: Option, + #[serde(default)] + pub allowed_https_hosts: BTreeSet, + #[serde(default)] + pub allowed_programs: BTreeSet, + #[serde(default)] + pub environment: BTreeMap, + #[serde(default)] + pub secret_files: BTreeMap, + pub network: RunnerNetwork, + pub memory_mebibytes: u32, + pub cpu_quota_percent: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum RunnerDriver { + Docker, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum RunnerNetwork { + None, + DependencyEgress, + HostPrivate, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WorkloadBinding { + pub driver: WorkloadDriver, + pub user: String, + pub group: String, + pub unit_prefix: String, + pub release_root: PathBuf, + pub state_root: PathBuf, + pub runtime_root: PathBuf, + pub network: WorkloadNetwork, + pub hardening: WorkloadHardening, + #[serde(default)] + pub read_only_paths: BTreeSet, + #[serde(default)] + pub read_write_paths: BTreeSet, + #[serde(default)] + pub capabilities: BTreeSet, + #[serde(default)] + pub devices: BTreeSet, + pub memory_mebibytes: u32, + pub cpu_quota_percent: u32, + #[serde(default)] + pub environment: BTreeMap, + #[serde(default)] + pub secret_files: BTreeMap, + #[serde(default)] + pub argument_bindings: BTreeMap, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum WorkloadDriver { + SystemdTransient, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum WorkloadNetwork { + HostPrivate, + None, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum WorkloadHardening { + Strict, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AdmissionBinding { + pub driver: AdmissionDriver, + pub record_path: PathBuf, + pub lock_path: PathBuf, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum AdmissionDriver { + AtomicFile, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrakeBinding { + pub deployment_store: PathBuf, + pub lifecycle_store: PathBuf, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StateTransitionBinding { + pub policy: StateTransitionPolicy, + pub archive_root: Option, + pub backup_root: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum StateTransitionPolicy { + Preserve, + FencedMigration, + FreshRoot, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RouteBinding { + pub driver: RouteDriver, + pub route_id: String, + pub stable_endpoint: String, + pub private_host: String, + pub private_port_start: u16, + pub private_port_end: u16, + pub config_path: PathBuf, + pub reload_unit: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum RouteDriver { + NginxHttp, + NginxStreamTcp, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RolloutBinding { + pub strategy: RolloutStrategy, + pub drain_seconds: u32, + pub retain_releases: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum RolloutStrategy { + CandidateThenPromote, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PlacementBinding { + pub desired_replicas: u32, + pub nodes: BTreeSet, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExternalCapabilityBinding { + pub capability: String, + pub schema: String, + pub compatibility: String, + pub endpoint: String, +} + +impl TargetDeclaration { + pub fn parse(input: &str) -> Result { + let declaration: Self = + toml::from_str(input).context("decoding strict Idunn target declaration")?; + declaration.validate()?; + Ok(declaration) + } + + pub fn validate(&self) -> Result<()> { + ensure!( + self.schema == TARGET_DECLARATION_SCHEMA, + "unsupported target declaration schema" + ); + require_id(&self.target, "target")?; + require_environment_name(&self.source_stamp_environment)?; + for path in &self.required_gitlinks { + require_relative_path(path, "required gitlink", false)?; + } + ensure!(!self.steps.is_empty(), "no recipe steps declared"); + ensure!(!self.artifacts.is_empty(), "no artifact outputs declared"); + + let mut runner_ids = BTreeSet::new(); + unique_ids( + self.steps.iter().map(|step| step.id.as_str()), + "recipe step", + )?; + for step in &self.steps { + require_id(&step.runner, "runner class")?; + runner_ids.insert(step.runner.as_str()); + ensure!(!step.argv.is_empty(), "step {} has empty argv", step.id); + for argument in &step.argv { + require_value(argument, "step argv")?; + } + require_program(&step.argv[0], "step program")?; + require_relative_path(&step.working_directory, "step working directory", true)?; + for name in &step.required_environment { + require_environment_name(name)?; + } + } + + let mut artifact_ids = BTreeSet::new(); + let mut destinations = BTreeSet::new(); + for artifact in &self.artifacts { + require_id(&artifact.id, "artifact")?; + ensure!( + artifact_ids.insert(artifact.id.as_str()), + "artifact id {} is declared twice", + artifact.id + ); + require_relative_path(&artifact.source, "artifact source", false)?; + require_leaf_path(&artifact.destination, "artifact destination")?; + ensure!( + destinations.insert(artifact.destination.as_path()), + "artifact destination {} is declared twice", + artifact.destination.display() + ); + match (artifact.source_kind, artifact.runner.as_deref()) { + (ArtifactSource::RunnerOutput, Some(runner)) => { + require_id(runner, "artifact runner class")?; + runner_ids.insert(runner); + } + (ArtifactSource::WorktreeTree, None) => {} + (ArtifactSource::RunnerOutput, None) => { + bail!("runner-output artifact {} has no runner class", artifact.id) + } + (ArtifactSource::WorktreeTree, Some(_)) => bail!( + "worktree-tree artifact {} cannot name a runner class", + artifact.id + ), + } + } + for artifact in &self.external_artifacts { + require_id(&artifact.id, "external artifact")?; + ensure!( + artifact_ids.insert(artifact.id.as_str()), + "artifact id {} is declared twice", + artifact.id + ); + require_id(&artifact.runner, "external artifact runner class")?; + runner_ids.insert(artifact.runner.as_str()); + require_relative_path(&artifact.manifest, "external artifact manifest", false)?; + require_leaf_path(&artifact.destination, "external artifact destination")?; + ensure!( + destinations.insert(artifact.destination.as_path()), + "artifact destination {} is declared twice", + artifact.destination.display() + ); + } + ensure!( + !runner_ids.is_empty(), + "target declaration uses no runner classes" + ); + + ensure!( + artifact_ids.contains(self.service.executable_artifact.as_str()), + "service executable artifact is not declared" + ); + for artifact in &self.service.required_adjacent_artifacts { + ensure!( + artifact_ids.contains(artifact.as_str()), + "adjacent service artifact {artifact} is not declared" + ); + } + for argument in &self.service.arguments { + validate_launch_argument(argument)?; + } + require_capability(&self.service.health.contract, "health contract")?; + for (label, health) in [ + ("staged health", &self.service.health.staged), + ("ready health", &self.service.health.ready), + ] { + require_value(&health.state, label)?; + require_value(&health.detail, label)?; + } + ensure!( + self.service.health.staged != self.service.health.ready, + "staged and ready health states are identical" + ); + for name in &self.service.required_environment { + require_environment_name(name)?; + } + for name in &self.service.optional_environment { + require_environment_name(name)?; + ensure!( + !self.service.required_environment.contains(name), + "service environment {name} is both required and optional" + ); + } + + require_capability(&self.state.generation, "state generation")?; + let slot_ids = unique_ids( + self.state.slots.iter().map(|slot| slot.id.as_str()), + "state slot", + )?; + let mut slot_paths = BTreeSet::new(); + for slot in &self.state.slots { + require_relative_path(&slot.relative_path, "state slot path", false)?; + ensure!( + slot_paths.insert(slot.relative_path.as_path()), + "state slot path {} is declared twice", + slot.relative_path.display() + ); + require_capability(&slot.schema, "state slot schema")?; + if slot.writer == StateWriter::ProcessBoundSingleWriter { + ensure!( + slot.startup == StateStartup::CreateOrOpenAfterAdmission, + "writable state slot {} must open after write admission", + slot.id + ); + } + if slot.recovery == StateRecovery::ExternalAuthority { + ensure!( + slot.writer == StateWriter::None, + "externally authoritative state slot {} cannot name the service as writer", + slot.id + ); + } + } + if let Some(migration) = self.state.migration.as_ref() { + ensure!( + artifact_ids.contains(migration.executable_artifact.as_str()), + "migration executable artifact is not declared" + ); + ensure!( + !migration.from_generations.is_empty(), + "migration has no source generations" + ); + for generation in &migration.from_generations { + require_capability(generation, "migration source generation")?; + } + ensure!( + migration.to_generation == self.state.generation, + "migration destination differs from state generation" + ); + for argument in &migration.arguments { + validate_launch_argument(argument)?; + } + } + ensure!( + slot_ids.len() == self.state.slots.len(), + "duplicate state slot" + ); + + let mut provided = BTreeSet::new(); + for capability in &self.provides { + require_capability_contract( + &capability.capability, + &capability.schema, + &capability.compatibility, + )?; + ensure!( + capability.capacity > 0, + "provided capability capacity must be positive" + ); + ensure!( + provided.insert(capability.capability.as_str()), + "capability {} is provided twice", + capability.capability + ); + } + let mut required = BTreeSet::new(); + for dependency in &self.dependencies { + require_capability_contract( + &dependency.capability, + &dependency.schema, + &dependency.compatibility, + )?; + ensure!( + dependency.minimum_capacity > 0, + "dependency capacity must be positive" + ); + ensure!( + required.insert((dependency.kind, dependency.capability.as_str())), + "dependency {} is declared twice for the same kind", + dependency.capability + ); + } + for conflict in &self.conflicts { + require_capability(&conflict.capability, "conflicting capability")?; + require_value(&conflict.reason, "conflict reason")?; + } + Ok(()) + } +} + +impl OperatorBinding { + pub fn parse(input: &str) -> Result { + let binding: Self = + toml::from_str(input).context("decoding strict Idunn operator binding")?; + binding.validate()?; + Ok(binding) + } + + pub fn validate(&self) -> Result<()> { + ensure!( + self.schema == OPERATOR_BINDING_SCHEMA, + "unsupported operator binding schema" + ); + require_id(&self.target, "target")?; + ensure!( + self.repository.origin.starts_with("https://"), + "repository origin must use HTTPS" + ); + ensure!( + self.repository.origin.ends_with(".git"), + "repository origin must name a Git repository" + ); + ensure!( + self.repository.admitted_ref.starts_with("refs/heads/"), + "admitted ref must be a full branch ref" + ); + require_sha1(&self.repository.minimum_revision, "minimum revision")?; + match self.repository.selection { + SourceSelectionPolicy::PinnedObject => { + let revision = self.repository.pinned_revision.as_deref().ok_or_else(|| { + anyhow::anyhow!("pinned-object selection has no pinned revision") + })?; + require_sha1(revision, "pinned revision")?; + ensure!( + self.repository.release_authority_store.is_none(), + "pinned-object selection cannot name a release-authority store" + ); + } + SourceSelectionPolicy::RefHead => { + ensure!( + self.repository.pinned_revision.is_none(), + "ref-head selection cannot name a pinned revision" + ); + ensure!( + self.repository.release_authority_store.is_none(), + "ref-head selection cannot name a release-authority store" + ); + } + SourceSelectionPolicy::SignedRelease => { + ensure!( + self.repository.pinned_revision.is_none(), + "signed-release selection cannot name a pinned revision" + ); + let store = self + .repository + .release_authority_store + .as_ref() + .ok_or_else(|| { + anyhow::anyhow!("signed-release selection has no authority store") + })?; + require_absolute_path(store, "release authority store")?; + } + } + require_absolute_path(&self.repository.checkout, "repository checkout")?; + require_relative_path(&self.repository.recipe_path, "recipe path", false)?; + for (path, gitlink) in &self.repository.gitlinks { + require_relative_path(path, "gitlink binding", false)?; + require_git_origin(&gitlink.origin, "gitlink origin")?; + } + ensure!(!self.runners.is_empty(), "operator binding has no runners"); + for (id, runner) in &self.runners { + require_id(id, "runner binding")?; + require_pinned_image(&runner.image)?; + ensure!( + runner.memory_mebibytes > 0, + "runner memory must be positive" + ); + ensure!( + (1..=100_000).contains(&runner.cpu_quota_percent), + "runner CPU quota is outside 1..=100000" + ); + if let Some(cache_root) = runner.cache_root.as_ref() { + require_absolute_path(cache_root, "runner cache root")?; + } + for program in &runner.allowed_programs { + require_program(program, "allowed runner program")?; + } + ensure!( + !runner.allowed_programs.is_empty(), + "runner {id} has no allowed programs" + ); + for host in &runner.allowed_https_hosts { + require_host(host)?; + } + match runner.network { + RunnerNetwork::None => ensure!( + runner.allowed_https_hosts.is_empty(), + "network-none runner {id} has HTTPS hosts" + ), + RunnerNetwork::DependencyEgress => { + ensure!( + runner + .affordances + .contains(&RunnerAffordance::DependencyNetwork), + "dependency-egress runner {id} does not grant dependency-network" + ); + ensure!( + !runner.allowed_https_hosts.is_empty(), + "dependency-egress runner {id} has no allowed hosts" + ); + } + RunnerNetwork::HostPrivate => ensure!( + runner + .affordances + .contains(&RunnerAffordance::PrivateCapabilityAccess), + "host-private runner {id} does not grant private-capability-access" + ), + } + for name in runner.environment.keys().chain(runner.secret_files.keys()) { + require_environment_name(name)?; + } + for path in runner.secret_files.values() { + require_absolute_path(path, "runner secret file")?; + } + if runner.affordances.contains(&RunnerAffordance::BuildCache) { + ensure!( + runner.cache_root.is_some(), + "build-cache runner {id} has no cache root" + ); + } + } + require_identity(&self.workload.user, "workload user")?; + require_identity(&self.workload.group, "workload group")?; + require_id(&self.workload.unit_prefix, "workload unit prefix")?; + for (label, path) in [ + ("release root", &self.workload.release_root), + ("state root", &self.workload.state_root), + ("runtime root", &self.workload.runtime_root), + ("admission record", &self.admission.record_path), + ("admission lock", &self.admission.lock_path), + ("deployment brake", &self.brakes.deployment_store), + ("lifecycle brake", &self.brakes.lifecycle_store), + ] { + require_absolute_path(path, label)?; + } + ensure!( + self.admission.record_path != self.admission.lock_path, + "admission record and lock paths are identical" + ); + ensure!( + self.brakes.deployment_store != self.brakes.lifecycle_store, + "deployment and lifecycle brakes are identical" + ); + ensure!( + self.workload.memory_mebibytes > 0, + "workload memory must be positive" + ); + ensure!( + (1..=100_000).contains(&self.workload.cpu_quota_percent), + "workload CPU quota is outside 1..=100000" + ); + for path in self + .workload + .read_only_paths + .iter() + .chain(self.workload.read_write_paths.iter()) + .chain(self.workload.devices.iter()) + { + require_absolute_path(path, "workload path")?; + } + for capability in &self.workload.capabilities { + require_value(capability, "workload capability")?; + } + for name in self + .workload + .environment + .keys() + .chain(self.workload.secret_files.keys()) + { + require_environment_name(name)?; + } + for name in self.workload.argument_bindings.keys() { + require_id(name, "argument binding")?; + } + for value in self.workload.argument_bindings.values() { + require_value(value, "argument binding value")?; + } + for path in self.workload.secret_files.values() { + require_absolute_path(path, "secret file")?; + } + if let Some(route) = self.route.as_ref() { + require_id(&route.route_id, "route id")?; + require_value(&route.stable_endpoint, "stable endpoint")?; + require_host(&route.private_host)?; + ensure!( + route.private_port_start > 0, + "private port range starts at zero" + ); + ensure!( + route.private_port_start <= route.private_port_end, + "private port range is inverted" + ); + require_absolute_path(&route.config_path, "route config")?; + require_unit(&route.reload_unit, "route reload unit")?; + } + match self.state_transition.policy { + StateTransitionPolicy::Preserve => {} + StateTransitionPolicy::FencedMigration => ensure!( + self.state_transition.backup_root.is_some(), + "fenced migration has no backup root" + ), + StateTransitionPolicy::FreshRoot => ensure!( + self.state_transition.archive_root.is_some(), + "fresh-root transition has no whole-root archive" + ), + } + if let Some(path) = self.state_transition.archive_root.as_ref() { + require_absolute_path(path, "state archive root")?; + } + if let Some(path) = self.state_transition.backup_root.as_ref() { + require_absolute_path(path, "state backup root")?; + } + ensure!( + self.rollout.retain_releases >= 2, + "candidate rollout must retain at least current and prior releases" + ); + ensure!( + self.placement.desired_replicas > 0, + "desired replicas must be positive" + ); + ensure!(!self.placement.nodes.is_empty(), "placement has no nodes"); + for node in &self.placement.nodes { + require_id(node, "placement node")?; + } + for capability in &self.external_capabilities { + require_capability_contract( + &capability.capability, + &capability.schema, + &capability.compatibility, + )?; + require_value(&capability.endpoint, "external capability endpoint")?; + } + for profile in &self.profiles { + require_capability(profile, "profile")?; + } + Ok(()) + } + + pub fn admit(&self, declaration: &TargetDeclaration) -> Result<()> { + ensure!( + self.target == declaration.target, + "binding target does not match declaration" + ); + let bound_gitlinks: BTreeSet<_> = self.repository.gitlinks.keys().cloned().collect(); + ensure!( + bound_gitlinks == declaration.required_gitlinks, + "operator gitlink bindings do not exactly match required gitlinks" + ); + let declared_runners: BTreeSet<_> = declaration + .steps + .iter() + .map(|step| step.runner.as_str()) + .chain( + declaration + .external_artifacts + .iter() + .map(|artifact| artifact.runner.as_str()), + ) + .chain( + declaration + .artifacts + .iter() + .filter_map(|artifact| artifact.runner.as_deref()), + ) + .collect(); + let bound_runners: BTreeSet<_> = self.runners.keys().map(String::as_str).collect(); + ensure!( + declared_runners == bound_runners, + "operator runner classes do not exactly match the target recipe" + ); + for step in &declaration.steps { + let binding = &self.runners[&step.runner]; + ensure!( + binding.affordances.contains(&RunnerAffordance::SourceRead), + "runner {} cannot read the frozen source", + step.runner + ); + ensure!( + binding.allowed_programs.contains(&step.argv[0]), + "runner {} does not admit program {}", + step.runner, + step.argv[0] + ); + let available: BTreeSet<_> = binding + .environment + .keys() + .chain(binding.secret_files.keys()) + .cloned() + .collect(); + ensure!( + step.required_environment.is_subset(&available), + "step {} lacks required runner environment", + step.id + ); + } + for artifact in declaration + .artifacts + .iter() + .filter(|artifact| artifact.source_kind == ArtifactSource::RunnerOutput) + { + let runner_id = artifact + .runner + .as_deref() + .expect("validated runner-output artifact"); + let binding = &self.runners[runner_id]; + ensure!( + binding + .affordances + .contains(&RunnerAffordance::ArtifactWrite), + "runner {runner_id} cannot publish artifact {}", + artifact.id + ); + } + for artifact in &declaration.external_artifacts { + let binding = &self.runners[&artifact.runner]; + ensure!( + binding.affordances.contains(&RunnerAffordance::SourceRead), + "external artifact {} runner cannot read the frozen source", + artifact.id + ); + ensure!( + binding + .affordances + .contains(&RunnerAffordance::ArtifactWrite), + "external artifact {} runner cannot publish artifacts", + artifact.id + ); + ensure!( + binding + .affordances + .contains(&RunnerAffordance::DependencyNetwork), + "external artifact {} runner has no dependency-network affordance", + artifact.id + ); + ensure!( + binding.network == RunnerNetwork::DependencyEgress + && !binding.allowed_https_hosts.is_empty(), + "external artifact {} runner has no admitted egress hosts", + artifact.id + ); + } + let available_environment: BTreeSet<_> = self + .workload + .environment + .keys() + .chain(self.workload.secret_files.keys()) + .cloned() + .collect(); + ensure!( + declaration + .service + .required_environment + .is_subset(&available_environment), + "operator service environment omits a required launch input" + ); + let declared_environment: BTreeSet<_> = declaration + .service + .required_environment + .union(&declaration.service.optional_environment) + .cloned() + .collect(); + ensure!( + available_environment.is_subset(&declared_environment), + "operator service environment contains an undeclared launch input" + ); + let required_arguments: BTreeSet<_> = declaration + .service + .arguments + .iter() + .filter_map(|argument| match argument { + LaunchArgument::Binding { name } => Some(name.clone()), + LaunchArgument::Literal { .. } => None, + }) + .collect(); + let bound_arguments: BTreeSet<_> = + self.workload.argument_bindings.keys().cloned().collect(); + ensure!( + required_arguments == bound_arguments, + "operator argument bindings do not exactly match the launch contract" + ); + match ( + declaration.service.route_required, + declaration.service.transport, + self.route.as_ref().map(|route| route.driver), + ) { + (true, ServiceTransport::Http, Some(RouteDriver::NginxHttp)) + | (true, ServiceTransport::Tcp, Some(RouteDriver::NginxStreamTcp)) + | (false, _, None) => {} + _ => bail!("route binding does not match the launch contract"), + } + match self.state_transition.policy { + StateTransitionPolicy::Preserve => {} + StateTransitionPolicy::FencedMigration => ensure!( + declaration.state.migration.is_some(), + "binding requests migration but target declares no migrator" + ), + StateTransitionPolicy::FreshRoot => {} + } + for dependency in declaration + .dependencies + .iter() + .filter(|dependency| dependency.kind == DependencyKind::ExternalOperatorBinding) + { + ensure!( + self.external_capabilities.iter().any(|binding| { + capability_compatible( + &dependency.capability, + &dependency.schema, + &dependency.compatibility, + &binding.capability, + &binding.schema, + &binding.compatibility, + ) + }), + "external capability {} has no compatible operator binding", + dependency.capability + ); + } + Ok(()) + } + + pub fn admit_external_artifact_manifest( + &self, + declaration: &TargetDeclaration, + artifact_id: &str, + manifest_input: &str, + ) -> Result { + let artifact = declaration + .external_artifacts + .iter() + .find(|artifact| artifact.id == artifact_id) + .with_context(|| format!("target declares no external artifact {artifact_id}"))?; + let runner = self.runners.get(&artifact.runner).with_context(|| { + format!("external artifact runner {} is not bound", artifact.runner) + })?; + ensure!( + runner.network == RunnerNetwork::DependencyEgress, + "external artifact runner has no dependency egress" + ); + let manifest = PinnedTarMemberManifest::parse(manifest_input)?; + let host = https_host(&manifest.url)?; + ensure!( + runner.allowed_https_hosts.contains(host), + "external artifact host {host} is not admitted" + ); + Ok(manifest) + } +} + +pub fn capability_compatible( + required_capability: &str, + required_schema: &str, + required_compatibility: &str, + provided_capability: &str, + provided_schema: &str, + provided_compatibility: &str, +) -> bool { + required_capability == provided_capability + && required_schema == provided_schema + && required_compatibility == provided_compatibility +} + +fn unique_ids<'a>(values: impl Iterator, label: &str) -> Result> { + let mut seen = BTreeSet::new(); + for value in values { + require_id(value, label)?; + ensure!(seen.insert(value), "duplicate {label} id {value}"); + } + Ok(seen) +} + +fn require_id(value: &str, label: &str) -> Result<()> { + ensure!(!value.is_empty(), "{label} is empty"); + ensure!(value.len() <= 96, "{label} is too long"); + ensure!( + value.bytes().all(|byte| byte.is_ascii_lowercase() + || byte.is_ascii_digit() + || matches!(byte, b'-' | b'_' | b'.' | b':')), + "{label} contains an invalid character" + ); + Ok(()) +} + +fn require_capability(value: &str, label: &str) -> Result<()> { + require_id(value, label) +} + +fn require_capability_contract(capability: &str, schema: &str, compatibility: &str) -> Result<()> { + require_capability(capability, "capability")?; + require_capability(schema, "capability schema")?; + require_capability(compatibility, "capability compatibility") +} + +fn require_value(value: &str, label: &str) -> Result<()> { + ensure!(!value.trim().is_empty(), "{label} is empty"); + ensure!(!value.contains('\0'), "{label} contains NUL"); + ensure!(value.len() <= 4_096, "{label} is too long"); + Ok(()) +} + +fn validate_launch_argument(argument: &LaunchArgument) -> Result<()> { + match argument { + LaunchArgument::Literal { value } => require_value(value, "literal launch argument"), + LaunchArgument::Binding { name } => require_id(name, "launch argument binding"), + } +} + +fn require_program(value: &str, label: &str) -> Result<()> { + require_value(value, label)?; + ensure!( + !value.contains('/') && !value.contains('\\') && !value.chars().any(char::is_whitespace), + "{label} must be one executable name" + ); + Ok(()) +} + +fn require_git_origin(value: &str, label: &str) -> Result<()> { + ensure!(value.starts_with("https://"), "{label} must use HTTPS"); + ensure!( + value.ends_with(".git"), + "{label} must name a Git repository" + ); + require_value(value, label) +} + +fn https_host(value: &str) -> Result<&str> { + let remainder = value + .strip_prefix("https://") + .ok_or_else(|| anyhow::anyhow!("artifact URL must use HTTPS"))?; + let authority = remainder.split('/').next().unwrap_or_default(); + ensure!(!authority.is_empty(), "artifact URL has no host"); + ensure!( + !authority.contains('@') + && !authority.contains(':') + && !authority.contains('?') + && !authority.contains('#'), + "artifact URL authority is not a bare host" + ); + require_host(authority)?; + Ok(authority) +} + +fn require_environment_name(value: &str) -> Result<()> { + ensure!( + !value.is_empty() && value.len() <= 128, + "environment name is empty or too long" + ); + ensure!( + value + .bytes() + .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_'), + "environment name contains an invalid character" + ); + Ok(()) +} + +fn require_relative_path(path: &Path, label: &str, allow_current: bool) -> Result<()> { + ensure!(!path.as_os_str().is_empty(), "{label} is empty"); + ensure!(!path.is_absolute(), "{label} must be relative"); + let mut saw_normal = false; + for component in path.components() { + match component { + Component::Normal(_) => saw_normal = true, + Component::CurDir if allow_current => {} + _ => bail!("{label} contains a forbidden path component"), + } + } + ensure!(allow_current || saw_normal, "{label} must name a path"); + Ok(()) +} + +fn require_leaf_path(path: &Path, label: &str) -> Result<()> { + require_relative_path(path, label, false)?; + ensure!( + path.components().count() == 1, + "{label} must be a single filename" + ); + Ok(()) +} + +fn require_absolute_path(path: &Path, label: &str) -> Result<()> { + ensure!(path.is_absolute(), "{label} must be absolute"); + ensure!( + path.components() + .all(|component| !matches!(component, Component::ParentDir)), + "{label} contains a parent traversal" + ); + Ok(()) +} + +fn require_sha1(value: &str, label: &str) -> Result<()> { + require_lower_hex(value, 40, label) +} + +fn require_sha256(value: &str, label: &str) -> Result<()> { + require_lower_hex(value, 64, label) +} + +fn require_lower_hex(value: &str, length: usize, label: &str) -> Result<()> { + ensure!(value.len() == length, "{label} has the wrong length"); + ensure!( + value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)), + "{label} must be lowercase hexadecimal" + ); + Ok(()) +} + +fn require_pinned_image(value: &str) -> Result<()> { + let Some((name, digest)) = value.rsplit_once("@sha256:") else { + bail!("runner image is not pinned by sha256 digest"); + }; + require_value(name, "runner image name")?; + require_sha256(digest, "runner image digest") +} + +fn require_identity(value: &str, label: &str) -> Result<()> { + require_id(value, label) +} + +fn require_unit(value: &str, label: &str) -> Result<()> { + require_value(value, label)?; + ensure!( + value.ends_with(".service"), + "{label} must be a systemd service unit" + ); + ensure!( + !value.contains('/') && !value.contains('\\'), + "{label} must not contain a path" + ); + Ok(()) +} + +fn require_host(value: &str) -> Result<()> { + require_value(value, "host")?; + ensure!( + !value.contains('/') && !value.contains('@'), + "host contains an invalid delimiter" + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const RECIPE: &str = r#" +schema = "gamecult.idunn.target_declaration.v1" +target = "test-service" +source_stamp_environment = "TEST_SERVICE_BUILD_COMMIT" + +[[steps]] +id = "test" +phase = "test" +runner = "rust" +argv = ["cargo", "test", "--locked", "-p", "test-service"] + +[[steps]] +id = "build" +phase = "build" +runner = "rust" +argv = ["cargo", "build", "--locked", "--release", "-p", "test-service"] + +[[external_artifacts]] +id = "tool" +runner = "rust" +manifest = "deployment/tool.toml" +destination = "tool" +executable = true + +[[artifacts]] +id = "daemon" +source_kind = "runner-output" +runner = "rust" +source = "target/release/test-service" +destination = "test-service" +executable = true + +[service] +executable_artifact = "daemon" +required_adjacent_artifacts = [] +arguments = [ + { kind = "literal", value = "--state-root" }, + { kind = "binding", name = "state_root" }, +] +transport = "http" +route_required = true +required_environment = ["TEST_SERVICE_BIND"] + +[service.health] +contract = "test-service.cultnet-service-health" + +[service.health.staged] +state = "warming" +detail = "traffic-admission-pending" + +[service.health.ready] +state = "active" +detail = "serving" + +[state] +generation = "v1" + +[[state.slots]] +id = "world" +relative_path = "world.cc" +kind = "cultcache-file" +schema = "test-service.state.v1" +writer = "process-bound-single-writer" +recovery = "preserve" +startup = "create-or-open-after-admission" + +[[provides]] +capability = "test-service.runtime" +schema = "test-service.state.v1" +compatibility = "v1" + +[[dependencies]] +kind = "shared-infrastructure" +capability = "odin.verse-rendezvous" +schema = "odin.verse-topology.v1" +compatibility = "v1" +startup = "before-promotion" +"#; + + const BINDING: &str = r#" +schema = "gamecult.idunn.operator_binding.v1" +target = "test-service" +profiles = ["aetheria", "full-gamecult"] + +[repository] +origin = "https://github.com/GameCult/TestService.git" +admitted_ref = "refs/heads/main" +minimum_revision = "13d5136b69bcd3a52c400d66a940f94a47122e48" +selection = "ref-head" +checkout = "/srv/build/TestService" +recipe_path = "deployment/idunn/recipe.toml" + +[runners.rust] +driver = "docker" +image = "rust@sha256:4c2fd73ef19c5ef9d54bee03b06b2839a392604fbfcd578ed948b71b37c1d7fb" +affordances = ["source-read", "artifact-write", "dependency-network", "build-cache"] +cache_root = "/srv/ghostlight/build-cache" +allowed_https_hosts = ["crates.io", "github.com"] +allowed_programs = ["cargo"] +network = "dependency-egress" +memory_mebibytes = 8192 +cpu_quota_percent = 400 + +[workload] +driver = "systemd-transient" +user = "test-service" +group = "test-service" +unit_prefix = "idunn-test-service" +release_root = "/srv/test-service/releases" +state_root = "/var/lib/gamecult/test-service" +runtime_root = "/etc/gamecult/test-service/runtime" +network = "host-private" +hardening = "strict" +memory_mebibytes = 2048 +cpu_quota_percent = 200 + +[workload.environment] +TEST_SERVICE_BIND = "idunn.private_endpoint" + +[workload.argument_bindings] +state_root = "/var/lib/gamecult/test-service" + +[route] +driver = "nginx-http" +route_id = "test-service-public" +stable_endpoint = "https://yggdrasil.gamecult.org/test-service/" +private_host = "127.0.0.1" +private_port_start = 18831 +private_port_end = 18839 +config_path = "/etc/nginx/idunn-routes/test-service.conf" +reload_unit = "nginx.service" + +[admission] +driver = "atomic-file" +record_path = "/etc/gamecult/test-service/runtime/process-admission.cc" +lock_path = "/etc/gamecult/test-service/runtime/process-admission.cc.lock" + +[brakes] +deployment_store = "/var/lib/gamecult/idunn-authority/test-service-deployment-brake.cc" +lifecycle_store = "/var/lib/gamecult/idunn-authority/test-service-lifecycle-brake.cc" + +[state_transition] +policy = "fresh-root" +archive_root = "/var/lib/gamecult/test-service-cold-archive" + +[rollout] +strategy = "candidate-then-promote" +drain_seconds = 30 +retain_releases = 2 + +[placement] +desired_replicas = 1 +nodes = ["yggdrasil"] +"#; + + #[test] + fn strict_recipe_and_binding_admit_without_host_privilege_in_recipe() { + let recipe = TargetDeclaration::parse(RECIPE).unwrap(); + let binding = OperatorBinding::parse(BINDING).unwrap(); + binding.admit(&recipe).unwrap(); + assert_eq!(recipe.target, "test-service"); + assert_eq!(binding.route.as_ref().unwrap().private_port_start, 18831); + } + + #[test] + fn unknown_recipe_field_is_rejected() { + let input = RECIPE.replace( + "target = \"test-service\"", + "target = \"test-service\"\nroot = true", + ); + assert!(TargetDeclaration::parse(&input).is_err()); + } + + #[test] + fn operator_cannot_omit_an_affordance_derived_from_the_recipe() { + let recipe = TargetDeclaration::parse(RECIPE).unwrap(); + let input = BINDING.replace( + "affordances = [\"source-read\", \"artifact-write\", \"dependency-network\", \"build-cache\"]", + "affordances = [\"source-read\", \"dependency-network\", \"build-cache\"]", + ); + let binding = OperatorBinding::parse(&input).unwrap(); + assert!(binding.admit(&recipe).is_err()); + } + + #[test] + fn route_transport_mismatch_is_rejected() { + let recipe = TargetDeclaration::parse(RECIPE).unwrap(); + let binding = + OperatorBinding::parse(&BINDING.replace("nginx-http", "nginx-stream-tcp")).unwrap(); + assert!(binding.admit(&recipe).is_err()); + } + + #[test] + fn raw_unit_template_is_rejected() { + let input = RECIPE.replace( + "executable_artifact = \"daemon\"", + "executable_artifact = \"daemon\"\nunit_template = \"deployment/root.service\"", + ); + assert!(TargetDeclaration::parse(&input).is_err()); + } + + #[test] + fn extra_operator_environment_is_rejected() { + let recipe = TargetDeclaration::parse(RECIPE).unwrap(); + let input = BINDING.replace( + "TEST_SERVICE_BIND = \"idunn.private_endpoint\"", + "TEST_SERVICE_BIND = \"idunn.private_endpoint\"\nUNDECLARED = \"no\"", + ); + let binding = OperatorBinding::parse(&input).unwrap(); + assert!(binding.admit(&recipe).is_err()); + } + + #[test] + fn fresh_root_keeps_target_preservation_semantics_inside_the_new_generation() { + let recipe = TargetDeclaration::parse(RECIPE).unwrap(); + let binding = OperatorBinding::parse(BINDING).unwrap(); + binding.admit(&recipe).unwrap(); + assert_eq!(recipe.state.slots[0].recovery, StateRecovery::Preserve); + assert_eq!( + binding.state_transition.policy, + StateTransitionPolicy::FreshRoot + ); + } + + #[test] + fn state_slot_path_cannot_escape_the_operator_owned_root() { + let input = RECIPE.replace( + "relative_path = \"world.cc\"", + "relative_path = \"../world.cc\"", + ); + assert!(TargetDeclaration::parse(&input).is_err()); + } + + #[test] + fn pinned_artifact_host_must_be_operator_admitted() { + let recipe = TargetDeclaration::parse(RECIPE).unwrap(); + let binding = OperatorBinding::parse(BINDING).unwrap(); + let manifest = r#" +schema = "gamecult.idunn.pinned_tar_member.v1" +url = "https://registry.npmjs.org/tool.tgz" +archive_sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +member = "package/bin/tool" +member_sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" +"#; + assert!( + binding + .admit_external_artifact_manifest(&recipe, "tool", manifest) + .is_err() + ); + let admitted = BINDING.replace( + "allowed_https_hosts = [\"crates.io\", \"github.com\"]", + "allowed_https_hosts = [\"crates.io\", \"github.com\", \"registry.npmjs.org\"]", + ); + let binding = OperatorBinding::parse(&admitted).unwrap(); + binding + .admit_external_artifact_manifest(&recipe, "tool", manifest) + .unwrap(); + } + + #[test] + fn dependency_compatibility_requires_exact_typed_contract() { + assert!(capability_compatible( + "odin.verse-rendezvous", + "odin.verse-topology.v1", + "v1", + "odin.verse-rendezvous", + "odin.verse-topology.v1", + "v1", + )); + assert!(!capability_compatible( + "odin.verse-rendezvous", + "odin.verse-topology.v1", + "v1", + "odin.verse-rendezvous", + "odin.verse-topology.v2", + "v2", + )); + } +} diff --git a/src/deployment_plan.rs b/src/deployment_plan.rs new file mode 100644 index 0000000..583059f --- /dev/null +++ b/src/deployment_plan.rs @@ -0,0 +1,1322 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; + +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::deployment::{ + CapabilityDependency, DependencyKind, ExternalCapabilityBinding, OperatorBinding, + ProvidedCapability, TargetDeclaration, capability_compatible, +}; + +pub const COMPILED_DEPLOYMENT_PLAN_SCHEMA: &str = "idunn.compiled_deployment_plan.v1"; +pub const SEALED_DEPLOYMENT_SCHEMA: &str = "idunn.sealed_deployment.v1"; +pub const EXPECTED_GENERATION_SCHEMA: &str = "idunn.expected_generation.v1"; +pub const GENERATION_CORRELATION_SCHEMA: &str = "idunn.generation_correlation.v1"; +pub const PROMOTION_TRANSACTION_SCHEMA: &str = "idunn.promotion_transaction.v1"; +pub const ADMITTED_GENERATION_SCHEMA: &str = "idunn.admitted_generation.v1"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ResolvedGitlink { + pub origin: String, + pub revision: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExactSource { + pub origin: String, + pub admitted_ref: String, + pub revision: String, + pub minimum_revision: String, + pub selection_receipt_sha256: String, + pub gitlinks: BTreeMap, +} + +impl ExactSource { + pub fn validate_against(&self, binding: &OperatorBinding) -> Result<()> { + ensure!( + self.origin == binding.repository.origin, + "exact source origin differs from binding" + ); + ensure!( + self.admitted_ref == binding.repository.admitted_ref, + "exact source ref differs from binding" + ); + require_sha1(&self.revision, "exact source revision")?; + ensure!( + self.minimum_revision == binding.repository.minimum_revision, + "exact source floor differs from binding" + ); + require_sha1(&self.minimum_revision, "exact source floor")?; + require_sha256(&self.selection_receipt_sha256, "source-selection receipt")?; + let expected_paths: BTreeSet<_> = binding.repository.gitlinks.keys().cloned().collect(); + let observed_paths: BTreeSet<_> = self.gitlinks.keys().cloned().collect(); + ensure!( + expected_paths == observed_paths, + "resolved Gitlinks differ from binding" + ); + for (path, observed) in &self.gitlinks { + let expected = &binding.repository.gitlinks[path]; + ensure!( + observed.origin == expected.origin, + "Gitlink {} origin differs from binding", + path.display() + ); + require_sha1(&observed.revision, "Gitlink revision")?; + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ProviderOrigin { + ManagedRuntime, + ExternalOperatorBinding, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProviderObservation { + pub provider_id: String, + pub provider_target: Option, + pub origin: ProviderOrigin, + pub generation: String, + pub deployment_id: Option, + pub capability: String, + pub schema: String, + pub compatibility: String, + pub capacity: u32, + pub endpoint: String, + pub expected: bool, + pub present: bool, + pub ready: bool, + pub observation_sha256: Option, +} + +impl ProviderObservation { + pub fn validate(&self) -> Result<()> { + require_token(&self.provider_id, "provider id")?; + if let Some(target) = &self.provider_target { + require_token(target, "provider target")?; + } + require_token(&self.generation, "provider generation")?; + if let Some(deployment_id) = &self.deployment_id { + require_token(deployment_id, "provider deployment id")?; + } + require_contract(&self.capability, &self.schema, &self.compatibility)?; + ensure!(self.capacity > 0, "provider capacity is zero"); + require_value(&self.endpoint, "provider endpoint")?; + ensure!( + !self.present || self.expected, + "provider is present without expected admission" + ); + ensure!( + !self.ready || self.present, + "provider is ready without signed presence" + ); + match self.origin { + ProviderOrigin::ManagedRuntime => { + ensure!( + self.provider_target.is_some(), + "managed provider has no target" + ); + if self.present { + ensure!( + self.deployment_id.is_some(), + "present managed provider has no deployment identity" + ); + require_sha256( + self.observation_sha256.as_deref().unwrap_or_default(), + "managed provider observation", + )?; + } + } + ProviderOrigin::ExternalOperatorBinding => { + ensure!( + self.provider_target.is_none(), + "external binding impersonates a managed target" + ); + ensure!( + !self.present && !self.ready, + "external configuration impersonates runtime observation" + ); + ensure!( + self.observation_sha256.is_none(), + "external configuration carries a runtime observation digest" + ); + } + } + Ok(()) + } + + fn compatible_with(&self, dependency: &CapabilityDependency) -> bool { + capability_compatible( + &dependency.capability, + &dependency.schema, + &dependency.compatibility, + &self.capability, + &self.schema, + &self.compatibility, + ) && self.capacity >= dependency.minimum_capacity + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DependencyResolution { + pub requirement: CapabilityDependency, + pub provider: Option, +} + +impl DependencyResolution { + pub fn blocks_start(&self) -> bool { + self.requirement.startup == crate::deployment::StartupOrder::BeforeStart + && self.requirement.kind != DependencyKind::Optional + && !self + .provider + .as_ref() + .is_some_and(|provider| provider.ready) + } + + pub fn blocks_promotion(&self) -> bool { + self.requirement.kind != DependencyKind::Optional + && !self + .provider + .as_ref() + .is_some_and(|provider| provider.ready) + } +} + +pub fn external_binding_observations( + bindings: &[ExternalCapabilityBinding], +) -> Vec { + bindings + .iter() + .map(|binding| ProviderObservation { + provider_id: format!("operator:{}", binding.capability), + provider_target: None, + origin: ProviderOrigin::ExternalOperatorBinding, + generation: "operator-bound".into(), + deployment_id: None, + capability: binding.capability.clone(), + schema: binding.schema.clone(), + compatibility: binding.compatibility.clone(), + capacity: 1, + endpoint: binding.endpoint.clone(), + expected: true, + present: false, + ready: false, + observation_sha256: None, + }) + .collect() +} + +pub fn resolve_dependencies( + declaration: &TargetDeclaration, + observations: &[ProviderObservation], +) -> Result> { + for observation in observations { + observation.validate()?; + } + for conflict in &declaration.conflicts { + if observations + .iter() + .any(|provider| provider.expected && provider.capability == conflict.capability) + { + bail!( + "capability conflict {}: {}", + conflict.capability, + conflict.reason + ); + } + } + declaration + .dependencies + .iter() + .map(|dependency| { + let mut candidates = observations + .iter() + .filter(|provider| provider.expected && provider.compatible_with(dependency)) + .cloned() + .collect::>(); + if dependency.kind == DependencyKind::ExternalOperatorBinding { + candidates + .retain(|provider| provider.origin == ProviderOrigin::ExternalOperatorBinding); + } else { + candidates.retain(|provider| provider.origin == ProviderOrigin::ManagedRuntime); + } + candidates.sort_by(|left, right| { + right + .ready + .cmp(&left.ready) + .then_with(|| right.present.cmp(&left.present)) + .then_with(|| left.provider_id.cmp(&right.provider_id)) + }); + let provider = candidates.into_iter().next(); + if provider.is_none() && dependency.kind != DependencyKind::Optional { + bail!( + "no expected provider satisfies {} {} {}", + dependency.capability, + dependency.schema, + dependency.compatibility + ); + } + Ok(DependencyResolution { + requirement: dependency.clone(), + provider, + }) + }) + .collect() +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExpectedGeneration { + pub schema: String, + pub target: String, + pub generation: String, + pub deployment_id: String, + pub source_revision: String, + pub candidate_endpoint: Option, + pub capabilities: Vec, +} + +impl ExpectedGeneration { + pub fn validate(&self) -> Result<()> { + ensure!( + self.schema == EXPECTED_GENERATION_SCHEMA, + "unsupported expected-generation schema" + ); + require_token(&self.target, "expected target")?; + require_token(&self.generation, "expected generation")?; + require_token(&self.deployment_id, "expected deployment")?; + require_sha1(&self.source_revision, "expected source revision")?; + if let Some(endpoint) = &self.candidate_endpoint { + require_value(endpoint, "candidate endpoint")?; + } + let mut capabilities = BTreeSet::new(); + for capability in &self.capabilities { + require_contract( + &capability.capability, + &capability.schema, + &capability.compatibility, + )?; + ensure!( + capability.capacity > 0, + "expected capability capacity is zero" + ); + ensure!( + capabilities.insert(( + &capability.capability, + &capability.schema, + &capability.compatibility + )), + "expected capability is duplicated" + ); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CompiledDeploymentPlan { + pub schema: String, + pub plan_id: String, + pub deployment_id: String, + pub created_at_unix_millis: u64, + pub source: ExactSource, + pub recipe_sha256: String, + pub binding_sha256: String, + pub declaration: TargetDeclaration, + pub binding: OperatorBinding, + pub dependencies: Vec, + pub expected: ExpectedGeneration, +} + +impl CompiledDeploymentPlan { + pub fn validate(&self) -> Result<()> { + ensure!( + self.schema == COMPILED_DEPLOYMENT_PLAN_SCHEMA, + "unsupported deployment-plan schema" + ); + require_sha256(&self.plan_id, "plan id")?; + require_token(&self.deployment_id, "deployment id")?; + ensure!( + self.created_at_unix_millis > 0, + "deployment plan has no creation time" + ); + self.declaration.validate()?; + self.binding.validate()?; + self.binding.admit(&self.declaration)?; + self.source.validate_against(&self.binding)?; + require_sha256(&self.recipe_sha256, "recipe digest")?; + require_sha256(&self.binding_sha256, "binding digest")?; + self.expected.validate()?; + ensure!( + self.expected.target == self.declaration.target, + "expected target differs from recipe" + ); + ensure!( + self.expected.generation == self.declaration.state.generation, + "expected generation differs from recipe" + ); + ensure!( + self.expected.deployment_id == self.deployment_id, + "expected deployment differs from plan" + ); + ensure!( + self.expected.source_revision == self.source.revision, + "expected source differs from plan" + ); + ensure!( + self.expected.capabilities == self.declaration.provides, + "expected capabilities differ from recipe" + ); + let resolved_requirements: Vec<_> = self + .dependencies + .iter() + .map(|resolution| &resolution.requirement) + .collect(); + let declared_requirements: Vec<_> = self.declaration.dependencies.iter().collect(); + ensure!( + resolved_requirements == declared_requirements, + "resolved graph differs from recipe dependencies" + ); + for resolution in &self.dependencies { + if let Some(provider) = &resolution.provider { + provider.validate()?; + ensure!( + provider.compatible_with(&resolution.requirement), + "resolved provider is incompatible" + ); + } else { + ensure!( + resolution.requirement.kind == DependencyKind::Optional, + "required dependency is unresolved" + ); + } + } + ensure!( + self.plan_id == self.recomputed_plan_id()?, + "deployment plan digest is not canonical" + ); + Ok(()) + } + + fn recomputed_plan_id(&self) -> Result { + let mut unsigned = self.clone(); + unsigned.plan_id.clear(); + Ok(sha256_id( + &rmp_serde::to_vec(&unsigned).context("encoding deployment plan identity")?, + )) + } +} + +#[allow(clippy::too_many_arguments)] +pub fn compile_deployment_plan( + declaration: TargetDeclaration, + binding: OperatorBinding, + source: ExactSource, + recipe_bytes: &[u8], + binding_bytes: &[u8], + deployment_id: impl Into, + candidate_port: Option, + created_at_unix_millis: u64, + observed_providers: &[ProviderObservation], +) -> Result { + declaration.validate()?; + binding.validate()?; + binding.admit(&declaration)?; + source.validate_against(&binding)?; + let deployment_id = deployment_id.into(); + require_token(&deployment_id, "deployment id")?; + ensure!( + created_at_unix_millis > 0, + "deployment plan has no creation time" + ); + let candidate_endpoint = match (&binding.route, candidate_port) { + (Some(route), Some(port)) => { + ensure!( + (route.private_port_start..=route.private_port_end).contains(&port), + "candidate port is outside the operator range" + ); + Some(format!("{}:{port}", route.private_host)) + } + (None, None) => None, + (Some(_), None) => bail!("routed deployment has no candidate port"), + (None, Some(_)) => bail!("private deployment cannot select a routed candidate port"), + }; + let mut providers = observed_providers.to_vec(); + providers.extend(external_binding_observations( + &binding.external_capabilities, + )); + let dependencies = resolve_dependencies(&declaration, &providers)?; + let expected = ExpectedGeneration { + schema: EXPECTED_GENERATION_SCHEMA.into(), + target: declaration.target.clone(), + generation: declaration.state.generation.clone(), + deployment_id: deployment_id.clone(), + source_revision: source.revision.clone(), + candidate_endpoint, + capabilities: declaration.provides.clone(), + }; + let mut plan = CompiledDeploymentPlan { + schema: COMPILED_DEPLOYMENT_PLAN_SCHEMA.into(), + plan_id: String::new(), + deployment_id, + created_at_unix_millis, + source, + recipe_sha256: sha256_id(recipe_bytes), + binding_sha256: sha256_id(binding_bytes), + declaration, + binding, + dependencies, + expected, + }; + plan.plan_id = plan.recomputed_plan_id()?; + plan.validate()?; + Ok(plan) +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ArtifactSeal { + pub artifact_id: String, + pub destination: PathBuf, + pub sha256: String, + pub size_bytes: u64, + pub executable: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SealedDeployment { + pub schema: String, + pub release_id: String, + pub plan: CompiledDeploymentPlan, + pub plan_sha256: String, + pub artifacts: Vec, + pub sealed_at_unix_millis: u64, +} + +impl SealedDeployment { + pub fn new( + plan: CompiledDeploymentPlan, + release_id: impl Into, + artifacts: Vec, + sealed_at_unix_millis: u64, + ) -> Result { + plan.validate()?; + let mut sealed = Self { + schema: SEALED_DEPLOYMENT_SCHEMA.into(), + release_id: release_id.into(), + plan_sha256: sha256_id(&rmp_serde::to_vec(&plan)?), + plan, + artifacts, + sealed_at_unix_millis, + }; + sealed.validate()?; + sealed + .artifacts + .sort_by(|left, right| left.artifact_id.cmp(&right.artifact_id)); + sealed.validate()?; + Ok(sealed) + } + + pub fn validate(&self) -> Result<()> { + ensure!( + self.schema == SEALED_DEPLOYMENT_SCHEMA, + "unsupported sealed-deployment schema" + ); + require_token(&self.release_id, "release id")?; + ensure!( + self.sealed_at_unix_millis >= self.plan.created_at_unix_millis, + "deployment was sealed before it was planned" + ); + self.plan.validate()?; + ensure!( + self.plan_sha256 == sha256_id(&rmp_serde::to_vec(&self.plan)?), + "sealed plan digest is wrong" + ); + let declared = self + .plan + .declaration + .artifacts + .iter() + .map(|artifact| { + ( + artifact.id.as_str(), + artifact.destination.as_path(), + artifact.executable, + ) + }) + .chain( + self.plan + .declaration + .external_artifacts + .iter() + .map(|artifact| { + ( + artifact.id.as_str(), + artifact.destination.as_path(), + artifact.executable, + ) + }), + ) + .collect::>(); + let mut observed = BTreeSet::new(); + for artifact in &self.artifacts { + require_token(&artifact.artifact_id, "artifact seal id")?; + require_sha256(&artifact.sha256, "artifact seal digest")?; + ensure!(artifact.size_bytes > 0, "sealed artifact is empty"); + ensure!( + observed.insert(( + artifact.artifact_id.as_str(), + artifact.destination.as_path(), + artifact.executable + )), + "artifact seal is duplicated" + ); + } + ensure!( + declared == observed, + "sealed artifacts differ from declared outputs" + ); + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RuntimePresence { + pub target: String, + pub generation: String, + pub deployment_id: String, + pub source_revision: String, + pub endpoint: Option, + pub capabilities: Vec, + pub runtime_id: String, + pub signer_identity_id: String, + pub signed_statement_sha256: String, +} + +impl RuntimePresence { + pub fn validate(&self) -> Result<()> { + require_token(&self.target, "presence target")?; + require_token(&self.generation, "presence generation")?; + require_token(&self.deployment_id, "presence deployment")?; + require_sha1(&self.source_revision, "presence source revision")?; + if let Some(endpoint) = &self.endpoint { + require_value(endpoint, "presence endpoint")?; + } + require_token(&self.runtime_id, "presence runtime")?; + require_token(&self.signer_identity_id, "presence signer")?; + require_sha256(&self.signed_statement_sha256, "presence statement")?; + let mut capabilities = BTreeSet::new(); + for capability in &self.capabilities { + require_contract( + &capability.capability, + &capability.schema, + &capability.compatibility, + )?; + ensure!( + capability.capacity > 0, + "presence capability capacity is zero" + ); + ensure!( + capabilities.insert(( + &capability.capability, + &capability.schema, + &capability.compatibility, + )), + "presence capability is duplicated" + ); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HealthObservation { + pub contract: String, + pub state: String, + pub detail: String, + pub signed_statement_sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GenerationCorrelation { + pub schema: String, + pub target: String, + pub generation: String, + pub expected: bool, + pub present: bool, + pub ready: bool, + pub disagreements: Vec, +} + +pub fn correlate_generation( + plan: &CompiledDeploymentPlan, + presence: Option<&RuntimePresence>, + health: Option<&HealthObservation>, +) -> Result { + plan.validate()?; + let mut disagreements = Vec::new(); + let mut present = false; + if let Some(presence) = presence { + presence.validate()?; + for (matches, code) in [ + (presence.target == plan.expected.target, "target-mismatch"), + ( + presence.generation == plan.expected.generation, + "generation-mismatch", + ), + ( + presence.deployment_id == plan.expected.deployment_id, + "deployment-mismatch", + ), + ( + presence.source_revision == plan.expected.source_revision, + "source-mismatch", + ), + ( + presence.endpoint == plan.expected.candidate_endpoint, + "endpoint-mismatch", + ), + ( + capability_set(&presence.capabilities) + == capability_set(&plan.expected.capabilities), + "capability-mismatch", + ), + ] { + if !matches { + disagreements.push(code.into()); + } + } + present = disagreements.is_empty(); + } else { + disagreements.push("runtime-presence-missing".into()); + } + let mut health_ready = false; + if let (Some(presence), Some(health)) = (presence, health) { + require_token(&health.contract, "health contract")?; + require_value(&health.state, "health state")?; + require_value(&health.detail, "health detail")?; + require_sha256(&health.signed_statement_sha256, "health statement")?; + if health.signed_statement_sha256 != presence.signed_statement_sha256 { + disagreements.push("health-presence-statement-mismatch".into()); + } else if health.contract != plan.declaration.service.health.contract { + disagreements.push("health-contract-mismatch".into()); + } else if health.state != plan.declaration.service.health.ready.state { + disagreements.push("health-state-not-ready".into()); + } else if health.detail != plan.declaration.service.health.ready.detail { + disagreements.push("health-detail-not-ready".into()); + } else { + health_ready = true; + } + } else if health.is_none() { + disagreements.push("health-missing".into()); + } + if plan + .dependencies + .iter() + .any(DependencyResolution::blocks_promotion) + { + disagreements.push("dependency-graph-not-ready".into()); + } + disagreements.sort(); + disagreements.dedup(); + Ok(GenerationCorrelation { + schema: GENERATION_CORRELATION_SCHEMA.into(), + target: plan.expected.target.clone(), + generation: plan.expected.generation.clone(), + expected: true, + present, + ready: present && health_ready && disagreements.is_empty(), + disagreements, + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum PromotionPhase { + Planned, + Materialized, + Sealed, + CandidateStarted, + Staged, + Fenced, + RouteObserved, + WriteAdmitted, + Active, + Draining, + Complete, +} + +impl PromotionPhase { + pub fn next(self) -> Option { + Some(match self { + Self::Planned => Self::Materialized, + Self::Materialized => Self::Sealed, + Self::Sealed => Self::CandidateStarted, + Self::CandidateStarted => Self::Staged, + Self::Staged => Self::Fenced, + Self::Fenced => Self::RouteObserved, + Self::RouteObserved => Self::WriteAdmitted, + Self::WriteAdmitted => Self::Active, + Self::Active => Self::Draining, + Self::Draining => Self::Complete, + Self::Complete => return None, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PromotionTransaction { + pub schema: String, + pub transaction_id: String, + pub plan_id: String, + pub target: String, + pub phase: PromotionPhase, + pub revision: u64, + pub updated_at_unix_millis: u64, +} + +impl PromotionTransaction { + pub fn new( + transaction_id: impl Into, + plan: &CompiledDeploymentPlan, + created_at_unix_millis: u64, + ) -> Result { + plan.validate()?; + let transaction = Self { + schema: PROMOTION_TRANSACTION_SCHEMA.into(), + transaction_id: transaction_id.into(), + plan_id: plan.plan_id.clone(), + target: plan.declaration.target.clone(), + phase: PromotionPhase::Planned, + revision: 0, + updated_at_unix_millis: created_at_unix_millis, + }; + transaction.validate()?; + Ok(transaction) + } + + pub fn validate(&self) -> Result<()> { + ensure!( + self.schema == PROMOTION_TRANSACTION_SCHEMA, + "unsupported promotion transaction schema" + ); + require_token(&self.transaction_id, "promotion transaction")?; + require_sha256(&self.plan_id, "promotion plan")?; + require_token(&self.target, "promotion target")?; + ensure!( + self.updated_at_unix_millis > 0, + "promotion transaction has no update time" + ); + Ok(()) + } + + pub fn advance(&self, phase: PromotionPhase, updated_at_unix_millis: u64) -> Result { + self.validate()?; + ensure!( + self.phase.next() == Some(phase), + "promotion phase transition is not adjacent" + ); + ensure!( + updated_at_unix_millis >= self.updated_at_unix_millis, + "promotion time moved backwards" + ); + let next = Self { + schema: self.schema.clone(), + transaction_id: self.transaction_id.clone(), + plan_id: self.plan_id.clone(), + target: self.target.clone(), + phase, + revision: self + .revision + .checked_add(1) + .context("promotion revision overflow")?, + updated_at_unix_millis, + }; + next.validate()?; + Ok(next) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AdmittedGeneration { + pub schema: String, + pub target: String, + pub generation: String, + pub deployment_id: String, + pub plan_id: String, + pub release_id: String, + pub source_revision: String, + pub workload_unit: String, + pub process_id: u32, + pub process_starttime_ticks: u64, + pub private_endpoint: Option, + pub route_id: Option, + pub route_observation_sha256: Option, + pub write_admission_sha256: String, + pub admitted_at_unix_millis: u64, +} + +impl AdmittedGeneration { + pub fn validate_against(&self, sealed: &SealedDeployment) -> Result<()> { + ensure!( + self.schema == ADMITTED_GENERATION_SCHEMA, + "unsupported admitted-generation schema" + ); + sealed.validate()?; + require_token(&self.target, "admitted target")?; + require_token(&self.generation, "admitted generation")?; + require_token(&self.deployment_id, "admitted deployment")?; + require_sha256(&self.plan_id, "admitted plan")?; + require_token(&self.release_id, "admitted release")?; + require_sha1(&self.source_revision, "admitted source")?; + require_token(&self.workload_unit, "admitted workload unit")?; + ensure!(self.process_id > 0, "admitted process id is zero"); + ensure!( + self.process_starttime_ticks > 0, + "admitted process start time is zero" + ); + if let Some(endpoint) = &self.private_endpoint { + require_value(endpoint, "admitted private endpoint")?; + } + match (&self.route_id, &self.route_observation_sha256) { + (Some(route_id), Some(digest)) => { + require_token(route_id, "admitted route")?; + require_sha256(digest, "route observation")?; + } + (None, None) => {} + _ => bail!("admitted route identity and observation are incomplete"), + } + require_sha256(&self.write_admission_sha256, "write admission")?; + ensure!(self.admitted_at_unix_millis > 0, "admission has no time"); + ensure!( + self.target == sealed.plan.declaration.target, + "admitted target differs from sealed plan" + ); + ensure!( + self.generation == sealed.plan.declaration.state.generation, + "admitted generation differs from sealed plan" + ); + ensure!( + self.deployment_id == sealed.plan.deployment_id, + "admitted deployment differs from sealed plan" + ); + ensure!( + self.plan_id == sealed.plan.plan_id, + "admitted plan differs from sealed plan" + ); + ensure!( + self.release_id == sealed.release_id, + "admitted release differs from sealed plan" + ); + ensure!( + self.source_revision == sealed.plan.source.revision, + "admitted source differs from sealed plan" + ); + ensure!( + self.private_endpoint == sealed.plan.expected.candidate_endpoint, + "admitted endpoint differs from expected plan" + ); + match &sealed.plan.binding.route { + Some(route) => ensure!( + self.route_id.as_deref() == Some(route.route_id.as_str()), + "admitted route differs from binding" + ), + None => ensure!( + self.route_id.is_none(), + "private deployment carries a route" + ), + } + Ok(()) + } +} + +fn require_token(value: &str, label: &str) -> Result<()> { + ensure!( + !value.is_empty() && value.len() <= 128, + "{label} is empty or too long" + ); + ensure!( + value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() + || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/')), + "{label} contains a forbidden character" + ); + Ok(()) +} + +fn require_contract(capability: &str, schema: &str, compatibility: &str) -> Result<()> { + require_token(capability, "capability")?; + require_token(schema, "capability schema")?; + require_token(compatibility, "capability compatibility") +} + +fn capability_set(capabilities: &[ProvidedCapability]) -> BTreeSet<(&str, &str, &str, u32)> { + capabilities + .iter() + .map(|capability| { + ( + capability.capability.as_str(), + capability.schema.as_str(), + capability.compatibility.as_str(), + capability.capacity, + ) + }) + .collect() +} + +fn require_value(value: &str, label: &str) -> Result<()> { + ensure!( + !value.trim().is_empty() && value == value.trim(), + "{label} is empty or noncanonical" + ); + ensure!( + value.len() <= 4096 && !value.contains('\0'), + "{label} is oversized or contains NUL" + ); + Ok(()) +} + +fn require_sha1(value: &str, label: &str) -> Result<()> { + require_lower_hex(value, 40, label) +} + +fn require_sha256(value: &str, label: &str) -> Result<()> { + let digest = value + .strip_prefix("sha256-") + .with_context(|| format!("{label} has no sha256- prefix"))?; + require_lower_hex(digest, 64, label) +} + +fn require_lower_hex(value: &str, length: usize, label: &str) -> Result<()> { + ensure!(value.len() == length, "{label} has the wrong length"); + ensure!( + value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)), + "{label} is not lowercase hexadecimal" + ); + Ok(()) +} + +fn sha256_id(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + let mut encoded = String::with_capacity(71); + encoded.push_str("sha256-"); + for byte in digest { + use std::fmt::Write as _; + write!(&mut encoded, "{byte:02x}").expect("writing to String cannot fail"); + } + encoded +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::deployment::{OperatorBinding, TargetDeclaration}; + + const RECIPE: &str = r#" +schema = "gamecult.idunn.target_declaration.v1" +target = "service" +source_stamp_environment = "SERVICE_BUILD_COMMIT" + +[[steps]] +id = "build" +phase = "build" +runner = "rust" +argv = ["cargo", "build", "--locked"] + +[[artifacts]] +id = "daemon" +source_kind = "runner-output" +runner = "rust" +source = "target/release/service" +destination = "service" +executable = true + +[service] +executable_artifact = "daemon" +transport = "http" +route_required = true +required_environment = ["SERVICE_BIND"] + +[service.health] +contract = "service.health" + +[service.health.staged] +state = "warming" +detail = "traffic-admission-pending" + +[service.health.ready] +state = "active" +detail = "serving" + +[state] +generation = "v1" + +[[provides]] +capability = "service.runtime" +schema = "service.runtime.v1" +compatibility = "v1" + +[[dependencies]] +kind = "shared-infrastructure" +capability = "odin.verse-rendezvous" +schema = "odin.verse-topology.v1" +compatibility = "v1" +"#; + + const BINDING: &str = r#" +schema = "gamecult.idunn.operator_binding.v1" +target = "service" + +[repository] +origin = "https://github.com/GameCult/Service.git" +admitted_ref = "refs/heads/main" +minimum_revision = "1111111111111111111111111111111111111111" +selection = "ref-head" +checkout = "/srv/build/Service" +recipe_path = "deployment/idunn/recipe.toml" + +[runners.rust] +driver = "docker" +image = "rust@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +affordances = ["source-read", "artifact-write"] +allowed_programs = ["cargo"] +network = "none" +memory_mebibytes = 2048 +cpu_quota_percent = 200 + +[workload] +driver = "systemd-transient" +user = "service" +group = "service" +unit_prefix = "idunn-service" +release_root = "/srv/service/releases" +state_root = "/var/lib/gamecult/service" +runtime_root = "/run/gamecult/idunn/service" +network = "host-private" +hardening = "strict" +memory_mebibytes = 1024 +cpu_quota_percent = 100 + +[workload.environment] +SERVICE_BIND = "idunn.private_endpoint" + +[route] +driver = "nginx-http" +route_id = "service" +stable_endpoint = "https://example.invalid/service/" +private_host = "127.0.0.1" +private_port_start = 18000 +private_port_end = 18009 +config_path = "/etc/nginx/idunn-routes/service.conf" +reload_unit = "nginx.service" + +[admission] +driver = "atomic-file" +record_path = "/run/gamecult/idunn/service/admission.cc" +lock_path = "/run/gamecult/idunn/service/admission.cc.lock" + +[brakes] +deployment_store = "/var/lib/gamecult/idunn/service-deployment-brake.cc" +lifecycle_store = "/var/lib/gamecult/idunn/service-lifecycle-brake.cc" + +[state_transition] +policy = "preserve" + +[rollout] +strategy = "candidate-then-promote" +drain_seconds = 30 +retain_releases = 2 + +[placement] +desired_replicas = 1 +nodes = ["yggdrasil"] +"#; + + fn provider(ready: bool) -> ProviderObservation { + ProviderObservation { + provider_id: "odin-yggdrasil".into(), + provider_target: Some("odin".into()), + origin: ProviderOrigin::ManagedRuntime, + generation: "odin-v1".into(), + deployment_id: Some("odin-deployment-1".into()), + capability: "odin.verse-rendezvous".into(), + schema: "odin.verse-topology.v1".into(), + compatibility: "v1".into(), + capacity: 1, + endpoint: "10.77.0.1:17871".into(), + expected: true, + present: ready, + ready, + observation_sha256: ready.then(|| format!("sha256-{}", "a".repeat(64))), + } + } + + fn plan(provider: ProviderObservation) -> CompiledDeploymentPlan { + compile_deployment_plan( + TargetDeclaration::parse(RECIPE).unwrap(), + OperatorBinding::parse(BINDING).unwrap(), + ExactSource { + origin: "https://github.com/GameCult/Service.git".into(), + admitted_ref: "refs/heads/main".into(), + revision: "2222222222222222222222222222222222222222".into(), + minimum_revision: "1111111111111111111111111111111111111111".into(), + selection_receipt_sha256: format!("sha256-{}", "d".repeat(64)), + gitlinks: BTreeMap::new(), + }, + RECIPE.as_bytes(), + BINDING.as_bytes(), + "deployment-1", + Some(18001), + 100, + &[provider], + ) + .unwrap() + } + + #[test] + fn compilation_is_deterministic_and_configuration_does_not_supply_readiness() { + let first = plan(provider(true)); + let second = plan(provider(true)); + assert_eq!(first, second); + assert!(!first.dependencies[0].blocks_promotion()); + + let external = ExternalCapabilityBinding { + capability: "odin.verse-rendezvous".into(), + schema: "odin.verse-topology.v1".into(), + compatibility: "v1".into(), + endpoint: "10.77.0.1:17871".into(), + }; + let observations = external_binding_observations(&[external]); + assert!(!observations[0].present); + assert!(!observations[0].ready); + } + + #[test] + fn shared_infrastructure_reuses_the_ready_provider() { + let mut weaker = provider(false); + weaker.provider_id = "odin-candidate".into(); + let resolved = resolve_dependencies( + &TargetDeclaration::parse(RECIPE).unwrap(), + &[weaker, provider(true)], + ) + .unwrap(); + assert_eq!( + resolved[0].provider.as_ref().unwrap().provider_id, + "odin-yggdrasil" + ); + } + + #[test] + fn present_and_ready_are_distinct_from_expected() { + let plan = plan(provider(true)); + let presence = RuntimePresence { + target: "service".into(), + generation: "v1".into(), + deployment_id: "deployment-1".into(), + source_revision: "2222222222222222222222222222222222222222".into(), + endpoint: Some("127.0.0.1:18001".into()), + capabilities: plan.expected.capabilities.clone(), + runtime_id: "service-runtime".into(), + signer_identity_id: "signer-1".into(), + signed_statement_sha256: format!("sha256-{}", "b".repeat(64)), + }; + let health = HealthObservation { + contract: "service.health".into(), + state: "active".into(), + detail: "serving".into(), + signed_statement_sha256: presence.signed_statement_sha256.clone(), + }; + let absent = correlate_generation(&plan, None, None).unwrap(); + assert!(absent.expected); + assert!(!absent.present); + assert!(!absent.ready); + let ready = correlate_generation(&plan, Some(&presence), Some(&health)).unwrap(); + assert!(ready.present); + assert!(ready.ready); + } + + #[test] + fn disagreement_remains_visible_and_blocks_readiness() { + let plan = plan(provider(true)); + let presence = RuntimePresence { + target: "service".into(), + generation: "wrong-generation".into(), + deployment_id: "deployment-1".into(), + source_revision: "2222222222222222222222222222222222222222".into(), + endpoint: Some("127.0.0.1:18001".into()), + capabilities: plan.expected.capabilities.clone(), + runtime_id: "service-runtime".into(), + signer_identity_id: "signer-1".into(), + signed_statement_sha256: format!("sha256-{}", "b".repeat(64)), + }; + let health = HealthObservation { + contract: "service.health".into(), + state: "active".into(), + detail: "serving".into(), + signed_statement_sha256: presence.signed_statement_sha256.clone(), + }; + let correlation = correlate_generation(&plan, Some(&presence), Some(&health)).unwrap(); + assert!(!correlation.present); + assert!(!correlation.ready); + assert!( + correlation + .disagreements + .contains(&"generation-mismatch".into()) + ); + } + + #[test] + fn sealed_artifacts_and_promotion_phases_are_exact() { + let plan = plan(provider(true)); + let sealed = SealedDeployment::new( + plan.clone(), + "release-1", + vec![ArtifactSeal { + artifact_id: "daemon".into(), + destination: "service".into(), + sha256: format!("sha256-{}", "c".repeat(64)), + size_bytes: 42, + executable: true, + }], + 110, + ) + .unwrap(); + sealed.validate().unwrap(); + let transaction = PromotionTransaction { + schema: PROMOTION_TRANSACTION_SCHEMA.into(), + transaction_id: "transaction-1".into(), + plan_id: plan.plan_id, + target: "service".into(), + phase: PromotionPhase::Planned, + revision: 0, + updated_at_unix_millis: 100, + }; + assert!(transaction.advance(PromotionPhase::Sealed, 101).is_err()); + assert_eq!( + transaction + .advance(PromotionPhase::Materialized, 101) + .unwrap() + .phase, + PromotionPhase::Materialized + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 58309eb..7474d59 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,3 @@ +pub mod deployment; +pub mod deployment_plan; pub mod provisioning;