From a539d4fb1ce90f86cc4f79d214dc48c1f8c369ab Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Sep 2026 22:56:41 +0200 Subject: [PATCH] Return the Idunn and Odin authority contracts to CultLib The standalone GameCult/cultnet-rs holds six modules CultLib never received: runtime_authority_contracts, service_identity, provider_health_contracts, idunn_deployment_brake, idunn_lifecycle_brake, and snapshot_query. They own Idunn Expected incarnations, dual-proved runtime activation, process write leases, service-signed presence health, and Odin topology correlation -- the wire contracts every GameCult daemon must agree on. They belong here because wire parity conformance lives here and nothing outside it is checked for cross-runtime agreement. Held as source to be copied, this contract already forked: Ghostlight vendors it at e542225 while its own authority map names f4ab237, and the two disagree on whether Present may coexist with a disagreement. One copy makes them exclusive; the other separates presence from readiness and gates through into_undisputed_present. A single owner under the parity harness is the fix; re-vendoring is not. None of the six touch RUDP, so they land without disturbing the protocol core. rudp.rs remains genuinely forked -- 140 hunks between the lineages, with reliable windows and ACK horizons on this side and bounded session memory, exact acknowledgement receipts, and hostile rollover rejection on the other. That reconciliation needs the cross-runtime interop harness and is not attempted here. Adds ed25519-dalek, zeroize, and the Windows Foundation/Cryptography features the credential paths require. 96 tests pass. The two rudp_server_hub failures are pre-existing on this base and reproduce at 230ace6 untouched. Co-Authored-By: Claude Opus 5 --- packages/cultnet-rs/Cargo.toml | 5 + .../cultnet-rs/src/idunn_deployment_brake.rs | 492 +++ .../cultnet-rs/src/idunn_lifecycle_brake.rs | 325 ++ packages/cultnet-rs/src/lib.rs | 12 + .../src/provider_health_contracts.rs | 653 ++++ .../src/runtime_authority_contracts.rs | 3309 +++++++++++++++++ packages/cultnet-rs/src/service_identity.rs | 920 +++++ packages/cultnet-rs/src/snapshot_query.rs | 339 ++ 8 files changed, 6055 insertions(+) create mode 100644 packages/cultnet-rs/src/idunn_deployment_brake.rs create mode 100644 packages/cultnet-rs/src/idunn_lifecycle_brake.rs create mode 100644 packages/cultnet-rs/src/provider_health_contracts.rs create mode 100644 packages/cultnet-rs/src/runtime_authority_contracts.rs create mode 100644 packages/cultnet-rs/src/service_identity.rs create mode 100644 packages/cultnet-rs/src/snapshot_query.rs diff --git a/packages/cultnet-rs/Cargo.toml b/packages/cultnet-rs/Cargo.toml index 41d14b52..f289d86e 100644 --- a/packages/cultnet-rs/Cargo.toml +++ b/packages/cultnet-rs/Cargo.toml @@ -16,6 +16,7 @@ anyhow = "1" base64 = "0.22" chrono = { version = "0.4", features = ["serde"] } cultcache-rs = { path = "../cultcache-rs" } +ed25519-dalek = "2.2" hmac = "0.12" rand = "0.9" rmp-serde = "1.3" @@ -24,9 +25,13 @@ serde = { version = "1", features = ["derive"] } serde_bytes = "0.11" serde_json = "1" sha2 = "0.10" +zeroize = "1" socket2 = "0.5" uuid = { version = "1", features = ["v4"] } +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography"] } + [dev-dependencies] pretty_assertions = "1.4" tempfile = "3" diff --git a/packages/cultnet-rs/src/idunn_deployment_brake.rs b/packages/cultnet-rs/src/idunn_deployment_brake.rs new file mode 100644 index 00000000..e790f2a1 --- /dev/null +++ b/packages/cultnet-rs/src/idunn_deployment_brake.rs @@ -0,0 +1,492 @@ +use anyhow::{Result, bail}; +use cultcache_rs::DatabaseEntry; + +use crate::{ + IdunnDeploymentBrakeOperatorIdentity, IdunnDeploymentBrakeReleasePurpose, + ServiceIdentitySignature, ServiceIdentityTrustAnchor, verify_service_identity_signature, +}; + +pub const IDUNN_DEPLOYMENT_BRAKE_SCHEMA: &str = "idunn.deployment_brake.v1"; +pub const IDUNN_DEPLOYMENT_BRAKE_TYPE: &str = "idunn.deployment_brake"; +pub const IDUNN_DEPLOYMENT_BRAKE_ID: &str = "idunn/deployment-brake"; +pub const IDUNN_DEPLOYMENT_BRAKE_AUTHORITY: &str = "idunn.deployment-brake"; +pub const IDUNN_DEPLOYMENT_BRAKE_SCOPE: &str = "deployment"; +pub const IDUNN_DEPLOYMENT_RELEASE_PURPOSE: &str = "idunn.deployment-release.v1"; +pub const IDUNN_DEPLOYMENT_RELEASE_MAX_LIFETIME_MILLIS: u64 = 15 * 60 * 1_000; + +/// Canonical deployment-facing brake projection consumed by Idunn. A released +/// status is not permission by itself: the authorization fields bind one +/// release and one deployment attempt for a short, explicit interval. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "idunn.deployment_brake", schema = "idunn.deployment_brake.v1")] +pub struct IdunnDeploymentBrakeRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub brake_id: String, + #[cultcache(key = 2)] + pub authority: String, + #[cultcache(key = 3)] + pub runtime_id: String, + #[cultcache(key = 4)] + pub status: String, + #[cultcache(key = 5)] + pub scope: String, + #[cultcache(key = 6)] + pub reason: String, + #[cultcache(key = 7)] + pub observed_at_unix_millis: u64, + #[cultcache(key = 8)] + pub expires_at_unix_millis: Option, + #[cultcache(key = 9)] + pub authorization_id: Option, + #[cultcache(key = 10)] + pub authorization_purpose: Option, + #[cultcache(key = 11)] + pub authorized_release_id: Option, + #[cultcache(key = 12)] + pub authorized_deployment_id: Option, + #[cultcache(key = 13)] + pub authorized_by: Option, + #[cultcache(key = 14)] + pub authorization_issued_at_unix_millis: Option, + #[cultcache(key = 15)] + pub authorization_expires_at_unix_millis: Option, + #[cultcache(key = 16)] + pub signature_algorithm: Option, + #[cultcache(key = 17)] + pub signature: Option>, + #[cultcache(key = 18)] + pub private_state_exposed: bool, + /// Human/operator principal responsible for the latest transition. This is + /// distinct from `authorized_by`, which is the cryptographic identity id. + #[cultcache(key = 19)] + pub updated_by: String, +} + +impl IdunnDeploymentBrakeRecord { + pub fn validate(&self) -> Result<()> { + if self.schema_version != IDUNN_DEPLOYMENT_BRAKE_SCHEMA { + bail!("deployment brake schema is unsupported"); + } + identifier(&self.brake_id, "brake id")?; + identifier(&self.authority, "authority")?; + identifier(&self.runtime_id, "runtime id")?; + identifier(&self.reason, "reason")?; + identifier(&self.scope, "scope")?; + identifier(&self.updated_by, "updating operator")?; + if !matches!(self.status.as_str(), "engaged" | "released") + || self.observed_at_unix_millis == 0 + || self + .expires_at_unix_millis + .is_some_and(|v| v <= self.observed_at_unix_millis) + || self.private_state_exposed + { + bail!("deployment brake shape, lifetime, or privacy is invalid"); + } + + let authorization = [ + self.authorization_id.as_ref(), + self.authorization_purpose.as_ref(), + self.authorized_release_id.as_ref(), + self.authorized_deployment_id.as_ref(), + self.authorized_by.as_ref(), + self.signature_algorithm.as_ref(), + ]; + let has_authorization = authorization.iter().any(|v| v.is_some()) + || self.authorization_issued_at_unix_millis.is_some() + || self.authorization_expires_at_unix_millis.is_some() + || self.signature.is_some(); + if self.status == "engaged" { + if has_authorization { + bail!("engaged deployment brake must not carry release authorization"); + } + return Ok(()); + } + if authorization.iter().any(|v| v.is_none()) + || self.authorization_issued_at_unix_millis.is_none() + || self.authorization_expires_at_unix_millis.is_none() + || self.signature.is_none() + { + bail!("released deployment brake authorization is incomplete"); + } + for (value, label) in [ + (&self.authorization_id, "authorization id"), + (&self.authorized_release_id, "authorized release id"), + (&self.authorized_deployment_id, "authorized deployment id"), + (&self.authorized_by, "authorizer"), + ] { + identifier(value.as_deref().unwrap(), label)?; + } + let issued = self.authorization_issued_at_unix_millis.unwrap(); + let expires = self.authorization_expires_at_unix_millis.unwrap(); + if self.authorization_purpose.as_deref() != Some(IDUNN_DEPLOYMENT_RELEASE_PURPOSE) + || self.signature_algorithm.as_deref() != Some("ed25519") + || self.signature.as_ref().is_none_or(|v| v.len() != 64) + || issued < self.observed_at_unix_millis + || expires <= issued + || expires - issued > IDUNN_DEPLOYMENT_RELEASE_MAX_LIFETIME_MILLIS + || self + .expires_at_unix_millis + .is_some_and(|brake_expiry| expires > brake_expiry) + { + bail!("deployment release authorization purpose, signature, or lifetime is invalid"); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug)] +pub enum IdunnDeploymentBrakeObservation<'a> { + Missing, + Corrupt, + Present(&'a IdunnDeploymentBrakeRecord), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IdunnDeploymentBrakeDenial { + Missing, + Corrupt, + Foreign, + WrongRuntime, + WrongScope, + Engaged, + Expired, + ReleaseMismatch, + DeploymentMismatch, + InvalidSignature, +} + +fn classify_idunn_deployment_brake( + observation: IdunnDeploymentBrakeObservation<'_>, + runtime_id: &str, + release_id: &str, + deployment_id: &str, + now_unix_millis: u64, +) -> std::result::Result<(), IdunnDeploymentBrakeDenial> { + let record = match observation { + IdunnDeploymentBrakeObservation::Missing => { + return Err(IdunnDeploymentBrakeDenial::Missing); + } + IdunnDeploymentBrakeObservation::Corrupt => { + return Err(IdunnDeploymentBrakeDenial::Corrupt); + } + IdunnDeploymentBrakeObservation::Present(record) => record, + }; + if record.validate().is_err() { + return Err(IdunnDeploymentBrakeDenial::Corrupt); + } + if record.brake_id != IDUNN_DEPLOYMENT_BRAKE_ID + || record.authority != IDUNN_DEPLOYMENT_BRAKE_AUTHORITY + { + return Err(IdunnDeploymentBrakeDenial::Foreign); + } + if record.runtime_id != runtime_id { + return Err(IdunnDeploymentBrakeDenial::WrongRuntime); + } + if !matches!(record.scope.as_str(), "all" | IDUNN_DEPLOYMENT_BRAKE_SCOPE) { + return Err(IdunnDeploymentBrakeDenial::WrongScope); + } + if record.status == "engaged" { + return Err(IdunnDeploymentBrakeDenial::Engaged); + } + if record + .expires_at_unix_millis + .is_some_and(|v| now_unix_millis >= v) + || record + .authorization_expires_at_unix_millis + .is_none_or(|v| now_unix_millis >= v) + || record + .authorization_issued_at_unix_millis + .is_none_or(|v| now_unix_millis < v) + { + return Err(IdunnDeploymentBrakeDenial::Expired); + } + if record.authorized_release_id.as_deref() != Some(release_id) { + return Err(IdunnDeploymentBrakeDenial::ReleaseMismatch); + } + if record.authorized_deployment_id.as_deref() != Some(deployment_id) { + return Err(IdunnDeploymentBrakeDenial::DeploymentMismatch); + } + Ok(()) +} + +pub fn evaluate_idunn_deployment_brake( + observation: IdunnDeploymentBrakeObservation<'_>, + operator_anchor: &ServiceIdentityTrustAnchor, + runtime_id: &str, + release_id: &str, + deployment_id: &str, + now_unix_millis: u64, +) -> std::result::Result<(), IdunnDeploymentBrakeDenial> { + classify_idunn_deployment_brake( + observation, + runtime_id, + release_id, + deployment_id, + now_unix_millis, + )?; + let IdunnDeploymentBrakeObservation::Present(record) = observation else { + unreachable!("successful classification always has a present record") + }; + verify_idunn_deployment_brake_authorization(record, operator_anchor) + .map_err(|_| IdunnDeploymentBrakeDenial::InvalidSignature) +} + +/// Verify the release grant using the dedicated operator public anchor. The +/// signed payload is the complete positional record with the signature field +/// empty, so authority, runtime, target IDs, and both time bounds are covered. +pub fn verify_idunn_deployment_brake_authorization( + record: &IdunnDeploymentBrakeRecord, + anchor: &ServiceIdentityTrustAnchor, +) -> Result<()> { + record.validate()?; + if record.status != "released" { + bail!("engaged deployment brake has no release authorization to verify"); + } + let identity_id = record + .authorized_by + .as_ref() + .ok_or_else(|| anyhow::anyhow!("deployment brake authorizer is absent"))?; + let signature = record + .signature + .as_ref() + .ok_or_else(|| anyhow::anyhow!("deployment brake signature is absent"))?; + let mut unsigned = record.clone(); + unsigned.signature = None; + verify_service_identity_signature::< + IdunnDeploymentBrakeOperatorIdentity, + IdunnDeploymentBrakeReleasePurpose, + >( + anchor, + &rmp_serde::to_vec(&unsigned)?, + &ServiceIdentitySignature { + identity_id: identity_id.clone(), + signature: signature.clone(), + }, + ) +} + +fn identifier(value: &str, label: &str) -> Result<()> { + if value.trim().is_empty() || value.len() > 256 || value.chars().any(char::is_control) { + bail!("{label} is empty, oversized, or contains control characters"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::enroll_service_identity_at; + + fn released() -> IdunnDeploymentBrakeRecord { + IdunnDeploymentBrakeRecord { + schema_version: IDUNN_DEPLOYMENT_BRAKE_SCHEMA.into(), + brake_id: IDUNN_DEPLOYMENT_BRAKE_ID.into(), + authority: IDUNN_DEPLOYMENT_BRAKE_AUTHORITY.into(), + runtime_id: "yggdrasil".into(), + status: "released".into(), + scope: "deployment".into(), + reason: "operator authorized one attempt".into(), + observed_at_unix_millis: 100, + expires_at_unix_millis: Some(1000), + authorization_id: Some("auth/r4".into()), + authorization_purpose: Some(IDUNN_DEPLOYMENT_RELEASE_PURPOSE.into()), + authorized_release_id: Some("release-4".into()), + authorized_deployment_id: Some("deployment-4".into()), + authorized_by: Some("operator/metacrat".into()), + authorization_issued_at_unix_millis: Some(100), + authorization_expires_at_unix_millis: Some(900), + signature_algorithm: Some("ed25519".into()), + signature: Some(vec![7; 64]), + private_state_exposed: false, + updated_by: "operator/metacrat".into(), + } + } + + #[test] + fn only_exact_bounded_release_is_permitted() { + let value = released(); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + "yggdrasil", + "release-4", + "deployment-4", + 500 + ), + Ok(()) + ); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Missing, + "yggdrasil", + "release-4", + "deployment-4", + 500 + ), + Err(IdunnDeploymentBrakeDenial::Missing) + ); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Corrupt, + "yggdrasil", + "release-4", + "deployment-4", + 500 + ), + Err(IdunnDeploymentBrakeDenial::Corrupt) + ); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + "yggdrasil", + "other", + "deployment-4", + 500 + ), + Err(IdunnDeploymentBrakeDenial::ReleaseMismatch) + ); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + "yggdrasil", + "release-4", + "other", + 500 + ), + Err(IdunnDeploymentBrakeDenial::DeploymentMismatch) + ); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + "yggdrasil", + "release-4", + "deployment-4", + 900 + ), + Err(IdunnDeploymentBrakeDenial::Expired) + ); + } + + #[test] + fn hostile_authority_scope_and_shape_substitutions_fail_closed() { + let mut value = released(); + value.authority = "idunn".into(); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + "yggdrasil", + "release-4", + "deployment-4", + 500 + ), + Err(IdunnDeploymentBrakeDenial::Foreign) + ); + let mut value = released(); + value.runtime_id = "nightwing".into(); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + "yggdrasil", + "release-4", + "deployment-4", + 500 + ), + Err(IdunnDeploymentBrakeDenial::WrongRuntime) + ); + let mut value = released(); + value.scope = "persona.public_speech".into(); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + "yggdrasil", + "release-4", + "deployment-4", + 500 + ), + Err(IdunnDeploymentBrakeDenial::WrongScope) + ); + let mut value = released(); + value.signature = Some(vec![0; 63]); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + "yggdrasil", + "release-4", + "deployment-4", + 500 + ), + Err(IdunnDeploymentBrakeDenial::Corrupt) + ); + let mut value = released(); + value.authorization_expires_at_unix_millis = + Some(100 + IDUNN_DEPLOYMENT_RELEASE_MAX_LIFETIME_MILLIS + 1); + assert!(value.validate().is_err()); + } + + #[test] + fn engaged_record_cannot_smuggle_authorization() { + let mut value = released(); + value.status = "engaged".into(); + assert!(value.validate().is_err()); + value.authorization_id = None; + value.authorization_purpose = None; + value.authorized_release_id = None; + value.authorized_deployment_id = None; + value.authorized_by = None; + value.authorization_issued_at_unix_millis = None; + value.authorization_expires_at_unix_millis = None; + value.signature_algorithm = None; + value.signature = None; + value.validate().unwrap(); + assert_eq!( + classify_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + "yggdrasil", + "release-4", + "deployment-4", + 500 + ), + Err(IdunnDeploymentBrakeDenial::Engaged) + ); + } + + #[test] + fn evaluation_requires_the_dedicated_operator_signature() -> Result<()> { + let temp = tempfile::tempdir()?; + let signer = enroll_service_identity_at::( + &temp.path().join("operator.cc"), + )?; + let anchor = signer.trust_anchor()?; + let mut value = released(); + value.authorized_by = Some(anchor.identity_id.clone()); + value.signature = None; + let proof = signer.sign::(&rmp_serde::to_vec(&value)?); + value.signature = Some(proof.signature); + assert_eq!( + evaluate_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + &anchor, + "yggdrasil", + "release-4", + "deployment-4", + 500, + ), + Ok(()) + ); + value.reason = "tampered after authorization".into(); + assert_eq!( + evaluate_idunn_deployment_brake( + IdunnDeploymentBrakeObservation::Present(&value), + &anchor, + "yggdrasil", + "release-4", + "deployment-4", + 500, + ), + Err(IdunnDeploymentBrakeDenial::InvalidSignature) + ); + Ok(()) + } +} diff --git a/packages/cultnet-rs/src/idunn_lifecycle_brake.rs b/packages/cultnet-rs/src/idunn_lifecycle_brake.rs new file mode 100644 index 00000000..86eefa64 --- /dev/null +++ b/packages/cultnet-rs/src/idunn_lifecycle_brake.rs @@ -0,0 +1,325 @@ +use anyhow::{Result, bail}; +use cultcache_rs::DatabaseEntry; + +pub const IDUNN_LIFECYCLE_BRAKE_SCHEMA: &str = "idunn.lifecycle_brake.v1"; +pub const IDUNN_LIFECYCLE_BRAKE_TYPE: &str = "idunn.lifecycle_brake"; +pub const IDUNN_LIFECYCLE_BRAKE_AUTHORITY: &str = "idunn.root"; +pub const IDUNN_LIFECYCLE_BRAKE_SCOPE: &str = "continuity-restart"; + +/// Root-owned, per-target continuity brake. This document has no authority over +/// Idunn startup, deployment, route admission, or any target other than the one +/// named in `target`. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "idunn.lifecycle_brake", schema = "idunn.lifecycle_brake.v1")] +pub struct IdunnLifecycleBrakeRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub authority: String, + #[cultcache(key = 2)] + pub runtime_id: String, + #[cultcache(key = 3)] + pub target: String, + #[cultcache(key = 4)] + pub scope: String, + #[cultcache(key = 5)] + pub status: String, + #[cultcache(key = 6)] + pub reason: String, + #[cultcache(key = 7)] + pub updated_at_unix_millis: u64, + #[cultcache(key = 8)] + pub released_until_unix_millis: Option, +} + +impl IdunnLifecycleBrakeRecord { + pub fn validate(&self) -> Result<()> { + if self.schema_version != IDUNN_LIFECYCLE_BRAKE_SCHEMA { + bail!("lifecycle brake schema is unsupported"); + } + identifier(&self.authority, "authority")?; + identifier(&self.runtime_id, "runtime id")?; + identifier(&self.target, "target")?; + identifier(&self.scope, "scope")?; + identifier(&self.reason, "reason")?; + if !matches!(self.status.as_str(), "engaged" | "released") + || self.updated_at_unix_millis == 0 + { + bail!("lifecycle brake status or update time is invalid"); + } + if self.status == "engaged" && self.released_until_unix_millis.is_some() { + bail!("engaged lifecycle brake cannot carry a release expiry"); + } + if self + .released_until_unix_millis + .is_some_and(|expires| expires <= self.updated_at_unix_millis) + { + bail!("lifecycle brake release expiry is not after its update"); + } + Ok(()) + } + + pub fn canonical_bytes(&self) -> Result> { + self.validate()?; + Ok(rmp_serde::to_vec(self)?) + } + + pub fn decode_canonical(payload: &[u8]) -> Result { + if messagepack_array_len(payload) != Some(9) { + bail!("lifecycle brake is not the 9-field positional contract"); + } + let value: Self = rmp_serde::from_slice(payload)?; + value.validate()?; + if rmp_serde::to_vec(&value)? != payload { + bail!("lifecycle brake encoding is not canonical"); + } + Ok(value) + } +} + +#[derive(Clone, Copy, Debug)] +pub enum IdunnLifecycleBrakeObservation<'a> { + Missing, + Corrupt, + Present(&'a IdunnLifecycleBrakeRecord), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IdunnLifecycleBrakeDenial { + Corrupt, + Foreign, + WrongRuntime, + WrongTarget, + Engaged, + Expired, +} + +/// Decide only whether Idunn may restart one already-admitted target to keep it +/// alive. Absence is the default allow state; a present record must bind the +/// exact Idunn runtime and target and must be explicitly released. +pub fn evaluate_idunn_continuity_restart( + observation: IdunnLifecycleBrakeObservation<'_>, + runtime_id: &str, + target: &str, + now_unix_millis: u64, +) -> std::result::Result<(), IdunnLifecycleBrakeDenial> { + let record = match observation { + IdunnLifecycleBrakeObservation::Missing => return Ok(()), + IdunnLifecycleBrakeObservation::Corrupt => { + return Err(IdunnLifecycleBrakeDenial::Corrupt); + } + IdunnLifecycleBrakeObservation::Present(record) => record, + }; + if record.validate().is_err() { + return Err(IdunnLifecycleBrakeDenial::Corrupt); + } + if record.authority != IDUNN_LIFECYCLE_BRAKE_AUTHORITY + || record.scope != IDUNN_LIFECYCLE_BRAKE_SCOPE + { + return Err(IdunnLifecycleBrakeDenial::Foreign); + } + if record.runtime_id != runtime_id { + return Err(IdunnLifecycleBrakeDenial::WrongRuntime); + } + if record.target != target { + return Err(IdunnLifecycleBrakeDenial::WrongTarget); + } + if record.status == "engaged" { + return Err(IdunnLifecycleBrakeDenial::Engaged); + } + if record + .released_until_unix_millis + .is_some_and(|expires| now_unix_millis >= expires) + { + return Err(IdunnLifecycleBrakeDenial::Expired); + } + Ok(()) +} + +fn identifier(value: &str, label: &str) -> Result<()> { + if value.trim().is_empty() || value.len() > 256 || value.chars().any(char::is_control) { + bail!("{label} is empty, oversized, or contains control characters"); + } + Ok(()) +} + +fn messagepack_array_len(payload: &[u8]) -> Option { + match *payload.first()? { + marker @ 0x90..=0x9f => Some((marker & 0x0f) as usize), + 0xdc if payload.len() >= 3 => Some(u16::from_be_bytes([payload[1], payload[2]]) as usize), + 0xdd if payload.len() >= 5 => { + Some(u32::from_be_bytes([payload[1], payload[2], payload[3], payload[4]]) as usize) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn released() -> IdunnLifecycleBrakeRecord { + IdunnLifecycleBrakeRecord { + schema_version: IDUNN_LIFECYCLE_BRAKE_SCHEMA.into(), + authority: IDUNN_LIFECYCLE_BRAKE_AUTHORITY.into(), + runtime_id: "idunn-yggdrasil".into(), + target: "ghostlight".into(), + scope: IDUNN_LIFECYCLE_BRAKE_SCOPE.into(), + status: "released".into(), + reason: "continuity restart permitted".into(), + updated_at_unix_millis: 100, + released_until_unix_millis: None, + } + } + + fn evaluate( + observation: IdunnLifecycleBrakeObservation<'_>, + target: &str, + now: u64, + ) -> std::result::Result<(), IdunnLifecycleBrakeDenial> { + evaluate_idunn_continuity_restart(observation, "idunn-yggdrasil", target, now) + } + + #[test] + fn lifecycle_brake_round_trips_only_as_the_canonical_positional_contract() -> Result<()> { + let value = released(); + let encoded = value.canonical_bytes()?; + assert_eq!(encoded[0], 0x99); + assert_eq!( + IdunnLifecycleBrakeRecord::decode_canonical(&encoded)?, + value + ); + + let mut noncanonical = vec![0xdc, 0, 9]; + noncanonical.extend_from_slice(&encoded[1..]); + assert!(IdunnLifecycleBrakeRecord::decode_canonical(&noncanonical).is_err()); + + let mut extended = encoded; + extended[0] = 0x9a; + extended.push(0xc0); + assert!(IdunnLifecycleBrakeRecord::decode_canonical(&extended).is_err()); + Ok(()) + } + + #[test] + fn absence_and_explicit_release_allow_only_the_named_continuity_restart() { + assert_eq!( + evaluate(IdunnLifecycleBrakeObservation::Missing, "ghostlight", 500), + Ok(()) + ); + + let mut value = released(); + assert_eq!( + evaluate( + IdunnLifecycleBrakeObservation::Present(&value), + "ghostlight", + 500 + ), + Ok(()) + ); + value.released_until_unix_millis = Some(900); + assert_eq!( + evaluate( + IdunnLifecycleBrakeObservation::Present(&value), + "ghostlight", + 899 + ), + Ok(()) + ); + assert_eq!( + evaluate( + IdunnLifecycleBrakeObservation::Present(&value), + "ghostlight", + 900 + ), + Err(IdunnLifecycleBrakeDenial::Expired) + ); + assert_eq!( + evaluate(IdunnLifecycleBrakeObservation::Missing, "odin", 900), + Ok(()) + ); + assert_eq!( + evaluate(IdunnLifecycleBrakeObservation::Present(&value), "odin", 500), + Err(IdunnLifecycleBrakeDenial::WrongTarget) + ); + } + + #[test] + fn corrupt_foreign_wrong_runtime_and_wrong_target_records_deny() { + assert_eq!( + evaluate(IdunnLifecycleBrakeObservation::Corrupt, "ghostlight", 500), + Err(IdunnLifecycleBrakeDenial::Corrupt) + ); + + let mut value = released(); + value.status = "paused".into(); + assert_eq!( + evaluate( + IdunnLifecycleBrakeObservation::Present(&value), + "ghostlight", + 500 + ), + Err(IdunnLifecycleBrakeDenial::Corrupt) + ); + + let mut value = released(); + value.authority = "service-owned".into(); + assert_eq!( + evaluate( + IdunnLifecycleBrakeObservation::Present(&value), + "ghostlight", + 500 + ), + Err(IdunnLifecycleBrakeDenial::Foreign) + ); + + let mut value = released(); + value.scope = "deployment".into(); + assert_eq!( + evaluate( + IdunnLifecycleBrakeObservation::Present(&value), + "ghostlight", + 500 + ), + Err(IdunnLifecycleBrakeDenial::Foreign) + ); + + let value = released(); + assert_eq!( + evaluate_idunn_continuity_restart( + IdunnLifecycleBrakeObservation::Present(&value), + "idunn-nightwing", + "ghostlight", + 500 + ), + Err(IdunnLifecycleBrakeDenial::WrongRuntime) + ); + assert_eq!( + evaluate(IdunnLifecycleBrakeObservation::Present(&value), "odin", 500), + Err(IdunnLifecycleBrakeDenial::WrongTarget) + ); + } + + #[test] + fn engaged_always_denies_and_cannot_smuggle_a_release_expiry() { + let mut value = released(); + value.status = "engaged".into(); + assert_eq!( + evaluate( + IdunnLifecycleBrakeObservation::Present(&value), + "ghostlight", + 500 + ), + Err(IdunnLifecycleBrakeDenial::Engaged) + ); + value.released_until_unix_millis = Some(900); + assert_eq!( + evaluate( + IdunnLifecycleBrakeObservation::Present(&value), + "ghostlight", + 500 + ), + Err(IdunnLifecycleBrakeDenial::Corrupt) + ); + } +} diff --git a/packages/cultnet-rs/src/lib.rs b/packages/cultnet-rs/src/lib.rs index 6fb1d38d..3e8a3c94 100644 --- a/packages/cultnet-rs/src/lib.rs +++ b/packages/cultnet-rs/src/lib.rs @@ -1,4 +1,10 @@ mod contracts; +mod idunn_deployment_brake; +mod idunn_lifecycle_brake; +mod provider_health_contracts; +mod runtime_authority_contracts; +mod service_identity; +mod snapshot_query; mod cultmesh; mod framing; mod operation_service; @@ -11,6 +17,12 @@ mod shard_catalog; mod transport; pub use contracts::*; +pub use idunn_deployment_brake::*; +pub use idunn_lifecycle_brake::*; +pub use provider_health_contracts::*; +pub use runtime_authority_contracts::*; +pub use service_identity::*; +pub use snapshot_query::*; pub use cultmesh::*; pub use framing::*; pub use operation_service::*; diff --git a/packages/cultnet-rs/src/provider_health_contracts.rs b/packages/cultnet-rs/src/provider_health_contracts.rs new file mode 100644 index 00000000..5ca320f0 --- /dev/null +++ b/packages/cultnet-rs/src/provider_health_contracts.rs @@ -0,0 +1,653 @@ +use anyhow::{Context, Result, anyhow, bail}; +use cultcache_rs::DatabaseEntry; +use serde::{Deserialize, Serialize}; + +use crate::runtime_authority_contracts::{ + GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE, + ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA, ODIN_RUNTIME_TOPOLOGY_CORRELATION_SIGNING_PURPOSE, +}; +use crate::{ + GameCultProviderHealthIdentity, IdunnServiceIdentity, OdinTopologyIdentity, + derive_service_identity_id, +}; + +pub const GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA: &str = "gamecult.service_trust_anchor.v1"; +pub const IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA: &str = + "idunn.authenticated_provider_health_projection.v1"; +pub const IDUNN_SIGNED_DAEMON_HEALTH_SCHEMA: &str = "idunn.signed_daemon_health.v1"; +pub const IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE: &str = + "idunn.authenticated-provider-health-projection.v1"; +pub const IDUNN_PROVIDER_ACTIVE_REASON: &str = "authenticated_provider_active"; +pub const IDUNN_PROVIDER_WARMING_REASON: &str = "authenticated_provider_warming"; +pub const IDUNN_PROVIDER_DEGRADED_REASON: &str = "authenticated_provider_degraded"; +pub const IDUNN_PROVIDER_FAILED_REASON: &str = "authenticated_provider_failed"; + +/// Provider-owned health statement. Ingress verifies `signature` over the +/// complete positional record with this field empty before admitting it. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.signed_daemon_health", + schema = "idunn.signed_daemon_health.v1" +)] +pub struct IdunnSignedDaemonHealthRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub daemon_id: String, + #[cultcache(key = 2)] + pub health_contract: String, + #[cultcache(key = 3)] + pub source_runtime_id: String, + #[cultcache(key = 4)] + pub state: String, + #[cultcache(key = 5)] + pub detail: String, + #[cultcache(key = 6)] + pub signer_identity_id: String, + #[cultcache(key = 7)] + pub publisher_incarnation_id: String, + #[cultcache(key = 8)] + pub publisher_sequence: u64, + #[cultcache(key = 9)] + pub observed_at_unix_millis: u64, + #[cultcache(key = 10)] + pub release_id: Option, + #[cultcache(key = 11)] + pub release_witness_sha256: Option, + #[cultcache(key = 12)] + pub source_commit: Option, + #[cultcache(key = 13)] + pub deployment_id: Option, + #[cultcache(key = 14)] + pub signature_algorithm: String, + #[cultcache(key = 15, bytes)] + pub signature: Vec, + #[cultcache(key = 16)] + pub private_state_exposed: bool, + #[cultcache(key = 17, default)] + pub activation_witness_sha256: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct LegacyIdunnSignedDaemonHealthWire { + schema_version: String, + daemon_id: String, + health_contract: String, + source_runtime_id: String, + state: String, + detail: String, + signer_identity_id: String, + publisher_incarnation_id: String, + publisher_sequence: u64, + observed_at_unix_millis: u64, + release_id: Option, + release_witness_sha256: Option, + source_commit: Option, + deployment_id: Option, + signature_algorithm: String, + #[serde(with = "serde_bytes")] + signature: Vec, + private_state_exposed: bool, +} + +impl From for IdunnSignedDaemonHealthRecord { + fn from(value: LegacyIdunnSignedDaemonHealthWire) -> Self { + Self { + schema_version: value.schema_version, + daemon_id: value.daemon_id, + health_contract: value.health_contract, + source_runtime_id: value.source_runtime_id, + state: value.state, + detail: value.detail, + signer_identity_id: value.signer_identity_id, + publisher_incarnation_id: value.publisher_incarnation_id, + publisher_sequence: value.publisher_sequence, + observed_at_unix_millis: value.observed_at_unix_millis, + release_id: value.release_id, + release_witness_sha256: value.release_witness_sha256, + source_commit: value.source_commit, + deployment_id: value.deployment_id, + signature_algorithm: value.signature_algorithm, + signature: value.signature, + private_state_exposed: value.private_state_exposed, + activation_witness_sha256: None, + } + } +} + +impl IdunnSignedDaemonHealthRecord { + /// Decode the canonical current or pre-activation positional wire and + /// return the exact wire generation's unsigned signature payload. + pub fn decode_canonical_signed_payload(payload: &[u8]) -> Result<(Self, Vec)> { + match messagepack_array_len(payload) { + Some(18) => { + let statement: Self = rmp_serde::from_slice(payload) + .context("decoding generic signed daemon health")?; + if rmp_serde::to_vec(&statement)? != payload { + bail!("signed daemon health payload is not canonical positional MessagePack"); + } + let mut unsigned = statement.clone(); + unsigned.signature.clear(); + Ok((statement, rmp_serde::to_vec(&unsigned)?)) + } + Some(17) => { + let legacy: LegacyIdunnSignedDaemonHealthWire = rmp_serde::from_slice(payload) + .context("decoding legacy generic signed daemon health")?; + if rmp_serde::to_vec(&legacy)? != payload { + bail!("signed daemon health payload is not canonical positional MessagePack"); + } + let mut unsigned = legacy.clone(); + unsigned.signature.clear(); + let unsigned_payload = rmp_serde::to_vec(&unsigned)?; + Ok((legacy.into(), unsigned_payload)) + } + _ => bail!("signed daemon health payload is not canonical positional MessagePack"), + } + } + + pub fn validate(&self) -> Result<()> { + if self.schema_version != IDUNN_SIGNED_DAEMON_HEALTH_SCHEMA { + bail!("signed daemon health schema is unsupported"); + } + validate_identifier(&self.daemon_id, "daemon id")?; + validate_identifier(&self.health_contract, "health contract")?; + validate_identifier(&self.source_runtime_id, "source runtime id")?; + validate_identifier(&self.signer_identity_id, "signer identity id")?; + validate_identifier(&self.publisher_incarnation_id, "publisher incarnation id")?; + if !matches!( + self.state.as_str(), + "active" | "warming" | "degraded" | "failed" + ) || self.detail.len() > 512 + || self.signature_algorithm != "ed25519" + || self.signature.len() != 64 + || self.publisher_sequence == 0 + || self.observed_at_unix_millis == 0 + { + bail!("signed daemon health shape is invalid"); + } + validate_optional_release_binding( + &self.release_id, + &self.release_witness_sha256, + &self.source_commit, + )?; + validate_optional_identifier(&self.deployment_id, "deployment id")?; + validate_optional_sha256(&self.activation_witness_sha256, "activation witness sha256")?; + if self.private_state_exposed { + bail!("signed daemon health exposes private state"); + } + Ok(()) + } +} + +fn messagepack_array_len(payload: &[u8]) -> Option { + match *payload.first()? { + marker @ 0x90..=0x9f => Some(usize::from(marker & 0x0f)), + 0xdc => Some(usize::from(u16::from_be_bytes([ + *payload.get(1)?, + *payload.get(2)?, + ]))), + 0xdd => usize::try_from(u32::from_be_bytes([ + *payload.get(1)?, + *payload.get(2)?, + *payload.get(3)?, + *payload.get(4)?, + ])) + .ok(), + _ => None, + } +} + +/// Root-distributed public key binding for one service-owned signed contract. +/// Consumers pin this document; a self-declared key inside a signed projection +/// is never authority. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.service_trust_anchor", + schema = "gamecult.service_trust_anchor.v1" +)] +pub struct GameCultServiceTrustAnchorRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub trust_anchor_id: String, + #[cultcache(key = 2)] + pub service_id: String, + #[cultcache(key = 3)] + pub runtime_id: String, + #[cultcache(key = 4)] + pub signer_identity_id: String, + #[cultcache(key = 5)] + pub signer_public_key: Vec, + #[cultcache(key = 6)] + pub signature_algorithm: String, + #[cultcache(key = 7)] + pub signing_purpose: String, + #[cultcache(key = 8)] + pub signed_schema: String, + #[cultcache(key = 9)] + pub binding_authority: String, + #[cultcache(key = 10)] + pub bound_at_unix_millis: u64, + #[cultcache(key = 11)] + pub expires_at_unix_millis: Option, + #[cultcache(key = 12)] + pub private_state_exposed: bool, +} + +impl GameCultServiceTrustAnchorRecord { + pub fn validate(&self) -> Result<()> { + if self.schema_version != GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA { + bail!("service trust anchor schema is unsupported"); + } + validate_identifier(&self.trust_anchor_id, "trust anchor id")?; + validate_identifier(&self.service_id, "service id")?; + validate_identifier(&self.runtime_id, "runtime id")?; + validate_identifier(&self.signer_identity_id, "signer identity id")?; + validate_identifier(&self.signing_purpose, "signing purpose")?; + validate_identifier(&self.signed_schema, "signed schema")?; + if self.signer_public_key.len() != 32 + || self.signature_algorithm != "ed25519" + || self.binding_authority != "root" + || self.bound_at_unix_millis == 0 + || self + .expires_at_unix_millis + .is_some_and(|expires_at| expires_at <= self.bound_at_unix_millis) + || self.private_state_exposed + { + bail!("service trust anchor authority, key, lifetime, or privacy is invalid"); + } + if self.signed_schema == IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA + && (self.service_id != "idunn" + || self.signing_purpose + != IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE + || self.signer_identity_id + != derive_service_identity_id::(&self.signer_public_key)?) + { + bail!("Idunn provider-health trust anchor profile is invalid"); + } + let is_runtime_presence_profile = self + .signed_schema + .starts_with("gamecult.runtime_presence_health.") + || self + .signing_purpose + .starts_with("gamecult.runtime_presence_health."); + if is_runtime_presence_profile + && (self.signed_schema != GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA + || self.signing_purpose != GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE + || self.signer_identity_id + != derive_service_identity_id::( + &self.signer_public_key, + )?) + { + bail!("runtime presence trust anchor profile is invalid"); + } + if (self.signed_schema == ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA + || self.signing_purpose == ODIN_RUNTIME_TOPOLOGY_CORRELATION_SIGNING_PURPOSE) + && (self.signed_schema != ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA + || self.signing_purpose != ODIN_RUNTIME_TOPOLOGY_CORRELATION_SIGNING_PURPOSE + || self.service_id != "odin" + || self.signer_identity_id + != derive_service_identity_id::(&self.signer_public_key)?) + { + bail!("Odin topology correlation trust anchor profile is invalid"); + } + Ok(()) + } +} + +/// Idunn-owned public projection of one current authenticated generic provider +/// admission. Absence and dependency failure produce no record; they are not +/// provider states Idunn may manufacture. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.authenticated_provider_health_projection", + schema = "idunn.authenticated_provider_health_projection.v1" +)] +pub struct IdunnAuthenticatedProviderHealthProjectionRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub projection_id: String, + #[cultcache(key = 2)] + pub daemon_id: String, + #[cultcache(key = 3)] + pub health_contract: String, + #[cultcache(key = 4)] + pub provider_state: String, + #[cultcache(key = 5)] + pub reason_code: String, + #[cultcache(key = 6)] + pub provider_observed_at_unix_millis: u64, + #[cultcache(key = 7)] + pub admitted_at_unix_millis: u64, + #[cultcache(key = 8)] + pub evaluated_at_unix_millis: u64, + #[cultcache(key = 9)] + pub trust_binding_id: String, + #[cultcache(key = 10)] + pub trust_binding_sha256: String, + #[cultcache(key = 11)] + pub signed_health_sha256: String, + #[cultcache(key = 12)] + pub authenticated_admission_sha256: String, + #[cultcache(key = 13)] + pub provider_signer_identity_id: String, + #[cultcache(key = 14)] + pub provider_incarnation_id: String, + #[cultcache(key = 15)] + pub provider_sequence: u64, + #[cultcache(key = 16)] + pub release_id: Option, + #[cultcache(key = 17)] + pub release_witness_sha256: Option, + #[cultcache(key = 18)] + pub source_commit: Option, + #[cultcache(key = 19)] + pub deployment_id: Option, + #[cultcache(key = 20)] + pub idunn_runtime_id: String, + #[cultcache(key = 21)] + pub idunn_signer_identity_id: String, + #[cultcache(key = 22)] + pub projection_incarnation_id: String, + #[cultcache(key = 23)] + pub projection_sequence: u64, + #[cultcache(key = 24)] + pub signature_algorithm: String, + #[cultcache(key = 25)] + pub signature: Vec, + #[cultcache(key = 26)] + pub private_state_exposed: bool, + #[cultcache(key = 27)] + pub expires_at_unix_millis: u64, +} + +/// Closed derivation for an authenticated provider state. `None` means no +/// provider-health projection may be published. +pub fn authenticated_provider_health_reason_code(state: &str) -> Option<&'static str> { + match state { + "active" => Some(IDUNN_PROVIDER_ACTIVE_REASON), + "warming" => Some(IDUNN_PROVIDER_WARMING_REASON), + "degraded" => Some(IDUNN_PROVIDER_DEGRADED_REASON), + "failed" => Some(IDUNN_PROVIDER_FAILED_REASON), + _ => None, + } +} + +impl IdunnAuthenticatedProviderHealthProjectionRecord { + pub fn validate(&self) -> Result<()> { + if self.schema_version != IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA { + bail!("authenticated provider health projection schema is unsupported"); + } + validate_identifier(&self.projection_id, "projection id")?; + validate_identifier(&self.daemon_id, "daemon id")?; + validate_identifier(&self.health_contract, "health contract")?; + validate_identifier(&self.trust_binding_id, "trust binding id")?; + validate_identifier( + &self.provider_signer_identity_id, + "provider signer identity id", + )?; + validate_identifier(&self.provider_incarnation_id, "provider incarnation id")?; + validate_identifier(&self.idunn_runtime_id, "Idunn runtime id")?; + validate_identifier(&self.idunn_signer_identity_id, "Idunn signer identity id")?; + validate_identifier(&self.projection_incarnation_id, "projection incarnation id")?; + let reason_is_valid = authenticated_provider_health_reason_code(&self.provider_state) + .is_some_and(|reason| reason == self.reason_code); + if !reason_is_valid + || self.provider_observed_at_unix_millis == 0 + || self.admitted_at_unix_millis < self.provider_observed_at_unix_millis + || self.evaluated_at_unix_millis < self.admitted_at_unix_millis + || self.expires_at_unix_millis <= self.evaluated_at_unix_millis + || self.provider_sequence == 0 + || self.projection_sequence == 0 + || !is_sha256(&self.trust_binding_sha256) + || !is_sha256(&self.signed_health_sha256) + || !is_sha256(&self.authenticated_admission_sha256) + || self.signature_algorithm != "ed25519" + || self.signature.len() != 64 + || self.private_state_exposed + { + bail!( + "authenticated provider health projection shape, lineage, reason, signature, or privacy is invalid" + ); + } + validate_optional_release_binding( + &self.release_id, + &self.release_witness_sha256, + &self.source_commit, + )?; + validate_optional_identifier(&self.deployment_id, "deployment id")?; + if self.deployment_id.is_some() != self.release_id.is_some() { + bail!("authenticated provider health projection release lineage is partial"); + } + Ok(()) + } +} + +fn validate_identifier(value: &str, label: &str) -> Result<()> { + if value.trim().is_empty() || value.len() > 256 || value.chars().any(char::is_control) { + bail!("{label} is empty, oversized, or contains control characters"); + } + Ok(()) +} + +fn validate_optional_identifier(value: &Option, label: &str) -> Result<()> { + if let Some(value) = value { + validate_identifier(value, label)?; + } + Ok(()) +} + +fn validate_optional_sha256(value: &Option, label: &str) -> Result<()> { + if value.as_deref().is_some_and(|value| !is_sha256(value)) { + bail!("{label} is malformed"); + } + Ok(()) +} + +fn validate_optional_release_binding( + release_id: &Option, + witness: &Option, + source_commit: &Option, +) -> Result<()> { + if release_id.is_some() || witness.is_some() || source_commit.is_some() { + validate_optional_identifier(release_id, "release id")?; + let witness = witness + .as_deref() + .ok_or_else(|| anyhow!("release witness is absent"))?; + let commit = source_commit + .as_deref() + .ok_or_else(|| anyhow!("source commit is absent"))?; + if release_id.is_none() || !is_sha256(witness) || !is_lower_hex(commit, 40) { + bail!("release binding is incomplete or malformed"); + } + } + Ok(()) +} + +fn is_sha256(value: &str) -> bool { + value + .strip_prefix("sha256-") + .is_some_and(|digest| is_lower_hex(digest, 64)) +} + +fn is_lower_hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn signed_health() -> IdunnSignedDaemonHealthRecord { + IdunnSignedDaemonHealthRecord { + schema_version: IDUNN_SIGNED_DAEMON_HEALTH_SCHEMA.into(), + daemon_id: "epiphany".into(), + health_contract: "epiphany.cultnet-rudp-runtime-health".into(), + source_runtime_id: "epiphany-yggdrasil".into(), + state: "active".into(), + detail: "managed-services-current".into(), + signer_identity_id: "provider-signing-key".into(), + publisher_incarnation_id: "9c2cba2e-c2de-4750-b222-b732f97d0435".into(), + publisher_sequence: 1, + observed_at_unix_millis: 100, + release_id: Some("release-1".into()), + release_witness_sha256: Some(format!("sha256-{}", "d".repeat(64))), + source_commit: Some("e".repeat(40)), + deployment_id: Some("deployment-1".into()), + signature_algorithm: "ed25519".into(), + signature: vec![6; 64], + private_state_exposed: false, + activation_witness_sha256: Some(format!("sha256-{}", "f".repeat(64))), + } + } + + fn anchor() -> GameCultServiceTrustAnchorRecord { + let public_key = vec![5; 32]; + GameCultServiceTrustAnchorRecord { + schema_version: GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(), + trust_anchor_id: "root/idunn/provider-health".into(), + service_id: "idunn".into(), + runtime_id: "idunn-yggdrasil".into(), + signer_identity_id: derive_service_identity_id::(&public_key) + .unwrap(), + signer_public_key: public_key, + signature_algorithm: "ed25519".into(), + signing_purpose: IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE.into(), + signed_schema: IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA.into(), + binding_authority: "root".into(), + bound_at_unix_millis: 100, + expires_at_unix_millis: Some(200), + private_state_exposed: false, + } + } + + fn projection() -> IdunnAuthenticatedProviderHealthProjectionRecord { + IdunnAuthenticatedProviderHealthProjectionRecord { + schema_version: IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA.into(), + projection_id: "authenticated-provider-health:epiphany".into(), + daemon_id: "epiphany".into(), + health_contract: "health.v1".into(), + provider_state: "active".into(), + reason_code: IDUNN_PROVIDER_ACTIVE_REASON.into(), + provider_observed_at_unix_millis: 100, + admitted_at_unix_millis: 101, + evaluated_at_unix_millis: 102, + trust_binding_id: "root/epiphany".into(), + trust_binding_sha256: format!("sha256-{}", "a".repeat(64)), + signed_health_sha256: format!("sha256-{}", "b".repeat(64)), + authenticated_admission_sha256: format!("sha256-{}", "c".repeat(64)), + provider_signer_identity_id: "provider-signing-key".into(), + provider_incarnation_id: "provider/boot/1".into(), + provider_sequence: 1, + release_id: Some("release-1".into()), + release_witness_sha256: Some(format!("sha256-{}", "d".repeat(64))), + source_commit: Some("e".repeat(40)), + deployment_id: Some("deployment-1".into()), + idunn_runtime_id: "idunn-yggdrasil".into(), + idunn_signer_identity_id: "idunn-signing-key".into(), + projection_incarnation_id: "idunn/boot/1".into(), + projection_sequence: 1, + signature_algorithm: "ed25519".into(), + signature: vec![6; 64], + private_state_exposed: false, + expires_at_unix_millis: 200, + } + } + + #[test] + fn contracts_accept_exact_root_and_lineage_shapes() -> Result<()> { + let anchor = anchor(); + let projection = projection(); + let health = signed_health(); + anchor.validate()?; + projection.validate()?; + health.validate()?; + let encoded = rmp_serde::to_vec(&health)?; + assert_eq!(encoded.first().copied(), Some(0xdc)); + assert_eq!(&encoded[1..3], &[0, 18]); + assert!( + encoded + .windows(4) + .any(|window| window == [0xc4, 0x40, 6, 6]), + "provider signature must use the portable MessagePack binary shape" + ); + assert_eq!( + rmp_serde::from_slice::(&encoded)?, + health + ); + assert_eq!( + rmp_serde::from_slice::(&rmp_serde::to_vec( + &anchor + )?)?, + anchor + ); + assert_eq!( + rmp_serde::from_slice::( + &rmp_serde::to_vec(&projection)? + )?, + projection + ); + assert_eq!(authenticated_provider_health_reason_code("missing"), None); + Ok(()) + } + + #[test] + fn activation_binding_is_additive_for_legacy_generic_health_records() -> Result<()> { + let mut health = signed_health(); + health.activation_witness_sha256 = None; + let mut legacy = rmp_serde::to_vec(&health)?; + assert_eq!(&legacy[..3], &[0xdc, 0, 18]); + assert_eq!(legacy.pop(), Some(0xc0)); + legacy[2] = 17; + let decoded: IdunnSignedDaemonHealthRecord = rmp_serde::from_slice(&legacy)?; + assert_eq!(decoded.activation_witness_sha256, None); + decoded.validate()?; + let (decoded, unsigned) = + IdunnSignedDaemonHealthRecord::decode_canonical_signed_payload(&legacy)?; + assert_eq!(decoded.activation_witness_sha256, None); + assert_eq!(&unsigned[..3], &[0xdc, 0, 17]); + Ok(()) + } + + #[test] + fn contracts_refuse_substitution_and_manufactured_states() { + let mut value = anchor(); + value.binding_authority = "idunn".into(); + assert!(value.validate().is_err()); + let mut value = anchor(); + value.signer_identity_id = "caller-selected".into(); + assert!(value.validate().is_err()); + let mut value = projection(); + value.reason_code = "release_drift".into(); + assert!(value.validate().is_err()); + let mut value = projection(); + value.provider_state = "missing".into(); + assert!(value.validate().is_err()); + let mut value = projection(); + value.deployment_id = None; + assert!(value.validate().is_err()); + let mut value = projection(); + value.signature.clear(); + assert!(value.validate().is_err()); + let mut value = projection(); + value.signed_health_sha256 = format!("sha256-{}", "A".repeat(64)); + assert!(value.validate().is_err()); + let mut value = signed_health(); + value.publisher_sequence = 0; + assert!(value.validate().is_err()); + let mut value = signed_health(); + value.activation_witness_sha256 = Some(format!("sha256-{}", "F".repeat(64))); + assert!(value.validate().is_err()); + let mut value = signed_health(); + value.release_witness_sha256 = None; + assert!(value.validate().is_err()); + let mut value = signed_health(); + value.private_state_exposed = true; + assert!(value.validate().is_err()); + } +} diff --git a/packages/cultnet-rs/src/runtime_authority_contracts.rs b/packages/cultnet-rs/src/runtime_authority_contracts.rs new file mode 100644 index 00000000..426be1fb --- /dev/null +++ b/packages/cultnet-rs/src/runtime_authority_contracts.rs @@ -0,0 +1,3309 @@ +use anyhow::{Context, Result, bail, ensure}; +use cultcache_rs::DatabaseEntry; +use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +use rand::RngCore; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::io::{Read, Write}; +use zeroize::Zeroizing; + +pub const GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA: &str = "gamecult.runtime_presence_health.v2"; +pub const GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE: &str = + "gamecult.runtime_presence_health.v2"; +pub const GAMECULT_RUNTIME_ACTIVATION_PROOF_SIGNING_PURPOSE: &str = + "gamecult.runtime_presence.activation-proof.v1"; +pub const IDUNN_RUNTIME_ACTIVATION_SCHEMA: &str = "idunn.runtime_activation.v2"; +pub const IDUNN_RUNTIME_ACTIVATION_SIGNING_PURPOSE: &str = "idunn.runtime_activation.v2"; +pub const IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME: &str = "gamecult-idunn-runtime-activation-key"; +pub const IDUNN_PROCESS_WRITE_LEASE_SCHEMA: &str = "idunn.process_write_lease.v1"; +pub const IDUNN_EXPECTED_INCARNATION_SCHEMA: &str = "idunn.expected_incarnation.v2"; +pub const ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA: &str = "odin.runtime_topology_correlation.v2"; +pub const ODIN_RUNTIME_TOPOLOGY_CORRELATION_SIGNING_PURPOSE: &str = + "odin.runtime_topology_correlation.v2"; + +const MAX_RUNTIME_CAPABILITIES: usize = 256; +const MAX_RUNTIME_DEPENDENCIES: usize = 256; +const MAX_TOPOLOGY_DISAGREEMENTS: usize = 256; +const IDUNN_RUNTIME_ACTIVATION_ID_DOMAIN: &[u8] = b"idunn.runtime-activation.id.v1\0"; +const IDUNN_RUNTIME_ACTIVATION_SIGNATURE_DOMAIN: &[u8] = b"idunn.runtime-activation.signature.v1\0"; + +/// One provider-owned capability claim inside a runtime-presence statement. +/// The enclosing vector is canonical only when these records are strictly +/// increasing by `(capability, schema, compatibility)`. Capacity describes +/// that one claim and does not create a second identity for the same claim. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GameCultRuntimeCapability { + pub capability: String, + pub schema: String, + pub compatibility: String, + pub capacity: u32, +} + +impl GameCultRuntimeCapability { + fn identity(&self) -> (&str, &str, &str) { + (&self.capability, &self.schema, &self.compatibility) + } +} + +/// Idunn's admitted requirement for one provider-owned runtime capability. +/// The provider reports actual capacity in `GameCultRuntimeCapability`; this +/// record states only the minimum needed for this incarnation to be Ready. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct IdunnExpectedCapability { + pub capability: String, + pub schema: String, + pub compatibility: String, + pub minimum_capacity: u32, +} + +impl IdunnExpectedCapability { + fn identity(&self) -> (&str, &str, &str) { + (&self.capability, &self.schema, &self.compatibility) + } +} + +/// Dual-proved claim from one exact runtime launch. The stable provider key and +/// Idunn's activation-scoped ephemeral key both sign `canonical_proof_payload`: +/// the canonical positional encoding of this complete record with both proof +/// byte fields empty. Present authority requires a matching Idunn-published +/// current activation; neither proof can establish admission by itself. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.runtime_presence_health", + schema = "gamecult.runtime_presence_health.v2" +)] +pub struct GameCultRuntimePresenceHealthRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub target: String, + #[cultcache(key = 2)] + pub expected_projection_sha256: String, + #[cultcache(key = 3)] + pub plan_id: String, + #[cultcache(key = 4)] + pub incarnation_id: String, + #[cultcache(key = 5)] + pub sealed_release_id: String, + #[cultcache(key = 6)] + pub activation_witness_sha256: String, + #[cultcache(key = 7)] + pub state_schema_generation: Option, + #[cultcache(key = 8)] + pub state_contract_sha256: Option, + #[cultcache(key = 9)] + pub runtime_id: String, + #[cultcache(key = 10)] + pub runtime_instance_id: String, + #[cultcache(key = 11)] + pub bound_endpoint: Option, + #[cultcache(key = 12)] + pub capabilities: Vec, + #[cultcache(key = 13)] + pub health_contract: String, + #[cultcache(key = 14)] + pub state: String, + #[cultcache(key = 15)] + pub detail: String, + #[cultcache(key = 16)] + pub write_lease_sha256: Option, + #[cultcache(key = 17)] + pub signer_identity_id: String, + #[cultcache(key = 18)] + pub publisher_sequence: u64, + #[cultcache(key = 19)] + pub observed_at_unix_millis: u64, + #[cultcache(key = 20)] + pub signature_algorithm: String, + #[cultcache(key = 21, bytes)] + pub signature: Vec, + #[cultcache(key = 22)] + pub activation_signer_identity_id: String, + #[cultcache(key = 23, bytes)] + pub activation_signature: Vec, +} + +impl GameCultRuntimePresenceHealthRecord { + /// Return the one canonical payload covered by both the stable provider + /// signature and the activation-scoped proof. Both signature fields are + /// empty in these bytes, avoiding circular signatures while binding every + /// authority-bearing statement field and both signer identities. + pub fn canonical_proof_payload(&self) -> Result> { + self.validate_shape(true)?; + let mut unsigned = self.clone(); + unsigned.signature.clear(); + unsigned.activation_signature.clear(); + Ok(rmp_serde::to_vec(&unsigned)?) + } + + /// Digest the complete signed presence record for an Odin correlation + /// receipt. An unsigned construction value is deliberately not digestible. + pub fn canonical_sha256(&self) -> Result { + self.validate()?; + Ok(prefixed_sha256(&rmp_serde::to_vec(self)?)) + } + + pub fn validate(&self) -> Result<()> { + self.validate_shape(false) + } + + fn validate_shape(&self, allow_unsigned: bool) -> Result<()> { + if self.schema_version != GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA { + bail!("runtime presence schema is unsupported"); + } + validate_authority_identifier(&self.target, "target")?; + validate_required_sha256( + &self.expected_projection_sha256, + "expected projection sha256", + )?; + validate_required_sha256(&self.plan_id, "plan id")?; + validate_authority_identifier(&self.incarnation_id, "incarnation id")?; + validate_required_sha256(&self.sealed_release_id, "sealed release id")?; + validate_required_sha256(&self.activation_witness_sha256, "activation witness sha256")?; + match (&self.state_schema_generation, &self.state_contract_sha256) { + (Some(generation), Some(contract_sha256)) => { + validate_authority_identifier(generation, "state schema generation")?; + validate_required_sha256(contract_sha256, "state contract sha256")?; + } + (None, None) => {} + _ => bail!("runtime presence state lineage is partial"), + } + validate_authority_identifier(&self.runtime_id, "runtime id")?; + validate_required_sha256(&self.runtime_instance_id, "runtime instance id")?; + validate_optional_endpoint(&self.bound_endpoint)?; + validate_runtime_capabilities(&self.capabilities)?; + validate_authority_identifier(&self.health_contract, "health contract")?; + validate_authority_identifier(&self.signer_identity_id, "signer identity id")?; + validate_authority_identifier( + &self.activation_signer_identity_id, + "activation signer identity id", + )?; + validate_optional_sha256(&self.write_lease_sha256, "write lease sha256")?; + + let signature_is_valid = + self.signature.len() == 64 || (allow_unsigned && self.signature.is_empty()); + let activation_signature_is_valid = self.activation_signature.len() == 64 + || (allow_unsigned && self.activation_signature.is_empty()); + if self.publisher_sequence == 0 + || self.observed_at_unix_millis == 0 + || !matches!( + self.state.as_str(), + "warming" | "active" | "degraded" | "failed" + ) + || self.detail.len() > 512 + || self.detail.chars().any(char::is_control) + || self.signature_algorithm != "ed25519" + || !signature_is_valid + || !activation_signature_is_valid + { + bail!("runtime presence state, sequence, detail, or signature is invalid"); + } + if self.state == "warming" && self.write_lease_sha256.is_some() { + bail!("warming runtime presence cannot claim a process write lease"); + } + if self.state_schema_generation.is_none() && self.write_lease_sha256.is_some() { + bail!("stateless runtime presence cannot claim a process write lease"); + } + Ok(()) + } +} + +/// Public route facts admitted for one incarnation. These are service-facing +/// endpoints only; actuator paths, unit files, container sockets, and runner +/// credentials do not belong in the Expected projection. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct IdunnExpectedRoute { + pub route_id: String, + pub transport: String, + pub stable_endpoint: String, + pub candidate_endpoint: String, +} + +impl IdunnExpectedRoute { + fn validate(&self) -> Result<()> { + validate_authority_identifier(&self.route_id, "route id")?; + validate_endpoint(&self.stable_endpoint, "stable route endpoint")?; + validate_endpoint(&self.candidate_endpoint, "candidate route endpoint")?; + if self.stable_endpoint == self.candidate_endpoint { + bail!("stable and candidate route endpoints are identical"); + } + match self.transport.as_str() { + "http" => { + if !(self.stable_endpoint.starts_with("http://") + || self.stable_endpoint.starts_with("https://")) + || !self.candidate_endpoint.starts_with("http://") + { + bail!("HTTP route endpoints use an unsupported scheme"); + } + } + "tcp" => { + if !self.stable_endpoint.starts_with("tcp://") + || !self.candidate_endpoint.starts_with("tcp://") + { + bail!("TCP route endpoints use an unsupported scheme"); + } + } + "rudp" => { + if !self.stable_endpoint.starts_with("rudp://") + || !self.candidate_endpoint.starts_with("rudp://") + { + bail!("RUDP route endpoints use an unsupported scheme"); + } + } + _ => bail!("route transport is unsupported"), + } + Ok(()) + } +} + +/// One capability requirement and Idunn's exact admitted provider selection. +/// Provider fields are all absent while unresolved. Managed providers bind an +/// Expected digest; external operator bindings instead bind an endpoint. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct IdunnExpectedDependency { + pub kind: String, + pub capability: String, + pub schema: String, + pub compatibility: String, + pub minimum_capacity: u32, + pub startup: String, + pub provider_id: Option, + pub provider_authority: Option, + pub provider_expected_projection_sha256: Option, + pub provider_endpoint: Option, +} + +impl IdunnExpectedDependency { + fn identity(&self) -> (&str, &str, &str) { + (&self.capability, &self.schema, &self.compatibility) + } + + fn validate(&self) -> Result<()> { + if !matches!( + self.kind.as_str(), + "bootstrap" + | "required" + | "optional" + | "shared-infrastructure" + | "private" + | "external-operator-binding" + ) { + bail!("dependency kind is unsupported"); + } + validate_authority_identifier(&self.capability, "dependency capability")?; + validate_authority_identifier(&self.schema, "dependency schema")?; + validate_authority_identifier(&self.compatibility, "dependency compatibility")?; + if self.minimum_capacity == 0 + || !matches!(self.startup.as_str(), "before-start" | "before-promotion") + { + bail!("dependency capacity or startup condition is invalid"); + } + if self.kind == "bootstrap" && self.startup != "before-start" { + bail!("bootstrap dependency must be satisfied before start"); + } + validate_optional_identifier(&self.provider_id, "dependency provider id")?; + validate_optional_identifier(&self.provider_authority, "dependency provider authority")?; + validate_optional_sha256( + &self.provider_expected_projection_sha256, + "dependency provider expected projection sha256", + )?; + validate_optional_endpoint_labeled( + &self.provider_endpoint, + "dependency provider endpoint", + )?; + + match ( + &self.provider_id, + &self.provider_authority, + &self.provider_expected_projection_sha256, + &self.provider_endpoint, + ) { + (None, None, None, None) => {} + (Some(_), Some(authority), Some(_), _) if authority == "managed-incarnation" => { + if self.kind == "external-operator-binding" { + bail!("external operator dependency cannot select a managed incarnation"); + } + } + (Some(_), Some(authority), None, Some(_)) + if authority == "external-operator-binding" + && self.kind == "external-operator-binding" => {} + _ => bail!("dependency provider binding is partial or authority-incoherent"), + } + Ok(()) + } +} + +/// Idunn-owned desired deployment identity published into CultMesh before +/// promotion. It describes the admitted incarnation and its public contracts, +/// never the private details needed to execute it on a particular host. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.expected_incarnation", + schema = "idunn.expected_incarnation.v2" +)] +pub struct IdunnExpectedIncarnationRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub target: String, + #[cultcache(key = 2)] + pub plan_id: String, + #[cultcache(key = 3)] + pub incarnation_id: String, + #[cultcache(key = 4)] + pub sealed_release_id: String, + #[cultcache(key = 5)] + pub source_repository: String, + #[cultcache(key = 6)] + pub source_revision: String, + #[cultcache(key = 7)] + pub recipe_sha256: String, + #[cultcache(key = 8)] + pub runtime_id: String, + #[cultcache(key = 9)] + pub expected_signer_identity_id: String, + #[cultcache(key = 10)] + pub health_contract: String, + #[cultcache(key = 11)] + pub artifact_sha256: String, + #[cultcache(key = 12)] + pub state_schema_generation: Option, + #[cultcache(key = 13)] + pub state_contract_sha256: Option, + #[cultcache(key = 14)] + pub write_lease_required: bool, + #[cultcache(key = 15)] + pub route: Option, + #[cultcache(key = 16)] + pub capabilities: Vec, + #[cultcache(key = 17)] + pub dependencies: Vec, +} + +impl IdunnExpectedIncarnationRecord { + pub fn decode_canonical(payload: &[u8]) -> Result { + if messagepack_array_len(payload) != Some(18) { + bail!("expected incarnation is not the 18-field positional contract"); + } + let expected: Self = + rmp_serde::from_slice(payload).context("decoding expected incarnation")?; + if rmp_serde::to_vec(&expected)? != payload { + bail!("expected incarnation is not canonical positional MessagePack"); + } + expected.validate()?; + Ok(expected) + } + + pub fn canonical_bytes(&self) -> Result> { + self.validate()?; + Ok(rmp_serde::to_vec(self)?) + } + + pub fn canonical_sha256(&self) -> Result { + Ok(prefixed_sha256(&self.canonical_bytes()?)) + } + + pub fn validate(&self) -> Result<()> { + if self.schema_version != IDUNN_EXPECTED_INCARNATION_SCHEMA { + bail!("expected incarnation schema is unsupported"); + } + validate_authority_identifier(&self.target, "target")?; + validate_required_sha256(&self.plan_id, "plan id")?; + validate_authority_identifier(&self.incarnation_id, "incarnation id")?; + validate_required_sha256(&self.sealed_release_id, "sealed release id")?; + validate_source_repository(&self.source_repository)?; + if !is_lower_hex(&self.source_revision, 40) { + bail!("source revision is not a lowercase Git object id"); + } + validate_required_sha256(&self.recipe_sha256, "recipe sha256")?; + validate_authority_identifier(&self.runtime_id, "runtime id")?; + validate_authority_identifier( + &self.expected_signer_identity_id, + "expected signer identity id", + )?; + validate_authority_identifier(&self.health_contract, "health contract")?; + validate_required_sha256(&self.artifact_sha256, "artifact sha256")?; + match (&self.state_schema_generation, &self.state_contract_sha256) { + (Some(generation), Some(contract_sha256)) => { + validate_authority_identifier(generation, "state schema generation")?; + validate_required_sha256(contract_sha256, "state contract sha256")?; + } + (None, None) => {} + _ => bail!("expected incarnation state lineage is partial"), + } + if self.write_lease_required && self.state_schema_generation.is_none() { + bail!("stateless incarnation cannot require a process write lease"); + } + if let Some(route) = &self.route { + route.validate()?; + } + validate_expected_capabilities(&self.capabilities)?; + validate_expected_dependencies(&self.dependencies)?; + Ok(()) + } +} + +/// Odin's observation of one dependency selected in the bound Expected +/// projection. Evidence digests identify the signed/provider-owned facts Odin +/// used; they do not copy those facts into Odin authority. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OdinRuntimeDependencyEvidence { + pub kind: String, + pub capability: String, + pub schema: String, + pub compatibility: String, + pub provider_id: Option, + pub provider_authority: Option, + pub provider_expected_projection_sha256: Option, + pub provider_endpoint: Option, + pub observed_capacity: Option, + pub provider_evidence_sha256: Option, + pub ready: bool, +} + +impl OdinRuntimeDependencyEvidence { + fn identity(&self) -> (&str, &str, &str) { + (&self.capability, &self.schema, &self.compatibility) + } + + fn validate(&self) -> Result<()> { + if !matches!( + self.kind.as_str(), + "bootstrap" + | "required" + | "optional" + | "shared-infrastructure" + | "private" + | "external-operator-binding" + ) { + bail!("dependency evidence kind is unsupported"); + } + validate_authority_identifier(&self.kind, "dependency evidence kind")?; + validate_authority_identifier(&self.capability, "dependency evidence capability")?; + validate_authority_identifier(&self.schema, "dependency evidence schema")?; + validate_authority_identifier(&self.compatibility, "dependency evidence compatibility")?; + validate_optional_identifier(&self.provider_id, "dependency evidence provider id")?; + validate_optional_identifier( + &self.provider_authority, + "dependency evidence provider authority", + )?; + validate_optional_sha256( + &self.provider_expected_projection_sha256, + "dependency evidence provider expected projection sha256", + )?; + validate_optional_endpoint_labeled( + &self.provider_endpoint, + "dependency evidence provider endpoint", + )?; + validate_optional_sha256( + &self.provider_evidence_sha256, + "dependency provider evidence sha256", + )?; + if self.observed_capacity == Some(0) { + bail!("dependency evidence capacity is zero"); + } + if self.provider_id.is_none() + && (self.provider_authority.is_some() + || self.provider_expected_projection_sha256.is_some() + || self.provider_endpoint.is_some() + || self.observed_capacity.is_some() + || self.provider_evidence_sha256.is_some() + || self.ready) + { + bail!("dependency evidence has facts without a provider"); + } + if self.provider_id.is_some() && self.provider_authority.is_none() { + bail!("dependency evidence provider authority is missing"); + } + match ( + &self.provider_id, + &self.provider_authority, + &self.provider_expected_projection_sha256, + &self.provider_endpoint, + ) { + (None, None, None, None) => {} + (Some(_), Some(authority), Some(_), _) if authority == "managed-incarnation" => { + if self.kind == "external-operator-binding" { + bail!("external dependency evidence names a managed incarnation"); + } + } + (Some(_), Some(authority), None, Some(_)) + if authority == "external-operator-binding" + && self.kind == "external-operator-binding" => {} + _ => bail!("dependency evidence provider binding is authority-incoherent"), + } + if self.ready + && (self.observed_capacity.is_none() || self.provider_evidence_sha256.is_none()) + { + bail!("ready dependency lacks capacity or signed evidence"); + } + Ok(()) + } +} + +/// One explicit Expected/observed disagreement. Codes are unique and sorted so +/// the signed receipt has one canonical explanation for each disagreement. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OdinTopologyDisagreement { + pub code: String, + pub expected: Option, + pub observed: Option, +} + +impl OdinTopologyDisagreement { + fn validate(&self) -> Result<()> { + validate_authority_identifier(&self.code, "topology disagreement code")?; + validate_optional_detail(&self.expected, "topology disagreement expected value")?; + validate_optional_detail(&self.observed, "topology disagreement observed value")?; + if self.expected.is_none() && self.observed.is_none() { + bail!("topology disagreement carries no expected or observed value"); + } + Ok(()) + } +} + +/// Odin-owned signed correlation of Idunn's exact Expected projection with +/// current Idunn activation and provider-signed presence. Presence state and +/// write-lease observation remain explicit so an opaque Ready bit cannot cross +/// Idunn's warming/fencing boundary. The signature covers the canonical +/// positional encoding with `signature` empty. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "odin.runtime_topology_correlation", + schema = "odin.runtime_topology_correlation.v2" +)] +pub struct OdinRuntimeTopologyCorrelationRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub target: String, + #[cultcache(key = 2)] + pub expected_projection_sha256: String, + #[cultcache(key = 3)] + pub expected: bool, + #[cultcache(key = 4)] + pub current_activation_sha256: Option, + #[cultcache(key = 5)] + pub signed_presence_sha256: Option, + #[cultcache(key = 6)] + pub observed_presence_state: Option, + #[cultcache(key = 7)] + pub observed_presence_publisher_sequence: Option, + #[cultcache(key = 8)] + pub observed_write_lease_sha256: Option, + #[cultcache(key = 9)] + pub observed_capabilities: Vec, + #[cultcache(key = 10)] + pub runtime_id: String, + #[cultcache(key = 11)] + pub runtime_instance_id: Option, + #[cultcache(key = 12)] + pub present: bool, + #[cultcache(key = 13)] + pub ready: bool, + #[cultcache(key = 14)] + pub dependencies: Vec, + #[cultcache(key = 15)] + pub disagreements: Vec, + #[cultcache(key = 16)] + pub signer_identity_id: String, + #[cultcache(key = 17)] + pub publisher_sequence: u64, + #[cultcache(key = 18)] + pub observed_at_unix_millis: u64, + #[cultcache(key = 19)] + pub signature_algorithm: String, + #[cultcache(key = 20, bytes)] + pub signature: Vec, +} + +impl OdinRuntimeTopologyCorrelationRecord { + pub fn decode_canonical_signed_payload(payload: &[u8]) -> Result<(Self, Vec)> { + if messagepack_array_len(payload) != Some(21) { + bail!("topology correlation is not the 21-field positional contract"); + } + let receipt: Self = + rmp_serde::from_slice(payload).context("decoding runtime topology correlation")?; + if rmp_serde::to_vec(&receipt)? != payload { + bail!("topology correlation is not canonical positional MessagePack"); + } + receipt.validate()?; + let unsigned = receipt.unsigned_signature_payload()?; + Ok((receipt, unsigned)) + } + + pub fn unsigned_signature_payload(&self) -> Result> { + self.validate_shape(true)?; + let mut unsigned = self.clone(); + unsigned.signature.clear(); + Ok(rmp_serde::to_vec(&unsigned)?) + } + + pub fn canonical_bytes(&self) -> Result> { + self.validate()?; + Ok(rmp_serde::to_vec(self)?) + } + + pub fn canonical_sha256(&self) -> Result { + Ok(prefixed_sha256(&self.canonical_bytes()?)) + } + + pub fn validate(&self) -> Result<()> { + self.validate_shape(false) + } + + pub fn validate_against_expected( + &self, + expected: &IdunnExpectedIncarnationRecord, + current_write_lease_sha256: Option<&str>, + ) -> Result<()> { + self.validate()?; + expected.validate()?; + if self.expected_projection_sha256 != expected.canonical_sha256()? + || self.target != expected.target + || self.runtime_id != expected.runtime_id + || self.dependencies.len() != expected.dependencies.len() + { + bail!("topology correlation substitutes or omits Expected authority"); + } + for (evidence, requirement) in self.dependencies.iter().zip(&expected.dependencies) { + if evidence.identity() != requirement.identity() + || evidence.kind != requirement.kind + || evidence.provider_id != requirement.provider_id + || evidence.provider_authority != requirement.provider_authority + || evidence.provider_expected_projection_sha256 + != requirement.provider_expected_projection_sha256 + || evidence.provider_endpoint != requirement.provider_endpoint + { + bail!("topology dependency evidence does not bind the Expected dependency"); + } + if evidence.ready + && evidence + .observed_capacity + .is_none_or(|capacity| capacity < requirement.minimum_capacity) + { + bail!("ready dependency does not meet Expected capacity"); + } + } + let mut capability_disagreements = Vec::new(); + correlate_capabilities( + &mut capability_disagreements, + &expected.capabilities, + &self.observed_capabilities, + ); + for disagreement in &capability_disagreements { + if !self.disagreements.contains(disagreement) { + bail!("topology correlation omits an observed capability disagreement"); + } + } + if let Some(current_write_lease_sha256) = current_write_lease_sha256 { + validate_required_sha256(current_write_lease_sha256, "current write lease sha256")?; + } + if expected.write_lease_required { + if self + .observed_write_lease_sha256 + .as_deref() + .is_some_and(|observed| Some(observed) != current_write_lease_sha256) + { + bail!("observed write lease is not the current Idunn grant"); + } + if self.ready + && (self.observed_write_lease_sha256.is_none() + || current_write_lease_sha256.is_none()) + { + bail!("Ready stateful topology lacks the exact current write lease"); + } + } else if self.observed_write_lease_sha256.is_some() || current_write_lease_sha256.is_some() + { + bail!("stateless Expected topology cannot carry a process write lease"); + } + Ok(()) + } + + fn validate_shape(&self, allow_unsigned: bool) -> Result<()> { + if self.schema_version != ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA { + bail!("topology correlation schema is unsupported"); + } + validate_authority_identifier(&self.target, "target")?; + validate_required_sha256( + &self.expected_projection_sha256, + "correlation expected projection sha256", + )?; + if !self.expected { + bail!("topology correlation cannot deny the Expected record it binds"); + } + validate_optional_sha256(&self.current_activation_sha256, "current activation sha256")?; + validate_optional_sha256(&self.signed_presence_sha256, "signed presence sha256")?; + validate_optional_identifier(&self.observed_presence_state, "observed presence state")?; + if self.observed_presence_publisher_sequence == Some(0) { + bail!("observed presence publisher sequence is zero"); + } + validate_optional_sha256( + &self.observed_write_lease_sha256, + "observed write lease sha256", + )?; + validate_runtime_capabilities(&self.observed_capabilities)?; + if self.signed_presence_sha256.is_none() && !self.observed_capabilities.is_empty() { + bail!("topology correlation has capabilities without signed presence"); + } + match ( + &self.signed_presence_sha256, + &self.observed_presence_state, + self.observed_presence_publisher_sequence, + &self.observed_write_lease_sha256, + ) { + (None, None, None, None) => {} + (Some(_), Some(state), Some(_), write_lease) + if matches!(state.as_str(), "warming" | "active" | "degraded" | "failed") => + { + if state == "warming" && write_lease.is_some() { + bail!("warming topology presence cannot carry a process write lease"); + } + } + _ => bail!("signed presence state, sequence, or write-lease observation is partial"), + } + validate_authority_identifier(&self.runtime_id, "runtime id")?; + validate_optional_sha256(&self.runtime_instance_id, "runtime instance id")?; + let has_runtime_evidence = + self.current_activation_sha256.is_some() || self.signed_presence_sha256.is_some(); + if self.runtime_instance_id.is_some() != has_runtime_evidence { + bail!("runtime instance identity and observation evidence are partial"); + } + if self.present + && (self.current_activation_sha256.is_none() + || self.signed_presence_sha256.is_none() + || self.observed_presence_publisher_sequence.is_none() + || self.runtime_instance_id.is_none()) + { + bail!("Present topology state lacks an authenticated runtime session"); + } + validate_dependency_evidence(&self.dependencies)?; + validate_topology_disagreements(&self.disagreements)?; + let has_activation = self.current_activation_sha256.is_some(); + let has_presence = self.signed_presence_sha256.is_some(); + if has_activation && has_presence && !self.present { + bail!("authenticated runtime session cannot be projected as not Present"); + } + if has_activation != has_presence && self.disagreements.is_empty() { + bail!("partial or rejected runtime evidence lacks an explicit disagreement"); + } + if self.ready + && (!self.present + || self.observed_presence_state.as_deref() != Some("active") + || !self.disagreements.is_empty() + || self + .dependencies + .iter() + .any(|dependency| dependency.kind != "optional" && !dependency.ready)) + { + bail!("Ready topology state is not supported by correlated evidence"); + } + validate_authority_identifier(&self.signer_identity_id, "signer identity id")?; + let signature_is_valid = + self.signature.len() == 64 || (allow_unsigned && self.signature.is_empty()); + if self.publisher_sequence == 0 + || self.observed_at_unix_millis == 0 + || self.signature_algorithm != "ed25519" + || !signature_is_valid + { + bail!("topology correlation sequence, time, or signature is invalid"); + } + Ok(()) + } +} + +/// An in-memory activation-scoped signer reconstructed by the launched service +/// from its protected systemd credential. The stable service identity never +/// receives this key, and the public activation record never contains it. +pub struct IdunnRuntimeActivationSigner { + signing_key: SigningKey, +} + +impl IdunnRuntimeActivationSigner { + fn generate() -> Self { + let mut seed = Zeroizing::new([0_u8; 32]); + rand::rng().fill_bytes(seed.as_mut()); + Self { + signing_key: SigningKey::from_bytes(&*seed), + } + } + + /// Open the exact raw 32-byte Ed25519 seed supplied through Idunn's systemd + /// credential without retaining an ordinary heap copy. No persistent key + /// schema exists: this authority lives for one activation and is replaced + /// on every launch. + pub fn from_credential_reader(mut credential: impl Read) -> Result { + let mut seed = Zeroizing::new([0_u8; 32]); + credential + .read_exact(seed.as_mut()) + .context("reading runtime activation credential")?; + let mut extra = [0_u8; 1]; + if credential.read(&mut extra)? != 0 { + bail!("runtime activation credential is longer than 32 bytes"); + } + Ok(Self { + signing_key: SigningKey::from_bytes(&*seed), + }) + } + + fn write_credential(&self, mut destination: impl Write) -> Result<()> { + let seed = Zeroizing::new(self.signing_key.to_bytes()); + destination + .write_all(seed.as_ref()) + .context("writing runtime activation credential") + } + + pub fn public_key(&self) -> Vec { + self.signing_key.verifying_key().to_bytes().to_vec() + } + + pub fn identity_id(&self) -> String { + derive_idunn_runtime_activation_identity_id(&self.public_key()) + .expect("an Ed25519 activation signer always has a 32-byte public key") + } + + pub fn sign_presence_proof( + &self, + presence: &GameCultRuntimePresenceHealthRecord, + ) -> Result> { + if presence.activation_signer_identity_id != self.identity_id() { + bail!("runtime presence names a different activation signer"); + } + let payload = presence.canonical_proof_payload()?; + Ok(self + .signing_key + .sign(&runtime_activation_signing_message(&payload)) + .to_bytes() + .to_vec()) + } +} + +/// Idunn's one-shot launch material. Issuance always creates a fresh key, and +/// writing the protected credential consumes the only Idunn-side signer. +pub struct IdunnRuntimeActivationLaunch { + activation: IdunnRuntimeActivationRecord, + signer: IdunnRuntimeActivationSigner, +} + +impl IdunnRuntimeActivationLaunch { + pub fn issue( + expected: &IdunnExpectedIncarnationRecord, + runtime_instance_id: String, + issued_at_unix_millis: u64, + idunn_signer: &crate::ServiceIdentitySigner, + ) -> Result { + let signer = IdunnRuntimeActivationSigner::generate(); + let activation = IdunnRuntimeActivationRecord::issue_with_signer( + expected, + runtime_instance_id, + &signer, + issued_at_unix_millis, + idunn_signer, + )?; + Ok(Self { activation, signer }) + } + + pub fn activation(&self) -> &IdunnRuntimeActivationRecord { + &self.activation + } + + pub fn write_credential(self, destination: impl Write) -> Result { + self.signer.write_credential(destination)?; + Ok(self.activation) + } +} + +/// Derive the activation-scoped identity from the Idunn-issued public key. The +/// domain is dedicated to runtime activation and cannot be substituted for a +/// stable provider, Idunn, or Odin service identity. +pub fn derive_idunn_runtime_activation_identity_id(public_key: &[u8]) -> Result { + if public_key.len() != 32 { + bail!("runtime activation public key has invalid length"); + } + Ok(format!( + "{:x}", + Sha256::digest([IDUNN_RUNTIME_ACTIVATION_ID_DOMAIN, public_key].concat()) + )) +} + +/// Current Idunn authority for one launch. Idunn's stable signature binds the +/// complete Expected digest and activation key; Expected in turn pins the +/// provider signer identity. The provider public key is lookup material, not a +/// second authority: its profile-derived identity must equal Idunn's signed +/// selection exactly. +#[derive(Clone, Debug)] +pub struct VerifiedRuntimeAuthority { + expected: IdunnExpectedIncarnationRecord, + activation: IdunnRuntimeActivationRecord, + provider_signer_public_key: Vec, + expected_sha256: String, + activation_sha256: String, +} + +impl VerifiedRuntimeAuthority { + pub fn expected(&self) -> &IdunnExpectedIncarnationRecord { + &self.expected + } + + pub fn activation(&self) -> &IdunnRuntimeActivationRecord { + &self.activation + } + + pub fn expected_sha256(&self) -> &str { + &self.expected_sha256 + } + + pub fn activation_sha256(&self) -> &str { + &self.activation_sha256 + } +} + +pub fn verify_runtime_authority( + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + idunn_anchor: &crate::ServiceIdentityTrustAnchor, + provider_signer_public_key: &[u8], +) -> Result { + expected.validate()?; + activation.verify_for_expected(expected, idunn_anchor)?; + if crate::derive_service_identity_id::( + provider_signer_public_key, + )? != expected.expected_signer_identity_id + { + bail!("provider public key is not Idunn's Expected signer selection"); + } + Ok(VerifiedRuntimeAuthority { + expected: expected.clone(), + activation: activation.clone(), + provider_signer_public_key: provider_signer_public_key.to_vec(), + expected_sha256: expected.canonical_sha256()?, + activation_sha256: activation.canonical_sha256()?, + }) +} + +#[derive(Clone, Copy, Debug)] +pub struct RuntimePresenceAuthenticationContext { + pub trusted_received_at_unix_millis: u64, + pub maximum_age_millis: u64, + pub maximum_future_skew_millis: u64, +} + +/// Canonical runtime bytes authenticated by both the Expected provider key and +/// the current activation key. No semantic claim has yet been accepted as +/// Present; Odin must correlate this observation against current authority. +#[derive(Clone, Debug)] +pub struct AuthenticatedRuntimePresenceClaim { + record: GameCultRuntimePresenceHealthRecord, + canonical_bytes: Vec, + signed_presence_sha256: String, + received_at_unix_millis: u64, +} + +impl AuthenticatedRuntimePresenceClaim { + pub fn record(&self) -> &GameCultRuntimePresenceHealthRecord { + &self.record + } + + pub fn canonical_bytes(&self) -> &[u8] { + &self.canonical_bytes + } + + pub fn signed_presence_sha256(&self) -> &str { + &self.signed_presence_sha256 + } + + pub fn received_at_unix_millis(&self) -> u64 { + self.received_at_unix_millis + } +} + +/// A signed Odin receipt authenticated against the exact current Expected, +/// activation, write lease, Idunn-admitted topology key, and trusted receipt +/// time. This is evidence, not a replay cursor or route-promotion grant. The +/// caller must source the key from Idunn's admitted Odin binding. Idunn's +/// durable admission owner must atomically check and advance Odin's publisher +/// sequence before treating the receipt as current. +#[derive(Clone, Debug)] +pub struct AuthenticatedOdinRuntimeTopologyCorrelation { + record: OdinRuntimeTopologyCorrelationRecord, + canonical_bytes: Vec, +} + +impl AuthenticatedOdinRuntimeTopologyCorrelation { + pub fn record(&self) -> &OdinRuntimeTopologyCorrelationRecord { + &self.record + } + + pub fn canonical_bytes(&self) -> &[u8] { + &self.canonical_bytes + } +} + +#[derive(Clone, Copy, Debug)] +pub struct OdinTopologyAuthenticationContext { + pub trusted_received_at_unix_millis: u64, + pub maximum_age_millis: u64, + pub maximum_future_skew_millis: u64, +} + +pub fn authenticate_odin_runtime_topology_correlation( + canonical_correlation: &[u8], + authority: &VerifiedRuntimeAuthority, + current_write_lease_sha256: Option<&str>, + admitted_odin_signer_public_key: &[u8], + context: OdinTopologyAuthenticationContext, +) -> Result { + ensure!( + context.trusted_received_at_unix_millis > 0 && context.maximum_age_millis > 0, + "Odin topology trusted time and maximum age must be positive" + ); + let (record, unsigned) = OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload( + canonical_correlation, + )?; + record.validate_against_expected(authority.expected(), current_write_lease_sha256)?; + if record.current_activation_sha256.as_deref() != Some(authority.activation_sha256()) + || record.runtime_instance_id.as_deref() + != Some(authority.activation.runtime_instance_id.as_str()) + { + bail!("topology correlation does not bind the current activation"); + } + let latest_trusted_timestamp = context + .trusted_received_at_unix_millis + .saturating_add(context.maximum_future_skew_millis); + if record.observed_at_unix_millis > latest_trusted_timestamp + || context + .trusted_received_at_unix_millis + .saturating_sub(record.observed_at_unix_millis) + > context.maximum_age_millis + { + bail!("Odin topology correlation is outside the trusted observation window"); + } + crate::verify_service_identity_signature_with_public_key::< + crate::OdinTopologyIdentity, + crate::OdinRuntimeTopologyCorrelationPurpose, + >( + admitted_odin_signer_public_key, + &unsigned, + &crate::ServiceIdentitySignature { + identity_id: record.signer_identity_id.clone(), + signature: record.signature.clone(), + }, + )?; + Ok(AuthenticatedOdinRuntimeTopologyCorrelation { + record, + canonical_bytes: canonical_correlation.to_vec(), + }) +} + +/// Odin's deterministic interpretation of an authenticated provider claim. +/// Authentication of the stable provider and current activation establishes +/// Present. Correlation disagreements remain explicit and deny Ready; they do +/// not erase the observed session that produced them. +#[derive(Clone, Debug)] +pub struct RuntimePresenceCorrelation { + presence: VerifiedRuntimePresence, + disagreements: Vec, +} + +impl RuntimePresenceCorrelation { + pub fn claim(&self) -> &AuthenticatedRuntimePresenceClaim { + &self.presence.claim + } + + pub fn disagreements(&self) -> &[OdinTopologyDisagreement] { + &self.disagreements + } + + pub fn into_present(self) -> VerifiedRuntimePresence { + self.presence + } + + pub fn into_undisputed_present(self) -> Result { + if !self.disagreements.is_empty() { + bail!("runtime presence disagrees with current Expected projection"); + } + Ok(self.presence) + } +} + +/// A dual-authenticated claim that matches current authority. This is the only +/// value that represents semantic Present. Replay admission deliberately does +/// not live here: Odin's durable store must atomically check and advance every +/// authenticated provider sequence, including disagreement-bearing claims, +/// before it signs a topology correlation. +#[derive(Clone, Debug)] +pub struct VerifiedRuntimePresence { + claim: AuthenticatedRuntimePresenceClaim, +} + +impl VerifiedRuntimePresence { + pub fn record(&self) -> &GameCultRuntimePresenceHealthRecord { + self.claim.record() + } + + pub fn canonical_bytes(&self) -> &[u8] { + self.claim.canonical_bytes() + } + + pub fn signed_presence_sha256(&self) -> &str { + self.claim.signed_presence_sha256() + } + + pub fn accepted_at_unix_millis(&self) -> u64 { + self.claim.received_at_unix_millis() + } +} + +pub fn authenticate_runtime_presence_claim( + canonical_presence: &[u8], + authority: &VerifiedRuntimeAuthority, + context: RuntimePresenceAuthenticationContext, +) -> Result { + ensure!( + context.trusted_received_at_unix_millis > 0 && context.maximum_age_millis > 0, + "runtime presence trusted time and maximum age must be positive" + ); + if messagepack_array_len(canonical_presence) != Some(24) { + bail!("runtime presence payload is not the 24-field positional contract"); + } + let presence: GameCultRuntimePresenceHealthRecord = + rmp_serde::from_slice(canonical_presence).context("decoding runtime presence health")?; + if rmp_serde::to_vec(&presence)? != canonical_presence { + bail!("runtime presence payload is not canonical positional MessagePack"); + } + presence.validate()?; + let latest_trusted_timestamp = context + .trusted_received_at_unix_millis + .saturating_add(context.maximum_future_skew_millis); + if presence.observed_at_unix_millis > latest_trusted_timestamp + || authority.activation.issued_at_unix_millis > latest_trusted_timestamp + || context + .trusted_received_at_unix_millis + .saturating_sub(presence.observed_at_unix_millis) + > context.maximum_age_millis + { + bail!("runtime presence is outside the trusted observation window"); + } + if presence.signer_identity_id != authority.expected.expected_signer_identity_id { + bail!("runtime presence signer is not Idunn's Expected signer selection"); + } + + let proof_payload = presence.canonical_proof_payload()?; + crate::verify_service_identity_signature_with_public_key::< + crate::GameCultProviderHealthIdentity, + crate::GameCultRuntimePresenceHealthPurpose, + >( + &authority.provider_signer_public_key, + &proof_payload, + &crate::ServiceIdentitySignature { + identity_id: presence.signer_identity_id.clone(), + signature: presence.signature.clone(), + }, + )?; + let activation_public_key: [u8; 32] = authority + .activation + .activation_signer_public_key + .as_slice() + .try_into() + .map_err(|_| anyhow::anyhow!("runtime activation public key has invalid length"))?; + let activation_signature = Signature::from_slice(&presence.activation_signature) + .map_err(|_| anyhow::anyhow!("runtime activation signature has invalid length"))?; + VerifyingKey::from_bytes(&activation_public_key)? + .verify( + &runtime_activation_signing_message(&proof_payload), + &activation_signature, + ) + .map_err(|_| anyhow::anyhow!("runtime activation proof verification failed"))?; + + Ok(AuthenticatedRuntimePresenceClaim { + record: presence, + canonical_bytes: canonical_presence.to_vec(), + signed_presence_sha256: prefixed_sha256(canonical_presence), + received_at_unix_millis: context.trusted_received_at_unix_millis, + }) +} + +pub fn correlate_runtime_presence_claim( + claim: AuthenticatedRuntimePresenceClaim, + authority: &VerifiedRuntimeAuthority, +) -> Result { + let expected = authority.expected(); + let activation = authority.activation(); + let presence = claim.record(); + let expected_endpoint = expected + .route + .as_ref() + .map(|route| route.candidate_endpoint.clone()); + let mut disagreements = Vec::new(); + push_disagreement( + &mut disagreements, + "activation-signer-identity", + Some(&activation.activation_signer_identity_id), + Some(&presence.activation_signer_identity_id), + ); + push_disagreement( + &mut disagreements, + "activation-witness", + Some(authority.activation_sha256()), + Some(&presence.activation_witness_sha256), + ); + push_disagreement( + &mut disagreements, + "bound-endpoint", + expected_endpoint.as_deref(), + presence.bound_endpoint.as_deref(), + ); + push_disagreement( + &mut disagreements, + "expected-projection", + Some(authority.expected_sha256()), + Some(&presence.expected_projection_sha256), + ); + push_disagreement( + &mut disagreements, + "health-contract", + Some(&expected.health_contract), + Some(&presence.health_contract), + ); + push_disagreement( + &mut disagreements, + "incarnation-id", + Some(&expected.incarnation_id), + Some(&presence.incarnation_id), + ); + push_disagreement( + &mut disagreements, + "plan-id", + Some(&expected.plan_id), + Some(&presence.plan_id), + ); + push_disagreement( + &mut disagreements, + "runtime-id", + Some(&expected.runtime_id), + Some(&presence.runtime_id), + ); + push_disagreement( + &mut disagreements, + "runtime-instance-id", + Some(&activation.runtime_instance_id), + Some(&presence.runtime_instance_id), + ); + push_disagreement( + &mut disagreements, + "sealed-release-id", + Some(&expected.sealed_release_id), + Some(&presence.sealed_release_id), + ); + push_disagreement( + &mut disagreements, + "signer-identity", + Some(&expected.expected_signer_identity_id), + Some(&presence.signer_identity_id), + ); + push_disagreement( + &mut disagreements, + "state-contract", + expected.state_contract_sha256.as_deref(), + presence.state_contract_sha256.as_deref(), + ); + push_disagreement( + &mut disagreements, + "state-schema-generation", + expected.state_schema_generation.as_deref(), + presence.state_schema_generation.as_deref(), + ); + push_disagreement( + &mut disagreements, + "target", + Some(&expected.target), + Some(&presence.target), + ); + if activation.issued_at_unix_millis > presence.observed_at_unix_millis { + disagreements.push(OdinTopologyDisagreement { + code: "activation-issued-after-presence".into(), + expected: Some(format!("at-most:{}", presence.observed_at_unix_millis)), + observed: Some(activation.issued_at_unix_millis.to_string()), + }); + } + correlate_capabilities( + &mut disagreements, + &expected.capabilities, + &presence.capabilities, + ); + disagreements.sort_by(|left, right| left.code.cmp(&right.code)); + validate_topology_disagreements(&disagreements)?; + Ok(RuntimePresenceCorrelation { + presence: VerifiedRuntimePresence { claim }, + disagreements, + }) +} + +fn push_disagreement( + disagreements: &mut Vec, + code: &str, + expected: Option<&str>, + observed: Option<&str>, +) { + if expected != observed { + disagreements.push(OdinTopologyDisagreement { + code: code.into(), + expected: expected.map(str::to_string), + observed: observed.map(str::to_string), + }); + } +} + +fn correlate_capabilities( + disagreements: &mut Vec, + expected: &[IdunnExpectedCapability], + observed: &[GameCultRuntimeCapability], +) { + for (index, required) in expected.iter().enumerate() { + let actual = observed + .iter() + .find(|actual| actual.identity() == required.identity()); + let requirement = format!( + "{}/{}/{} capacity>={}", + required.capability, required.schema, required.compatibility, required.minimum_capacity + ); + match actual { + None => disagreements.push(OdinTopologyDisagreement { + code: format!("expected-capability-{index:03}-missing"), + expected: Some(requirement), + observed: None, + }), + Some(actual) if actual.capacity < required.minimum_capacity => { + disagreements.push(OdinTopologyDisagreement { + code: format!("expected-capability-{index:03}-capacity"), + expected: Some(requirement), + observed: Some(format!("capacity={}", actual.capacity)), + }); + } + Some(_) => {} + } + } +} + +fn runtime_activation_signing_message(payload: &[u8]) -> Vec { + let purpose = GAMECULT_RUNTIME_ACTIVATION_PROOF_SIGNING_PURPOSE.as_bytes(); + let mut out = Vec::with_capacity( + IDUNN_RUNTIME_ACTIVATION_SIGNATURE_DOMAIN.len() + purpose.len() + payload.len() + 16, + ); + out.extend_from_slice(IDUNN_RUNTIME_ACTIVATION_SIGNATURE_DOMAIN); + out.extend_from_slice(&(purpose.len() as u64).to_be_bytes()); + out.extend_from_slice(purpose); + out.extend_from_slice(&(payload.len() as u64).to_be_bytes()); + out.extend_from_slice(payload); + out +} + +/// Idunn-issued launch identity. Idunn's stable service identity signs the +/// complete activation, including the ephemeral public key, before the private +/// credential is passed to one workload alongside Expected. Odin still treats +/// it as current only after Idunn publishes an observed native process. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.runtime_activation", + schema = "idunn.runtime_activation.v2" +)] +pub struct IdunnRuntimeActivationRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub expected_projection_sha256: String, + #[cultcache(key = 2)] + pub runtime_id: String, + #[cultcache(key = 3)] + pub runtime_instance_id: String, + #[cultcache(key = 4)] + pub activation_signer_identity_id: String, + #[cultcache(key = 5, bytes)] + pub activation_signer_public_key: Vec, + #[cultcache(key = 6)] + pub issued_at_unix_millis: u64, + #[cultcache(key = 7)] + pub idunn_signer_identity_id: String, + #[cultcache(key = 8)] + pub signature_algorithm: String, + #[cultcache(key = 9, bytes)] + pub signature: Vec, +} + +impl IdunnRuntimeActivationRecord { + fn issue_with_signer( + expected: &IdunnExpectedIncarnationRecord, + runtime_instance_id: String, + activation_signer: &IdunnRuntimeActivationSigner, + issued_at_unix_millis: u64, + idunn_signer: &crate::ServiceIdentitySigner, + ) -> Result { + expected.validate()?; + let mut activation = Self { + schema_version: IDUNN_RUNTIME_ACTIVATION_SCHEMA.into(), + expected_projection_sha256: expected.canonical_sha256()?, + runtime_id: expected.runtime_id.clone(), + runtime_instance_id, + activation_signer_identity_id: activation_signer.identity_id(), + activation_signer_public_key: activation_signer.public_key(), + issued_at_unix_millis, + idunn_signer_identity_id: idunn_signer.entry().identity_id.clone(), + signature_algorithm: "ed25519".into(), + signature: Vec::new(), + }; + let proof = idunn_signer.sign::( + &activation.unsigned_signature_payload()?, + ); + activation.signature = proof.signature; + activation.validate()?; + Ok(activation) + } + + pub fn decode_canonical(payload: &[u8]) -> Result { + if messagepack_array_len(payload) != Some(10) { + bail!("runtime activation is not the 10-field positional contract"); + } + let activation: Self = + rmp_serde::from_slice(payload).context("decoding runtime activation")?; + if rmp_serde::to_vec(&activation)? != payload { + bail!("runtime activation is not canonical positional MessagePack"); + } + activation.validate()?; + Ok(activation) + } + + pub fn canonical_bytes(&self) -> Result> { + self.validate()?; + Ok(rmp_serde::to_vec(self)?) + } + + pub fn canonical_sha256(&self) -> Result { + Ok(prefixed_sha256(&self.canonical_bytes()?)) + } + + pub fn unsigned_signature_payload(&self) -> Result> { + self.validate_shape(true)?; + let mut unsigned = self.clone(); + unsigned.signature.clear(); + Ok(rmp_serde::to_vec(&unsigned)?) + } + + pub fn verify_for_expected( + &self, + expected: &IdunnExpectedIncarnationRecord, + idunn_anchor: &crate::ServiceIdentityTrustAnchor, + ) -> Result<()> { + self.validate()?; + expected.validate()?; + if self.expected_projection_sha256 != expected.canonical_sha256()? + || self.runtime_id != expected.runtime_id + { + bail!("runtime activation does not bind the current Expected incarnation"); + } + crate::verify_service_identity_signature::< + crate::IdunnServiceIdentity, + crate::IdunnRuntimeActivationPurpose, + >( + idunn_anchor, + &self.unsigned_signature_payload()?, + &crate::ServiceIdentitySignature { + identity_id: self.idunn_signer_identity_id.clone(), + signature: self.signature.clone(), + }, + ) + .context("verifying Idunn runtime activation signature") + } + + pub fn validate(&self) -> Result<()> { + self.validate_shape(false) + } + + fn validate_shape(&self, allow_unsigned: bool) -> Result<()> { + if self.schema_version != IDUNN_RUNTIME_ACTIVATION_SCHEMA { + bail!("runtime activation schema is unsupported"); + } + validate_required_sha256( + &self.expected_projection_sha256, + "activation expected projection sha256", + )?; + validate_authority_identifier(&self.runtime_id, "activation runtime id")?; + validate_required_sha256(&self.runtime_instance_id, "runtime instance id")?; + validate_authority_identifier( + &self.activation_signer_identity_id, + "activation signer identity id", + )?; + if self.activation_signer_identity_id + != derive_idunn_runtime_activation_identity_id(&self.activation_signer_public_key)? + { + bail!("runtime activation signer identity does not match its public key"); + } + validate_authority_identifier( + &self.idunn_signer_identity_id, + "Idunn activation signer identity id", + )?; + let signature_is_valid = + self.signature.len() == 64 || (allow_unsigned && self.signature.is_empty()); + if self.issued_at_unix_millis == 0 + || self.signature_algorithm != "ed25519" + || !signature_is_valid + { + bail!("runtime activation issue time or signature is invalid"); + } + Ok(()) + } +} + +/// Unsigned Idunn-owned local file that grants one exact process incarnation +/// state-write authority. It is authoritative only when read through the +/// root-owned admitted path and lock protocol; its bytes carry no route or +/// traffic authority. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "idunn.process_write_lease", + schema = "idunn.process_write_lease.v1" +)] +pub struct IdunnProcessWriteLeaseRecord { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub target: String, + #[cultcache(key = 2)] + pub expected_projection_sha256: String, + #[cultcache(key = 3)] + pub plan_id: String, + #[cultcache(key = 4)] + pub incarnation_id: String, + #[cultcache(key = 5)] + pub sealed_release_id: String, + #[cultcache(key = 6)] + pub activation_witness_sha256: String, + #[cultcache(key = 7)] + pub state_schema_generation: String, + #[cultcache(key = 8)] + pub state_contract_sha256: String, + #[cultcache(key = 9)] + pub runtime_id: String, + #[cultcache(key = 10)] + pub runtime_instance_id: String, + #[cultcache(key = 11)] + pub warming_presence_sha256: String, + #[cultcache(key = 12)] + pub lease_epoch: u64, + #[cultcache(key = 13)] + pub issued_at_unix_millis: u64, +} + +impl IdunnProcessWriteLeaseRecord { + pub fn decode_canonical(payload: &[u8]) -> Result { + if messagepack_array_len(payload) != Some(14) { + bail!("process write lease is not the 14-field positional contract"); + } + let lease: Self = rmp_serde::from_slice(payload).context("decoding process write lease")?; + if rmp_serde::to_vec(&lease)? != payload { + bail!("process write lease is not canonical positional MessagePack"); + } + lease.validate()?; + Ok(lease) + } + + pub fn canonical_bytes(&self) -> Result> { + self.validate()?; + Ok(rmp_serde::to_vec(self)?) + } + + pub fn canonical_sha256(&self) -> Result { + Ok(prefixed_sha256(&self.canonical_bytes()?)) + } + + pub fn validate(&self) -> Result<()> { + if self.schema_version != IDUNN_PROCESS_WRITE_LEASE_SCHEMA { + bail!("process write lease schema is unsupported"); + } + validate_authority_identifier(&self.target, "target")?; + validate_required_sha256( + &self.expected_projection_sha256, + "lease expected projection sha256", + )?; + validate_required_sha256(&self.plan_id, "plan id")?; + validate_authority_identifier(&self.incarnation_id, "incarnation id")?; + validate_required_sha256(&self.sealed_release_id, "sealed release id")?; + validate_required_sha256(&self.activation_witness_sha256, "activation witness sha256")?; + validate_authority_identifier(&self.state_schema_generation, "state schema generation")?; + validate_required_sha256(&self.state_contract_sha256, "state contract sha256")?; + validate_authority_identifier(&self.runtime_id, "runtime id")?; + validate_required_sha256(&self.runtime_instance_id, "runtime instance id")?; + validate_required_sha256(&self.warming_presence_sha256, "warming presence sha256")?; + if self.lease_epoch == 0 || self.issued_at_unix_millis == 0 { + bail!("process write lease epoch or issue time is invalid"); + } + Ok(()) + } +} + +fn messagepack_array_len(payload: &[u8]) -> Option { + match *payload.first()? { + marker @ 0x90..=0x9f => Some(usize::from(marker & 0x0f)), + 0xdc => Some(usize::from(u16::from_be_bytes([ + *payload.get(1)?, + *payload.get(2)?, + ]))), + 0xdd => usize::try_from(u32::from_be_bytes([ + *payload.get(1)?, + *payload.get(2)?, + *payload.get(3)?, + *payload.get(4)?, + ])) + .ok(), + _ => None, + } +} + +fn validate_authority_identifier(value: &str, label: &str) -> Result<()> { + if value.is_empty() + || value.len() > 256 + || value.trim() != value + || value.chars().any(char::is_control) + { + bail!("{label} is empty, oversized, padded, or contains control characters"); + } + Ok(()) +} + +fn validate_optional_identifier(value: &Option, label: &str) -> Result<()> { + if let Some(value) = value { + validate_authority_identifier(value, label)?; + } + Ok(()) +} + +fn validate_source_repository(value: &str) -> Result<()> { + validate_authority_identifier(value, "source repository")?; + let segments: Vec<&str> = value.split('/').collect(); + if segments.len() < 3 + || !segments[0].contains('.') + || segments.iter().any(|segment| { + segment.is_empty() + || matches!(*segment, "." | "..") + || !segment + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + }) + { + bail!("source repository is not a canonical host/owner/repository identity"); + } + Ok(()) +} + +fn validate_endpoint(value: &str, label: &str) -> Result<()> { + if value.is_empty() + || value.len() > 2048 + || value.trim() != value + || value.chars().any(char::is_control) + { + bail!("{label} is empty, oversized, padded, or contains control characters"); + } + Ok(()) +} + +fn validate_optional_endpoint_labeled(value: &Option, label: &str) -> Result<()> { + if let Some(endpoint) = value { + validate_endpoint(endpoint, label)?; + } + Ok(()) +} + +fn validate_optional_endpoint(value: &Option) -> Result<()> { + validate_optional_endpoint_labeled(value, "bound endpoint") +} + +fn validate_runtime_capabilities(capabilities: &[GameCultRuntimeCapability]) -> Result<()> { + if capabilities.len() > MAX_RUNTIME_CAPABILITIES { + bail!("runtime presence capability count exceeds its contract bound"); + } + let mut previous: Option<(&str, &str, &str)> = None; + for capability in capabilities { + validate_authority_identifier(&capability.capability, "capability")?; + validate_authority_identifier(&capability.schema, "capability schema")?; + validate_authority_identifier(&capability.compatibility, "capability compatibility")?; + if capability.capacity == 0 { + bail!("runtime capability capacity is zero"); + } + let identity = ( + capability.capability.as_str(), + capability.schema.as_str(), + capability.compatibility.as_str(), + ); + if previous.is_some_and(|previous| previous >= identity) { + bail!("runtime capabilities are not strictly sorted and unique"); + } + previous = Some(identity); + } + Ok(()) +} + +fn validate_expected_capabilities(capabilities: &[IdunnExpectedCapability]) -> Result<()> { + if capabilities.len() > MAX_RUNTIME_CAPABILITIES { + bail!("Expected capability count exceeds its contract bound"); + } + let mut previous: Option<(&str, &str, &str)> = None; + for capability in capabilities { + validate_authority_identifier(&capability.capability, "Expected capability")?; + validate_authority_identifier(&capability.schema, "Expected capability schema")?; + validate_authority_identifier( + &capability.compatibility, + "Expected capability compatibility", + )?; + if capability.minimum_capacity == 0 { + bail!("Expected capability minimum capacity is zero"); + } + let identity = capability.identity(); + if previous.is_some_and(|previous| previous >= identity) { + bail!("Expected capabilities are not strictly sorted and unique"); + } + previous = Some(identity); + } + Ok(()) +} + +fn validate_expected_dependencies(dependencies: &[IdunnExpectedDependency]) -> Result<()> { + if dependencies.len() > MAX_RUNTIME_DEPENDENCIES { + bail!("Expected dependency count exceeds its contract bound"); + } + let mut previous: Option<(&str, &str, &str)> = None; + for dependency in dependencies { + dependency.validate()?; + let identity = dependency.identity(); + if previous.is_some_and(|previous| previous >= identity) { + bail!("Expected dependencies are not strictly sorted and unique"); + } + previous = Some(identity); + } + Ok(()) +} + +fn validate_dependency_evidence(dependencies: &[OdinRuntimeDependencyEvidence]) -> Result<()> { + if dependencies.len() > MAX_RUNTIME_DEPENDENCIES { + bail!("dependency evidence count exceeds its contract bound"); + } + let mut previous: Option<(&str, &str, &str)> = None; + for dependency in dependencies { + dependency.validate()?; + let identity = dependency.identity(); + if previous.is_some_and(|previous| previous >= identity) { + bail!("dependency evidence is not strictly sorted and unique"); + } + previous = Some(identity); + } + Ok(()) +} + +fn validate_topology_disagreements(disagreements: &[OdinTopologyDisagreement]) -> Result<()> { + if disagreements.len() > MAX_TOPOLOGY_DISAGREEMENTS { + bail!("topology disagreement count exceeds its contract bound"); + } + let mut previous: Option<&str> = None; + for disagreement in disagreements { + disagreement.validate()?; + if previous.is_some_and(|previous| previous >= disagreement.code.as_str()) { + bail!("topology disagreements are not strictly sorted and unique by code"); + } + previous = Some(&disagreement.code); + } + Ok(()) +} + +fn validate_optional_detail(value: &Option, label: &str) -> Result<()> { + if value.as_deref().is_some_and(|value| { + value.is_empty() + || value.len() > 1024 + || value.trim() != value + || value.chars().any(char::is_control) + }) { + bail!("{label} is empty, oversized, padded, or contains control characters"); + } + Ok(()) +} + +fn validate_required_sha256(value: &str, label: &str) -> Result<()> { + if !is_sha256(value) { + bail!("{label} is malformed"); + } + Ok(()) +} + +fn validate_optional_sha256(value: &Option, label: &str) -> Result<()> { + if value.as_deref().is_some_and(|value| !is_sha256(value)) { + bail!("{label} is malformed"); + } + Ok(()) +} + +fn prefixed_sha256(bytes: &[u8]) -> String { + format!("sha256-{:x}", Sha256::digest(bytes)) +} + +fn is_sha256(value: &str) -> bool { + value + .strip_prefix("sha256-") + .is_some_and(|digest| is_lower_hex(digest, 64)) +} + +fn is_lower_hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, GameCultProviderHealthIdentity, + GameCultRuntimePresenceHealthPurpose, GameCultServiceTrustAnchorRecord, + IDUNN_SIGNED_DAEMON_HEALTH_SCHEMA, IdunnServiceIdentity, + OdinRuntimeTopologyCorrelationPurpose, OdinTopologyIdentity, ServiceIdentitySignature, + ServiceIdentitySigner, ServiceSignaturePurpose, derive_service_identity_id, + enroll_service_identity_at, verify_service_identity_signature, + }; + + struct WrongOdinTopologyPurpose; + + impl ServiceSignaturePurpose for WrongOdinTopologyPurpose { + const PURPOSE: &'static [u8] = b"odin.not-runtime-topology-correlation.v1"; + } + + fn digest(byte: char) -> String { + format!("sha256-{}", byte.to_string().repeat(64)) + } + + fn runtime_capability(name: &str) -> GameCultRuntimeCapability { + GameCultRuntimeCapability { + capability: name.into(), + schema: format!("{name}.v1"), + compatibility: "v1".into(), + capacity: 1, + } + } + + fn expected_capability(name: &str) -> IdunnExpectedCapability { + IdunnExpectedCapability { + capability: name.into(), + schema: format!("{name}.v1"), + compatibility: "v1".into(), + minimum_capacity: 1, + } + } + + fn runtime_presence() -> GameCultRuntimePresenceHealthRecord { + GameCultRuntimePresenceHealthRecord { + schema_version: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(), + target: "ghostlight".into(), + expected_projection_sha256: digest('9'), + plan_id: digest('e'), + incarnation_id: "ghostlight/2026-09-02/1".into(), + sealed_release_id: digest('f'), + activation_witness_sha256: digest('a'), + state_schema_generation: Some("world-v2".into()), + state_contract_sha256: Some(digest('b')), + runtime_id: "ghostlight-yggdrasil-1".into(), + runtime_instance_id: digest('8'), + bound_endpoint: Some("http://127.0.0.1:14103".into()), + capabilities: vec![ + runtime_capability("conversation"), + runtime_capability("state"), + ], + health_contract: "ghostlight.runtime-health.v1".into(), + state: "active".into(), + detail: "ready".into(), + write_lease_sha256: Some(digest('c')), + signer_identity_id: "provider-signing-key".into(), + publisher_sequence: 1, + observed_at_unix_millis: 100, + signature_algorithm: "ed25519".into(), + signature: vec![6; 64], + activation_signer_identity_id: "activation-signing-key".into(), + activation_signature: vec![7; 64], + } + } + + fn runtime_activation() -> IdunnRuntimeActivationRecord { + let signer = IdunnRuntimeActivationSigner::from_credential_reader(&[8; 32][..]).unwrap(); + IdunnRuntimeActivationRecord { + schema_version: IDUNN_RUNTIME_ACTIVATION_SCHEMA.into(), + expected_projection_sha256: digest('9'), + runtime_id: "ghostlight-yggdrasil-1".into(), + runtime_instance_id: digest('8'), + activation_signer_identity_id: signer.identity_id(), + activation_signer_public_key: signer.public_key(), + issued_at_unix_millis: 99, + idunn_signer_identity_id: "idunn-signing-key".into(), + signature_algorithm: "ed25519".into(), + signature: vec![5; 64], + } + } + + fn process_write_lease() -> IdunnProcessWriteLeaseRecord { + IdunnProcessWriteLeaseRecord { + schema_version: IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into(), + target: "ghostlight".into(), + expected_projection_sha256: digest('9'), + plan_id: digest('e'), + incarnation_id: "ghostlight/2026-09-02/1".into(), + sealed_release_id: digest('f'), + activation_witness_sha256: digest('a'), + state_schema_generation: "world-v2".into(), + state_contract_sha256: digest('b'), + runtime_id: "ghostlight-yggdrasil-1".into(), + runtime_instance_id: digest('8'), + warming_presence_sha256: digest('d'), + lease_epoch: 1, + issued_at_unix_millis: 101, + } + } + + fn expected_dependency( + kind: &str, + capability: &str, + provider_id: Option<&str>, + ) -> IdunnExpectedDependency { + IdunnExpectedDependency { + kind: kind.into(), + capability: capability.into(), + schema: format!("{capability}.v1"), + compatibility: "v1".into(), + minimum_capacity: 1, + startup: if kind == "bootstrap" { + "before-start".into() + } else { + "before-promotion".into() + }, + provider_id: provider_id.map(str::to_string), + provider_authority: provider_id.map(|_| "managed-incarnation".into()), + provider_expected_projection_sha256: provider_id.map(|_| digest('1')), + provider_endpoint: provider_id.map(|_| "tcp://127.0.0.1:14100".into()), + } + } + + fn expected_incarnation() -> IdunnExpectedIncarnationRecord { + IdunnExpectedIncarnationRecord { + schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(), + target: "ghostlight".into(), + plan_id: digest('2'), + incarnation_id: "ghostlight/2026-09-02/1".into(), + sealed_release_id: digest('3'), + source_repository: "github.com/GameCult/Ghostlight".into(), + source_revision: "4".repeat(40), + recipe_sha256: digest('5'), + runtime_id: "ghostlight-yggdrasil-1".into(), + expected_signer_identity_id: "ghostlight-provider-signing-key".into(), + health_contract: "ghostlight.runtime-health.v1".into(), + artifact_sha256: digest('6'), + state_schema_generation: Some("world-v2".into()), + state_contract_sha256: Some(digest('7')), + write_lease_required: true, + route: Some(IdunnExpectedRoute { + route_id: "ghostlight-public".into(), + transport: "http".into(), + stable_endpoint: "https://ghostlight.gamecult.net".into(), + candidate_endpoint: "http://127.0.0.1:14103".into(), + }), + capabilities: vec![ + expected_capability("conversation"), + expected_capability("state"), + ], + dependencies: vec![ + expected_dependency("shared-infrastructure", "rendezvous", Some("odin-ygg-1")), + expected_dependency("optional", "telemetry", None), + ], + } + } + + fn dependency_evidence(requirement: &IdunnExpectedDependency) -> OdinRuntimeDependencyEvidence { + let selected = requirement.provider_id.is_some(); + OdinRuntimeDependencyEvidence { + kind: requirement.kind.clone(), + capability: requirement.capability.clone(), + schema: requirement.schema.clone(), + compatibility: requirement.compatibility.clone(), + provider_id: requirement.provider_id.clone(), + provider_authority: requirement.provider_authority.clone(), + provider_expected_projection_sha256: requirement + .provider_expected_projection_sha256 + .clone(), + provider_endpoint: requirement.provider_endpoint.clone(), + observed_capacity: selected.then_some(1), + provider_evidence_sha256: selected.then(|| digest('8')), + ready: selected, + } + } + + fn topology_correlation( + expected: &IdunnExpectedIncarnationRecord, + ) -> OdinRuntimeTopologyCorrelationRecord { + OdinRuntimeTopologyCorrelationRecord { + schema_version: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into(), + target: expected.target.clone(), + expected_projection_sha256: expected.canonical_sha256().unwrap(), + expected: true, + current_activation_sha256: Some(digest('9')), + signed_presence_sha256: Some(digest('a')), + observed_presence_state: Some("active".into()), + observed_presence_publisher_sequence: Some(1), + observed_write_lease_sha256: Some(digest('c')), + observed_capabilities: expected + .capabilities + .iter() + .map(|capability| GameCultRuntimeCapability { + capability: capability.capability.clone(), + schema: capability.schema.clone(), + compatibility: capability.compatibility.clone(), + capacity: capability.minimum_capacity, + }) + .collect(), + runtime_id: expected.runtime_id.clone(), + runtime_instance_id: Some(digest('b')), + present: true, + ready: true, + dependencies: expected + .dependencies + .iter() + .map(dependency_evidence) + .collect(), + disagreements: vec![], + signer_identity_id: "odin-topology-signing-key".into(), + publisher_sequence: 1, + observed_at_unix_millis: 102, + signature_algorithm: "ed25519".into(), + signature: vec![7; 64], + } + } + + fn validate_against_current_lease( + receipt: &OdinRuntimeTopologyCorrelationRecord, + expected: &IdunnExpectedIncarnationRecord, + ) -> Result<()> { + let current_lease = digest('c'); + receipt.validate_against_expected(expected, Some(¤t_lease)) + } + + fn topology_anchor() -> GameCultServiceTrustAnchorRecord { + let public_key = vec![9; 32]; + GameCultServiceTrustAnchorRecord { + schema_version: GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(), + trust_anchor_id: "root/odin/runtime-topology".into(), + service_id: "odin".into(), + runtime_id: "odin-yggdrasil-1".into(), + signer_identity_id: derive_service_identity_id::(&public_key) + .unwrap(), + signer_public_key: public_key, + signature_algorithm: "ed25519".into(), + signing_purpose: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SIGNING_PURPOSE.into(), + signed_schema: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into(), + binding_authority: "root".into(), + bound_at_unix_millis: 100, + expires_at_unix_millis: Some(200), + private_state_exposed: false, + } + } + + fn runtime_presence_anchor() -> GameCultServiceTrustAnchorRecord { + let public_key = vec![7; 32]; + GameCultServiceTrustAnchorRecord { + schema_version: GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(), + trust_anchor_id: "root/ghostlight/runtime-presence".into(), + service_id: "ghostlight".into(), + runtime_id: "ghostlight-yggdrasil-1".into(), + signer_identity_id: derive_service_identity_id::( + &public_key, + ) + .unwrap(), + signer_public_key: public_key, + signature_algorithm: "ed25519".into(), + signing_purpose: GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE.into(), + signed_schema: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(), + binding_authority: "root".into(), + bound_at_unix_millis: 100, + expires_at_unix_millis: Some(200), + private_state_exposed: false, + } + } + + struct DualProofFixture { + stable_signer: ServiceIdentitySigner, + activation_signer: IdunnRuntimeActivationSigner, + odin_signer: ServiceIdentitySigner, + idunn_anchor: crate::ServiceIdentityTrustAnchor, + stable_public_key: Vec, + odin_anchor: GameCultServiceTrustAnchorRecord, + expected: IdunnExpectedIncarnationRecord, + activation: IdunnRuntimeActivationRecord, + presence: GameCultRuntimePresenceHealthRecord, + } + + fn dual_proof_fixture(identity_path: &std::path::Path) -> Result { + let stable_signer = + enroll_service_identity_at::(identity_path)?; + let stable_public = stable_signer.trust_anchor()?; + let idunn_signer = enroll_service_identity_at::( + &identity_path.with_extension("idunn.cc"), + )?; + let idunn_anchor = idunn_signer.trust_anchor()?; + let odin_signer = enroll_service_identity_at::( + &identity_path.with_extension("odin.cc"), + )?; + let odin_public = odin_signer.trust_anchor()?; + let mut expected = expected_incarnation(); + expected.expected_signer_identity_id = stable_public.identity_id.clone(); + expected.capabilities[0].minimum_capacity = 2; + let launch = + IdunnRuntimeActivationLaunch::issue(&expected, digest('8'), 99, &idunn_signer)?; + let activation = launch.activation().clone(); + let mut activation_credential = Vec::new(); + assert_eq!( + launch.write_credential(&mut activation_credential)?, + activation + ); + let activation_signer = + IdunnRuntimeActivationSigner::from_credential_reader(&activation_credential[..])?; + + let stable_public_key = stable_public.public_key.clone(); + let odin_anchor = GameCultServiceTrustAnchorRecord { + schema_version: GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(), + trust_anchor_id: "root/odin/runtime-topology".into(), + service_id: "odin".into(), + runtime_id: "odin-yggdrasil-1".into(), + signer_identity_id: odin_public.identity_id, + signer_public_key: odin_public.public_key, + signature_algorithm: "ed25519".into(), + signing_purpose: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SIGNING_PURPOSE.into(), + signed_schema: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into(), + binding_authority: "root".into(), + bound_at_unix_millis: 1, + expires_at_unix_millis: Some(1_000), + private_state_exposed: false, + }; + + let mut presence = runtime_presence(); + presence.target = expected.target.clone(); + presence.plan_id = expected.plan_id.clone(); + presence.incarnation_id = expected.incarnation_id.clone(); + presence.sealed_release_id = expected.sealed_release_id.clone(); + presence.state_schema_generation = expected.state_schema_generation.clone(); + presence.state_contract_sha256 = expected.state_contract_sha256.clone(); + presence.bound_endpoint = expected + .route + .as_ref() + .map(|route| route.candidate_endpoint.clone()); + presence.capabilities = expected + .capabilities + .iter() + .map(|capability| GameCultRuntimeCapability { + capability: capability.capability.clone(), + schema: capability.schema.clone(), + compatibility: capability.compatibility.clone(), + capacity: capability.minimum_capacity, + }) + .collect(); + presence.health_contract = expected.health_contract.clone(); + presence.runtime_id = activation.runtime_id.clone(); + presence.runtime_instance_id = activation.runtime_instance_id.clone(); + presence.expected_projection_sha256 = activation.expected_projection_sha256.clone(); + presence.activation_witness_sha256 = activation.canonical_sha256()?; + presence.signer_identity_id = stable_public.identity_id; + presence.activation_signer_identity_id = activation_signer.identity_id(); + presence.observed_at_unix_millis = 110; + presence.signature.clear(); + presence.activation_signature.clear(); + let proof_payload = presence.canonical_proof_payload()?; + presence.signature = stable_signer + .sign::(&proof_payload) + .signature; + presence.activation_signature = activation_signer.sign_presence_proof(&presence)?; + + Ok(DualProofFixture { + stable_signer, + activation_signer, + odin_signer, + idunn_anchor, + stable_public_key, + odin_anchor, + expected, + activation, + presence, + }) + } + + fn resign_presence(fixture: &mut DualProofFixture) -> Result> { + fixture.presence.signature.clear(); + fixture.presence.activation_signature.clear(); + let proof_payload = fixture.presence.canonical_proof_payload()?; + fixture.presence.signature = fixture + .stable_signer + .sign::(&proof_payload) + .signature; + fixture.presence.activation_signature = fixture + .activation_signer + .sign_presence_proof(&fixture.presence)?; + Ok(rmp_serde::to_vec(&fixture.presence)?) + } + + fn fixture_authority(fixture: &DualProofFixture) -> Result { + verify_runtime_authority( + &fixture.expected, + &fixture.activation, + &fixture.idunn_anchor, + &fixture.stable_public_key, + ) + } + + fn authenticate_fixture( + fixture: &DualProofFixture, + ) -> Result { + authenticate_runtime_presence_claim( + &rmp_serde::to_vec(&fixture.presence)?, + &fixture_authority(fixture)?, + RuntimePresenceAuthenticationContext { + trusted_received_at_unix_millis: 120, + maximum_age_millis: 30, + maximum_future_skew_millis: 5, + }, + ) + } + + fn correlate_fixture(fixture: &DualProofFixture) -> Result { + correlate_runtime_presence_claim( + authenticate_fixture(fixture)?, + &fixture_authority(fixture)?, + ) + } + + fn verify_fixture(fixture: &DualProofFixture) -> Result { + correlate_fixture(fixture)?.into_undisputed_present() + } + + fn authenticated_topology_receipt( + fixture: &DualProofFixture, + presence: &VerifiedRuntimePresence, + present: bool, + disagreements: Vec, + ) -> Result { + let authority = fixture_authority(fixture)?; + let mut receipt = topology_correlation(&fixture.expected); + receipt.current_activation_sha256 = Some(authority.activation_sha256().into()); + receipt.signed_presence_sha256 = Some(presence.signed_presence_sha256().into()); + receipt.observed_presence_state = Some(presence.record().state.clone()); + receipt.observed_presence_publisher_sequence = Some(presence.record().publisher_sequence); + receipt.observed_write_lease_sha256 = presence.record().write_lease_sha256.clone(); + receipt.observed_capabilities = presence.record().capabilities.clone(); + receipt.runtime_instance_id = Some(fixture.activation.runtime_instance_id.clone()); + receipt.present = present; + receipt.ready = present && presence.record().state == "active"; + receipt.disagreements = disagreements; + receipt.signer_identity_id = fixture.odin_anchor.signer_identity_id.clone(); + receipt.signature.clear(); + receipt.signature = fixture + .odin_signer + .sign::(&receipt.unsigned_signature_payload()?) + .signature; + let encoded = receipt.canonical_bytes()?; + authenticate_odin_runtime_topology_correlation( + &encoded, + &authority, + presence.record().write_lease_sha256.as_deref(), + &fixture.odin_anchor.signer_public_key, + OdinTopologyAuthenticationContext { + trusted_received_at_unix_millis: 120, + maximum_age_millis: 30, + maximum_future_skew_millis: 5, + }, + ) + } + + #[test] + fn runtime_authority_contracts_round_trip_as_canonical_positional_records() -> Result<()> { + let presence = runtime_presence(); + presence.validate()?; + let encoded_presence = rmp_serde::to_vec(&presence)?; + assert_eq!(messagepack_array_len(&encoded_presence), Some(24)); + let decoded_presence: GameCultRuntimePresenceHealthRecord = + rmp_serde::from_slice(&encoded_presence)?; + assert_eq!(decoded_presence, presence); + let unsigned = presence.canonical_proof_payload()?; + let unsigned_presence: GameCultRuntimePresenceHealthRecord = + rmp_serde::from_slice(&unsigned)?; + assert!(unsigned_presence.signature.is_empty()); + assert!(unsigned_presence.activation_signature.is_empty()); + + let activation = runtime_activation(); + let encoded_activation = activation.canonical_bytes()?; + assert_eq!(messagepack_array_len(&encoded_activation), Some(10)); + assert_eq!( + IdunnRuntimeActivationRecord::decode_canonical(&encoded_activation)?, + activation + ); + assert_eq!( + activation.canonical_sha256()?, + prefixed_sha256(&encoded_activation) + ); + + let lease = process_write_lease(); + lease.validate()?; + let encoded_lease = lease.canonical_bytes()?; + assert_eq!(messagepack_array_len(&encoded_lease), Some(14)); + assert_eq!( + IdunnProcessWriteLeaseRecord::decode_canonical(&encoded_lease)?, + lease + ); + assert_eq!(lease.canonical_sha256()?, prefixed_sha256(&encoded_lease)); + Ok(()) + } + + #[test] + fn exact_stable_and_activation_proofs_admit_runtime_presence() -> Result<()> { + let temp = tempfile::tempdir()?; + let fixture = dual_proof_fixture(&temp.path().join("runtime-presence.cc"))?; + assert_eq!(fixture.activation.activation_signer_public_key.len(), 32); + let verified = verify_fixture(&fixture)?; + assert_eq!(verified.record(), &fixture.presence); + Ok(()) + } + + #[test] + fn authenticated_expected_disagreements_remain_typed_present_and_not_ready() -> Result<()> { + type Mutation = fn(&mut GameCultRuntimePresenceHealthRecord); + let cases: &[(&str, &str, Mutation)] = &[ + ("target", "target", |value| value.target = "epiphany".into()), + ("projection", "expected-projection", |value| { + value.expected_projection_sha256 = digest('0') + }), + ("plan", "plan-id", |value| value.plan_id = digest('0')), + ("incarnation", "incarnation-id", |value| { + value.incarnation_id = "ghostlight/other/1".into() + }), + ("release", "sealed-release-id", |value| { + value.sealed_release_id = digest('0') + }), + ("runtime", "runtime-id", |value| { + value.runtime_id = "ghostlight-other-runtime".into() + }), + ("process", "runtime-instance-id", |value| { + value.runtime_instance_id = digest('0') + }), + ("endpoint", "bound-endpoint", |value| { + value.bound_endpoint = Some("http://127.0.0.1:14104".into()) + }), + ("health", "health-contract", |value| { + value.health_contract = "ghostlight.other-health.v1".into() + }), + ("state-generation", "state-schema-generation", |value| { + value.state_schema_generation = Some("world-v3".into()) + }), + ("state-contract", "state-contract", |value| { + value.state_contract_sha256 = Some(digest('0')) + }), + ("activation", "activation-witness", |value| { + value.activation_witness_sha256 = digest('0') + }), + ]; + + let temp = tempfile::tempdir()?; + for (name, expected_code, mutate) in cases { + let mut fixture = dual_proof_fixture(&temp.path().join(format!("{name}.cc")))?; + mutate(&mut fixture.presence); + resign_presence(&mut fixture)?; + let correlation = correlate_fixture(&fixture)?; + assert!( + correlation + .disagreements() + .iter() + .any(|disagreement| disagreement.code == *expected_code), + "missing {expected_code} disagreement for {name}" + ); + assert_eq!( + correlation.claim().record().runtime_instance_id, + fixture.presence.runtime_instance_id + ); + assert!(correlation.into_undisputed_present().is_err()); + } + Ok(()) + } + + #[test] + fn provider_owns_observed_capacity_while_expected_owns_only_the_minimum() -> Result<()> { + let temp = tempfile::tempdir()?; + let mut fixture = dual_proof_fixture(&temp.path().join("runtime-presence.cc"))?; + fixture.presence.capabilities[0].capacity = 50; + fixture + .presence + .capabilities + .push(runtime_capability("telemetry")); + resign_presence(&mut fixture)?; + verify_fixture(&fixture)?; + + fixture.presence.capabilities[0].capacity = 1; + fixture + .presence + .capabilities + .retain(|capability| capability.capability != "state"); + resign_presence(&mut fixture)?; + let correlation = correlate_fixture(&fixture)?; + let codes = correlation + .disagreements() + .iter() + .map(|disagreement| disagreement.code.as_str()) + .collect::>(); + assert!(codes.contains(&"expected-capability-000-capacity")); + assert!(codes.contains(&"expected-capability-001-missing")); + assert!(!codes.iter().any(|code| code.contains("unexpected"))); + Ok(()) + } + + #[test] + fn stable_proof_and_provider_key_substitution_fail_closed() -> Result<()> { + let temp = tempfile::tempdir()?; + let mut fixture = dual_proof_fixture(&temp.path().join("runtime-presence.cc"))?; + fixture.presence.detail = "tampered after signing".into(); + assert!(authenticate_fixture(&fixture).is_err()); + + let other_idunn = enroll_service_identity_at::( + &temp.path().join("other-idunn.cc"), + )?; + assert!( + verify_runtime_authority( + &fixture.expected, + &fixture.activation, + &other_idunn.trust_anchor()?, + &fixture.stable_public_key, + ) + .is_err() + ); + + fixture.stable_public_key = vec![9; 32]; + assert!(fixture_authority(&fixture).is_err()); + Ok(()) + } + + #[test] + fn incumbent_stable_key_without_activation_key_cannot_claim_presence() -> Result<()> { + let temp = tempfile::tempdir()?; + let mut fixture = dual_proof_fixture(&temp.path().join("runtime-presence.cc"))?; + fixture.presence.activation_signature = vec![0; 64]; + let proof_payload = fixture.presence.canonical_proof_payload()?; + fixture.presence.signature = fixture + .stable_signer + .sign::(&proof_payload) + .signature; + + let error = verify_fixture(&fixture).unwrap_err(); + assert!(error.to_string().contains("activation proof verification")); + Ok(()) + } + + #[test] + fn activation_cannot_substitute_another_expected_runtime_id() -> Result<()> { + let temp = tempfile::tempdir()?; + let mut fixture = dual_proof_fixture(&temp.path().join("runtime-presence.cc"))?; + fixture.activation.runtime_id = "ghostlight-yggdrasil-2".into(); + fixture.presence.runtime_id = fixture.activation.runtime_id.clone(); + fixture.presence.activation_witness_sha256 = fixture.activation.canonical_sha256()?; + + // The stable service key can re-sign the altered canonical statement, + // but the activation proof still came from the other runtime id. + let proof_payload = fixture.presence.canonical_proof_payload()?; + fixture.presence.signature = fixture + .stable_signer + .sign::(&proof_payload) + .signature; + let error = fixture_authority(&fixture).unwrap_err(); + assert!(error.to_string().contains("current Expected")); + Ok(()) + } + + #[test] + fn idunn_signature_prevents_provider_minted_activation() -> Result<()> { + let temp = tempfile::tempdir()?; + let mut fixture = dual_proof_fixture(&temp.path().join("runtime-presence.cc"))?; + fixture.activation.issued_at_unix_millis += 1; + fixture.presence.activation_witness_sha256 = fixture.activation.canonical_sha256()?; + resign_presence(&mut fixture)?; + let error = fixture_authority(&fixture).unwrap_err(); + assert!( + error + .to_string() + .contains("Idunn runtime activation signature") + ); + Ok(()) + } + + #[test] + fn authenticated_odin_receipt_is_fresh_evidence_not_replay_authority() -> Result<()> { + let temp = tempfile::tempdir()?; + let fixture = dual_proof_fixture(&temp.path().join("runtime-presence.cc"))?; + let authority = fixture_authority(&fixture)?; + let presence = verify_fixture(&fixture)?; + let accepted = authenticated_topology_receipt(&fixture, &presence, true, Vec::new())?; + assert_eq!( + accepted.record().observed_presence_publisher_sequence, + Some(fixture.presence.publisher_sequence) + ); + assert_eq!( + accepted.record().signed_presence_sha256.as_deref(), + Some(presence.signed_presence_sha256()) + ); + + let mut tampered = accepted.record().clone(); + tampered.signature = vec![0; 64]; + assert!( + authenticate_odin_runtime_topology_correlation( + &tampered.canonical_bytes()?, + &authority, + presence.record().write_lease_sha256.as_deref(), + &fixture.odin_anchor.signer_public_key, + OdinTopologyAuthenticationContext { + trusted_received_at_unix_millis: 120, + maximum_age_millis: 30, + maximum_future_skew_millis: 5, + }, + ) + .is_err() + ); + assert!( + authenticate_odin_runtime_topology_correlation( + accepted.canonical_bytes(), + &authority, + presence.record().write_lease_sha256.as_deref(), + &fixture.odin_anchor.signer_public_key, + OdinTopologyAuthenticationContext { + trusted_received_at_unix_millis: 200, + maximum_age_millis: 30, + maximum_future_skew_millis: 5, + }, + ) + .is_err() + ); + Ok(()) + } + + #[test] + fn separate_launches_receive_distinct_activation_identities() -> Result<()> { + let temp = tempfile::tempdir()?; + let idunn = + enroll_service_identity_at::(&temp.path().join("idunn.cc"))?; + let expected = expected_incarnation(); + let first = IdunnRuntimeActivationLaunch::issue(&expected, digest('8'), 99, &idunn)?; + let second = IdunnRuntimeActivationLaunch::issue(&expected, digest('9'), 100, &idunn)?; + assert_ne!( + first.activation().activation_signer_identity_id, + second.activation().activation_signer_identity_id + ); + Ok(()) + } + + #[test] + fn trusted_time_rejects_stale_and_future_presence() -> Result<()> { + let temp = tempfile::tempdir()?; + let mut fixture = dual_proof_fixture(&temp.path().join("runtime-presence.cc"))?; + let authority = fixture_authority(&fixture)?; + let canonical = rmp_serde::to_vec(&fixture.presence)?; + assert!( + authenticate_runtime_presence_claim( + &canonical, + &authority, + RuntimePresenceAuthenticationContext { + trusted_received_at_unix_millis: 200, + maximum_age_millis: 10, + maximum_future_skew_millis: 5, + }, + ) + .is_err() + ); + + fixture.presence.observed_at_unix_millis = 126; + resign_presence(&mut fixture)?; + assert!( + authenticate_runtime_presence_claim( + &rmp_serde::to_vec(&fixture.presence)?, + &authority, + RuntimePresenceAuthenticationContext { + trusted_received_at_unix_millis: 120, + maximum_age_millis: 30, + maximum_future_skew_millis: 5, + }, + ) + .is_err() + ); + + Ok(()) + } + + #[test] + fn runtime_authority_decoders_reject_malformed_and_noncanonical_bytes() -> Result<()> { + let temp = tempfile::tempdir()?; + let fixture = dual_proof_fixture(&temp.path().join("runtime-presence.cc"))?; + assert!( + authenticate_runtime_presence_claim( + &[0x91, 0xc0], + &fixture_authority(&fixture)?, + RuntimePresenceAuthenticationContext { + trusted_received_at_unix_millis: 120, + maximum_age_millis: 30, + maximum_future_skew_millis: 5, + }, + ) + .is_err() + ); + assert!(IdunnRuntimeActivationRecord::decode_canonical(&[0x91, 0xc0]).is_err()); + assert!(IdunnProcessWriteLeaseRecord::decode_canonical(&[0x91, 0xc0]).is_err()); + + let mut legacy_presence = fixture.presence.clone(); + legacy_presence.schema_version = "gamecult.runtime_presence_health.v1".into(); + assert!( + authenticate_runtime_presence_claim( + &rmp_serde::to_vec(&legacy_presence)?, + &fixture_authority(&fixture)?, + RuntimePresenceAuthenticationContext { + trusted_received_at_unix_millis: 120, + maximum_age_millis: 30, + maximum_future_skew_millis: 5, + }, + ) + .is_err() + ); + let mut legacy_activation = fixture.activation.clone(); + legacy_activation.schema_version = "idunn.runtime_activation.v1".into(); + assert!( + IdunnRuntimeActivationRecord::decode_canonical(&rmp_serde::to_vec(&legacy_activation)?) + .is_err() + ); + let mut legacy_expected = fixture.expected.clone(); + legacy_expected.schema_version = "idunn.expected_incarnation.v1".into(); + assert!( + IdunnExpectedIncarnationRecord::decode_canonical(&rmp_serde::to_vec(&legacy_expected)?) + .is_err() + ); + let mut legacy_topology = topology_correlation(&fixture.expected); + legacy_topology.schema_version = "odin.runtime_topology_correlation.v1".into(); + assert!( + OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload( + &rmp_serde::to_vec(&legacy_topology)?, + ) + .is_err() + ); + + let presence = rmp_serde::to_vec(&runtime_presence())?; + assert_eq!(&presence[..3], &[0xdc, 0, 24]); + let mut noncanonical_presence = vec![0xdd, 0, 0, 0, 24]; + noncanonical_presence.extend_from_slice(&presence[3..]); + assert!( + authenticate_runtime_presence_claim( + &noncanonical_presence, + &fixture_authority(&fixture)?, + RuntimePresenceAuthenticationContext { + trusted_received_at_unix_millis: 120, + maximum_age_millis: 30, + maximum_future_skew_millis: 5, + }, + ) + .is_err() + ); + + let activation = runtime_activation().canonical_bytes()?; + assert_eq!(activation[0], 0x9a); + let mut noncanonical_activation = vec![0xdc, 0, 10]; + noncanonical_activation.extend_from_slice(&activation[1..]); + assert!(IdunnRuntimeActivationRecord::decode_canonical(&noncanonical_activation).is_err()); + + let lease = process_write_lease().canonical_bytes()?; + assert_eq!(lease[0], 0x9e); + let mut noncanonical_lease = vec![0xdc, 0, 14]; + noncanonical_lease.extend_from_slice(&lease[1..]); + assert!(IdunnProcessWriteLeaseRecord::decode_canonical(&noncanonical_lease).is_err()); + Ok(()) + } + + #[test] + fn runtime_presence_refuses_capability_and_warming_lease_ambiguity() { + let mut value = runtime_presence(); + value.capabilities.reverse(); + assert!(value.validate().is_err()); + + let mut value = runtime_presence(); + let mut duplicate = runtime_capability("state"); + duplicate.capacity = 2; + value.capabilities.push(duplicate); + assert!(value.validate().is_err()); + + let mut value = runtime_presence(); + value.capabilities[0].capacity = 0; + assert!(value.validate().is_err()); + + let mut value = runtime_presence(); + value.state = "warming".into(); + assert!(value.validate().is_err()); + value.write_lease_sha256 = None; + assert!(value.validate().is_ok()); + + let mut value = runtime_presence(); + value.state_schema_generation = None; + assert!(value.validate().is_err()); + value.state_contract_sha256 = None; + assert!(value.validate().is_err()); + value.write_lease_sha256 = None; + assert!(value.validate().is_ok()); + } + + #[test] + fn runtime_authority_refuses_malformed_digest_process_and_epoch_bindings() { + let mut value = runtime_presence(); + value.activation_witness_sha256 = digest('A'); + assert!(value.validate().is_err()); + + let mut value = runtime_presence(); + value.plan_id = "plan-1".into(); + assert!(value.validate().is_err()); + + let mut value = runtime_presence(); + value.sealed_release_id = "release-1".into(); + assert!(value.validate().is_err()); + + let mut value = runtime_presence(); + value.runtime_instance_id = "systemd-invocation-1".into(); + assert!(value.validate().is_err()); + + let mut value = runtime_presence(); + value.expected_projection_sha256 = "expected-1".into(); + assert!(value.validate().is_err()); + + let mut value = runtime_presence(); + value.write_lease_sha256 = Some("lease-1".into()); + assert!(value.validate().is_err()); + + let mut value = process_write_lease(); + value.warming_presence_sha256 = digest('D'); + assert!(value.validate().is_err()); + + let mut value = process_write_lease(); + value.plan_id = "plan-1".into(); + assert!(value.validate().is_err()); + + let mut value = process_write_lease(); + value.runtime_instance_id = "pid-4242".into(); + assert!(value.validate().is_err()); + + let mut value = process_write_lease(); + value.lease_epoch = 0; + assert!(value.validate().is_err()); + + let mut value = runtime_activation(); + value.runtime_instance_id = digest('A'); + assert!(value.validate().is_err()); + + let mut value = runtime_activation(); + value.expected_projection_sha256 = "expected-1".into(); + assert!(value.validate().is_err()); + } + + #[test] + fn runtime_presence_trust_anchor_is_provider_profile_and_purpose_bound() -> Result<()> { + let anchor = runtime_presence_anchor(); + anchor.validate()?; + + let mut value = anchor.clone(); + value.signing_purpose = "idunn.signed_daemon_health.v1".into(); + assert!(value.validate().is_err()); + + let mut value = anchor.clone(); + value.signed_schema = IDUNN_SIGNED_DAEMON_HEALTH_SCHEMA.into(); + assert!(value.validate().is_err()); + + let mut value = anchor.clone(); + value.signing_purpose = "gamecult.runtime_presence_health.v1".into(); + value.signed_schema = "gamecult.runtime_presence_health.v1".into(); + assert!(value.validate().is_err()); + + let mut value = anchor; + value.signer_identity_id = + derive_service_identity_id::(&value.signer_public_key)?; + assert!(value.validate().is_err()); + Ok(()) + } + + #[test] + fn process_write_lease_cannot_encode_route_or_traffic_authority() -> Result<()> { + let canonical = process_write_lease().canonical_bytes()?; + assert_eq!(messagepack_array_len(&canonical), Some(14)); + + for forbidden in ["route", "traffic"] { + let mut with_extra_authority = vec![0xdc, 0, 15]; + with_extra_authority.extend_from_slice(&canonical[1..]); + with_extra_authority.extend_from_slice(&rmp_serde::to_vec(&forbidden)?); + assert!(IdunnProcessWriteLeaseRecord::decode_canonical(&with_extra_authority).is_err()); + } + Ok(()) + } + + #[test] + fn expected_and_topology_correlation_round_trip_canonically() -> Result<()> { + let expected = expected_incarnation(); + let expected_bytes = expected.canonical_bytes()?; + assert_eq!(&expected_bytes[..3], &[0xdc, 0, 18]); + assert_eq!( + IdunnExpectedIncarnationRecord::decode_canonical(&expected_bytes)?, + expected + ); + assert_eq!( + expected.canonical_sha256()?, + prefixed_sha256(&expected_bytes) + ); + + let receipt = topology_correlation(&expected); + validate_against_current_lease(&receipt, &expected)?; + let receipt_bytes = receipt.canonical_bytes()?; + assert_eq!(&receipt_bytes[..3], &[0xdc, 0, 21]); + let (decoded, unsigned) = + OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload(&receipt_bytes)?; + assert_eq!(decoded, receipt); + let unsigned_receipt: OdinRuntimeTopologyCorrelationRecord = + rmp_serde::from_slice(&unsigned)?; + assert!(unsigned_receipt.signature.is_empty()); + assert_eq!(unsigned, receipt.unsigned_signature_payload()?); + assert_eq!(receipt.canonical_sha256()?, prefixed_sha256(&receipt_bytes)); + Ok(()) + } + + #[test] + fn expected_and_topology_decoders_reject_noncanonical_or_extended_records() -> Result<()> { + assert!(IdunnExpectedIncarnationRecord::decode_canonical(&[0x91, 0xc0]).is_err()); + assert!( + OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload(&[0x91, 0xc0]) + .is_err() + ); + + let expected = expected_incarnation().canonical_bytes()?; + let mut noncanonical_expected = vec![0xdd, 0, 0, 0, 18]; + noncanonical_expected.extend_from_slice(&expected[3..]); + assert!(IdunnExpectedIncarnationRecord::decode_canonical(&noncanonical_expected).is_err()); + + let receipt = topology_correlation(&expected_incarnation()).canonical_bytes()?; + let mut noncanonical_receipt = vec![0xdd, 0, 0, 0, 21]; + noncanonical_receipt.extend_from_slice(&receipt[3..]); + assert!( + OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload( + &noncanonical_receipt, + ) + .is_err() + ); + + for forbidden in ["private-host-path", "runner-secret"] { + let mut extended = vec![0xdc, 0, 19]; + extended.extend_from_slice(&expected[3..]); + extended.extend_from_slice(&rmp_serde::to_vec(&forbidden)?); + assert!(IdunnExpectedIncarnationRecord::decode_canonical(&extended).is_err()); + } + Ok(()) + } + + #[test] + fn expected_refuses_partial_state_and_noncanonical_claim_sets() { + let mut value = expected_incarnation(); + value.state_contract_sha256 = None; + assert!(value.validate().is_err()); + + let mut value = expected_incarnation(); + value.state_schema_generation = None; + assert!(value.validate().is_err()); + + let mut value = expected_incarnation(); + value.state_schema_generation = None; + value.state_contract_sha256 = None; + assert!(value.validate().is_err()); + value.write_lease_required = false; + assert!(value.validate().is_ok()); + + let mut value = expected_incarnation(); + value.capabilities.reverse(); + assert!(value.validate().is_err()); + + let mut value = expected_incarnation(); + value.capabilities.push(expected_capability("state")); + assert!(value.validate().is_err()); + + let mut value = expected_incarnation(); + value.dependencies.reverse(); + assert!(value.validate().is_err()); + + let mut value = expected_incarnation(); + value.dependencies.push(value.dependencies[1].clone()); + assert!(value.validate().is_err()); + + let mut value = expected_incarnation(); + let mut duplicate = value.dependencies[1].clone(); + duplicate.kind = "required".into(); + value.dependencies.push(duplicate); + assert!(value.validate().is_err()); + + let mut value = expected_incarnation(); + value.dependencies[0].provider_authority = None; + assert!(value.validate().is_err()); + + let mut value = expected_incarnation(); + value.source_revision = "A".repeat(40); + assert!(value.validate().is_err()); + + for private_source in [ + "F:\\Projects\\Ghostlight", + "/srv/build/Ghostlight", + "https://token@github.com/GameCult/Ghostlight", + ] { + let mut value = expected_incarnation(); + value.source_repository = private_source.into(); + assert!(value.validate().is_err()); + } + + let mut value = expected_incarnation(); + let stable_endpoint = value.route.as_ref().unwrap().stable_endpoint.clone(); + value.route.as_mut().unwrap().candidate_endpoint = stable_endpoint; + assert!(value.validate().is_err()); + } + + #[test] + fn expected_route_keeps_rudp_distinct_and_scheme_exact() { + let mut value = expected_incarnation(); + value.route = Some(IdunnExpectedRoute { + route_id: "odin-rendezvous".into(), + transport: "rudp".into(), + stable_endpoint: "rudp://10.77.0.1:17871".into(), + candidate_endpoint: "rudp://127.0.0.1:24171".into(), + }); + assert!(value.validate().is_ok()); + + value.route.as_mut().unwrap().candidate_endpoint = "tcp://127.0.0.1:24171".into(); + assert!(value.validate().is_err()); + + value.route.as_mut().unwrap().candidate_endpoint = "udp://127.0.0.1:24171".into(); + assert!(value.validate().is_err()); + } + + #[test] + fn topology_correlation_refuses_expected_substitution_and_dependency_omission() { + let expected = expected_incarnation(); + + let mut value = topology_correlation(&expected); + value.target = "epiphany".into(); + assert!(value.validate().is_ok()); + assert!(validate_against_current_lease(&value, &expected).is_err()); + + let mut value = topology_correlation(&expected); + value.runtime_id = "ghostlight-other-runtime".into(); + assert!(validate_against_current_lease(&value, &expected).is_err()); + + let mut value = topology_correlation(&expected); + value.expected_projection_sha256 = digest('c'); + assert!(validate_against_current_lease(&value, &expected).is_err()); + + let mut value = topology_correlation(&expected); + value.dependencies.pop(); + assert!(value.validate().is_ok()); + assert!(validate_against_current_lease(&value, &expected).is_err()); + + let mut value = topology_correlation(&expected); + value.dependencies[0].provider_id = Some("odin-substitute".into()); + assert!(value.validate().is_ok()); + assert!(validate_against_current_lease(&value, &expected).is_err()); + + let mut value = topology_correlation(&expected); + value.dependencies[0].kind = "required".into(); + assert!(value.validate().is_ok()); + assert!(validate_against_current_lease(&value, &expected).is_err()); + + let mut value = topology_correlation(&expected); + value.dependencies[0].observed_capacity = Some(0); + assert!(value.validate().is_err()); + + let mut value = topology_correlation(&expected); + value.dependencies[0].observed_capacity = Some(1); + let mut stricter = expected.clone(); + stricter.dependencies[0].minimum_capacity = 2; + value.expected_projection_sha256 = stricter.canonical_sha256().unwrap(); + assert!(validate_against_current_lease(&value, &stricter).is_err()); + } + + #[test] + fn topology_correlation_requires_explicit_coherent_partial_states() { + let expected = expected_incarnation(); + let mut value = topology_correlation(&expected); + value.signed_presence_sha256 = None; + value.observed_presence_state = None; + value.observed_presence_publisher_sequence = None; + value.observed_write_lease_sha256 = None; + value.observed_capabilities.clear(); + value.present = false; + value.ready = false; + assert!(value.validate().is_err()); + + value.disagreements.push(OdinTopologyDisagreement { + code: "presence-missing".into(), + expected: Some("signed-runtime-presence".into()), + observed: None, + }); + assert!(value.validate().is_ok()); + + let mut value = topology_correlation(&expected); + value.runtime_instance_id = None; + assert!(value.validate().is_err()); + + let mut value = topology_correlation(&expected); + value.current_activation_sha256 = None; + value.present = true; + value.ready = false; + value.disagreements.push(OdinTopologyDisagreement { + code: "activation-missing".into(), + expected: Some("current-activation".into()), + observed: None, + }); + assert!(value.validate().is_err()); + + let mut value = topology_correlation(&expected); + value.expected = false; + value.present = false; + value.ready = false; + assert!(value.validate().is_err()); + } + + #[test] + fn topology_correlation_refuses_unsorted_or_duplicate_claims() { + let expected = expected_incarnation(); + let mut value = topology_correlation(&expected); + value.dependencies.reverse(); + assert!(value.validate().is_err()); + + let mut value = topology_correlation(&expected); + value.dependencies.push(value.dependencies[1].clone()); + assert!(value.validate().is_err()); + + let mut value = topology_correlation(&expected); + value.ready = false; + value.disagreements = vec![ + OdinTopologyDisagreement { + code: "schema-mismatch".into(), + expected: Some("state.v2".into()), + observed: Some("state.v1".into()), + }, + OdinTopologyDisagreement { + code: "endpoint-mismatch".into(), + expected: Some("route-a".into()), + observed: Some("route-b".into()), + }, + ]; + assert!(value.validate().is_err()); + + value.disagreements[1].code = "schema-mismatch".into(); + assert!(value.validate().is_err()); + } + + #[test] + fn topology_correlation_preserves_warming_and_exact_write_lease_authority() { + let expected = expected_incarnation(); + let value = topology_correlation(&expected); + validate_against_current_lease(&value, &expected).unwrap(); + assert!( + value + .validate_against_expected(&expected, Some(&digest('d'))) + .is_err() + ); + assert!(value.validate_against_expected(&expected, None).is_err()); + + let mut digest_only_ready = topology_correlation(&expected); + digest_only_ready.observed_write_lease_sha256 = None; + digest_only_ready.validate().unwrap(); + assert!( + digest_only_ready + .validate_against_expected(&expected, Some(&digest('c'))) + .is_err() + ); + + let mut warming = topology_correlation(&expected); + warming.observed_presence_state = Some("warming".into()); + warming.ready = false; + assert!(warming.validate().is_err()); + warming.observed_write_lease_sha256 = None; + warming.validate().unwrap(); + warming.validate_against_expected(&expected, None).unwrap(); + warming.ready = true; + assert!(warming.validate().is_err()); + + let mut partial = topology_correlation(&expected); + partial.observed_presence_state = None; + assert!(partial.validate().is_err()); + let mut partial = topology_correlation(&expected); + partial.signed_presence_sha256 = None; + assert!(partial.validate().is_err()); + + let mut stateless = expected.clone(); + stateless.state_schema_generation = None; + stateless.state_contract_sha256 = None; + stateless.write_lease_required = false; + let mut stateless_receipt = topology_correlation(&stateless); + stateless_receipt.observed_write_lease_sha256 = None; + stateless_receipt + .validate_against_expected(&stateless, None) + .unwrap(); + stateless_receipt.observed_write_lease_sha256 = Some(digest('c')); + assert!( + stateless_receipt + .validate_against_expected(&stateless, Some(&digest('c'))) + .is_err() + ); + } + + #[test] + fn topology_correlation_cannot_manufacture_ready() { + let expected = expected_incarnation(); + let mut value = topology_correlation(&expected); + value.dependencies[0].ready = false; + assert!(value.validate().is_err()); + + let mut value = topology_correlation(&expected); + value.disagreements.push(OdinTopologyDisagreement { + code: "capability-mismatch".into(), + expected: Some("conversation.v1".into()), + observed: Some("conversation.v0".into()), + }); + assert!(value.validate().is_err()); + + let mut value = topology_correlation(&expected); + value.present = false; + value.disagreements.push(OdinTopologyDisagreement { + code: "identity-mismatch".into(), + expected: Some("expected-runtime".into()), + observed: Some("other-runtime".into()), + }); + assert!(value.validate().is_err()); + + let mut value = topology_correlation(&expected); + value.dependencies[0].provider_evidence_sha256 = None; + assert!(value.validate().is_err()); + + let mut missing_capability = topology_correlation(&expected); + missing_capability.observed_capabilities.pop(); + assert!(missing_capability.validate().is_ok()); + assert!( + missing_capability + .validate_against_expected(&expected, Some(&digest('c'))) + .is_err() + ); + missing_capability.present = true; + missing_capability.ready = false; + missing_capability.disagreements = vec![OdinTopologyDisagreement { + code: "generic-mismatch".into(), + expected: Some("expected".into()), + observed: Some("observed".into()), + }]; + assert!( + missing_capability + .validate_against_expected(&expected, Some(&digest('c'))) + .is_err() + ); + correlate_capabilities( + &mut missing_capability.disagreements, + &expected.capabilities, + &missing_capability.observed_capabilities, + ); + missing_capability + .disagreements + .sort_by(|left, right| left.code.cmp(&right.code)); + missing_capability + .validate_against_expected(&expected, Some(&digest('c'))) + .unwrap(); + + let mut additional_capability = topology_correlation(&expected); + additional_capability + .observed_capabilities + .push(runtime_capability("telemetry")); + additional_capability + .validate_against_expected(&expected, Some(&digest('c'))) + .unwrap(); + } + + #[test] + fn topology_signature_is_exact_and_purpose_bound() -> Result<()> { + let temp = tempfile::tempdir()?; + let signer = enroll_service_identity_at::( + &temp.path().join("odin-topology.cc"), + )?; + let anchor = signer.trust_anchor()?; + let expected = expected_incarnation(); + let mut receipt = topology_correlation(&expected); + receipt.signer_identity_id = anchor.identity_id.clone(); + receipt.signature.clear(); + let unsigned = receipt.unsigned_signature_payload()?; + let proof = signer.sign::(&unsigned); + receipt.signature = proof.signature.clone(); + + let encoded = receipt.canonical_bytes()?; + let (decoded, decoded_unsigned) = + OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload(&encoded)?; + verify_service_identity_signature::< + OdinTopologyIdentity, + OdinRuntimeTopologyCorrelationPurpose, + >( + &anchor, + &decoded_unsigned, + &ServiceIdentitySignature { + identity_id: decoded.signer_identity_id, + signature: decoded.signature, + }, + )?; + + let mut substituted = decoded_unsigned.clone(); + substituted.push(0); + assert!( + verify_service_identity_signature::< + OdinTopologyIdentity, + OdinRuntimeTopologyCorrelationPurpose, + >(&anchor, &substituted, &proof) + .is_err() + ); + + let wrong_purpose = signer.sign::(&decoded_unsigned); + assert!( + verify_service_identity_signature::< + OdinTopologyIdentity, + OdinRuntimeTopologyCorrelationPurpose, + >(&anchor, &decoded_unsigned, &wrong_purpose) + .is_err() + ); + Ok(()) + } + + #[test] + fn topology_trust_anchor_is_odin_profile_and_purpose_bound() -> Result<()> { + let anchor = topology_anchor(); + anchor.validate()?; + + let mut value = anchor.clone(); + value.service_id = "idunn".into(); + assert!(value.validate().is_err()); + + let mut value = anchor.clone(); + value.signing_purpose = GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE.into(); + assert!(value.validate().is_err()); + + let mut value = anchor.clone(); + value.signed_schema = GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(); + assert!(value.validate().is_err()); + + let mut value = anchor; + value.signer_identity_id = + derive_service_identity_id::(&value.signer_public_key)?; + assert!(value.validate().is_err()); + Ok(()) + } +} diff --git a/packages/cultnet-rs/src/service_identity.rs b/packages/cultnet-rs/src/service_identity.rs new file mode 100644 index 00000000..81b91a8c --- /dev/null +++ b/packages/cultnet-rs/src/service_identity.rs @@ -0,0 +1,920 @@ +use anyhow::{Context, Result, anyhow, bail}; +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore}; +use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +use rand::RngCore; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::io::{Read, Write}; +use std::marker::PhantomData; +use std::path::Path; +#[cfg(windows)] +use zeroize::Zeroize; +use zeroize::Zeroizing; + +pub const WINDOWS_SERVICE_IDENTITY_ASSURANCE: &str = "os_user_installation_bound_best_effort"; +pub const LINUX_SERVICE_IDENTITY_ASSURANCE: &str = "os_installation_file_bound_cloneable_baseline"; + +/// Fixes every authority-bearing name at the call site. A service cannot open +/// another service's identity by supplying a convenient runtime string. +pub trait ServiceIdentityProfile: Send + Sync + 'static { + const PRIVATE_TYPE: &'static str; + const PRIVATE_SCHEMA: &'static str; + const PRIVATE_KEY: &'static str; + const TRUST_ANCHOR_TYPE: &'static str; + const TRUST_ANCHOR_SCHEMA: &'static str; + const TRUST_ANCHOR_KEY: &'static str; + const ID_DOMAIN: &'static [u8]; + const SIGNATURE_DOMAIN: &'static [u8]; + const PROTECTOR_CONTEXT: &'static str; +} + +/// A purpose is a type, not caller-provided prose. Protocol implementations +/// define one zero-sized type per signed statement kind. +pub trait ServiceSignaturePurpose: Send + Sync + 'static { + const PURPOSE: &'static [u8]; +} + +pub enum IdunnServiceIdentity {} + +/// Odin-owned identity dedicated to signed Expected/Present/Ready topology +/// correlation. It is not a provider-health key and cannot issue Idunn +/// admission or lifecycle authority. +pub enum OdinTopologyIdentity {} + +pub struct OdinRuntimeTopologyCorrelationPurpose; + +impl ServiceSignaturePurpose for OdinRuntimeTopologyCorrelationPurpose { + const PURPOSE: &'static [u8] = b"odin.runtime_topology_correlation.v2"; +} + +impl ServiceIdentityProfile for OdinTopologyIdentity { + const PRIVATE_TYPE: &'static str = "odin.topology_identity.private.v1"; + const PRIVATE_SCHEMA: &'static str = "odin.topology_identity.private.v1"; + const PRIVATE_KEY: &'static str = "odin-topology-identity"; + const TRUST_ANCHOR_TYPE: &'static str = "odin.topology_identity.trust_anchor.v1"; + const TRUST_ANCHOR_SCHEMA: &'static str = "odin.topology_identity.trust_anchor.v1"; + const TRUST_ANCHOR_KEY: &'static str = "odin-topology-identity-public"; + const ID_DOMAIN: &'static [u8] = b"odin.topology-identity.id.v1\0"; + const SIGNATURE_DOMAIN: &'static [u8] = b"odin.topology-identity.signature.v1\0"; + const PROTECTOR_CONTEXT: &'static str = "odin-topology-identity-v1"; +} + +/// Root-operated identity dedicated to deployment-brake release grants. The +/// Idunn daemon receives only this profile's public trust anchor; opening the +/// private store is a provisioning operation, never daemon startup work. +pub enum IdunnDeploymentBrakeOperatorIdentity {} + +pub struct IdunnDeploymentBrakeReleasePurpose; + +impl ServiceSignaturePurpose + for IdunnDeploymentBrakeReleasePurpose +{ + const PURPOSE: &'static [u8] = b"idunn.deployment-release.v1"; +} + +impl ServiceIdentityProfile for IdunnDeploymentBrakeOperatorIdentity { + const PRIVATE_TYPE: &'static str = "idunn.deployment_brake_operator.private.v1"; + const PRIVATE_SCHEMA: &'static str = "idunn.deployment_brake_operator.private.v1"; + const PRIVATE_KEY: &'static str = "idunn-deployment-brake-operator"; + const TRUST_ANCHOR_TYPE: &'static str = "idunn.deployment_brake_operator.trust_anchor.v1"; + const TRUST_ANCHOR_SCHEMA: &'static str = "idunn.deployment_brake_operator.trust_anchor.v1"; + const TRUST_ANCHOR_KEY: &'static str = "idunn-deployment-brake-operator-public"; + const ID_DOMAIN: &'static [u8] = b"idunn.deployment-brake-operator.id.v1\0"; + const SIGNATURE_DOMAIN: &'static [u8] = b"idunn.deployment-brake-operator.signature.v1\0"; + const PROTECTOR_CONTEXT: &'static str = "idunn-deployment-brake-operator-v1"; +} + +/// Dedicated provider-owned identity for generic daemon-health statements. +/// It is intentionally independent of any one provider runtime or repository. +pub enum GameCultProviderHealthIdentity {} + +/// The only generic health statement purpose accepted from provider-health +/// identities by Idunn admission. +pub struct IdunnSignedDaemonHealthPurpose; + +impl ServiceSignaturePurpose for IdunnSignedDaemonHealthPurpose { + const PURPOSE: &'static [u8] = b"idunn.signed_daemon_health.v1"; +} + +/// Provider-owned runtime presence and health. This is deliberately distinct +/// from the legacy daemon-health purpose so an old signature cannot acquire +/// deployment-incarnation authority by substitution. +pub struct GameCultRuntimePresenceHealthPurpose; + +impl ServiceSignaturePurpose + for GameCultRuntimePresenceHealthPurpose +{ + const PURPOSE: &'static [u8] = b"gamecult.runtime_presence_health.v2"; +} + +impl ServiceIdentityProfile for GameCultProviderHealthIdentity { + const PRIVATE_TYPE: &'static str = "gamecult.provider_health_identity.private.v1"; + const PRIVATE_SCHEMA: &'static str = "gamecult.provider_health_identity.private.v1"; + const PRIVATE_KEY: &'static str = "gamecult-provider-health-identity"; + const TRUST_ANCHOR_TYPE: &'static str = "gamecult.provider_health_identity.trust_anchor.v1"; + const TRUST_ANCHOR_SCHEMA: &'static str = "gamecult.provider_health_identity.trust_anchor.v1"; + const TRUST_ANCHOR_KEY: &'static str = "gamecult-provider-health-identity-public"; + const ID_DOMAIN: &'static [u8] = b"gamecult.provider-health.identity.v1\0"; + const SIGNATURE_DOMAIN: &'static [u8] = b"gamecult.provider-health.signature.v1\0"; + const PROTECTOR_CONTEXT: &'static str = "gamecult-provider-health-identity-v1"; +} + +/// The only signing purpose accepted for Idunn's public projection of a +/// provider-authenticated health admission. Keeping this profile here makes +/// purpose selection a compile-time protocol choice rather than caller text. +pub struct IdunnAuthenticatedProviderHealthProjectionPurpose; + +impl ServiceSignaturePurpose + for IdunnAuthenticatedProviderHealthProjectionPurpose +{ + const PURPOSE: &'static [u8] = b"idunn.authenticated-provider-health-projection.v1"; +} + +/// Idunn's stable identity signs every activation before its ephemeral key is +/// handed to a workload. This makes the launch witness portable without +/// allowing a configuration file or provider to mint its own activation. +pub struct IdunnRuntimeActivationPurpose; + +impl ServiceSignaturePurpose for IdunnRuntimeActivationPurpose { + const PURPOSE: &'static [u8] = b"idunn.runtime_activation.v2"; +} + +impl ServiceIdentityProfile for IdunnServiceIdentity { + const PRIVATE_TYPE: &'static str = "idunn.service_identity.private.v1"; + const PRIVATE_SCHEMA: &'static str = "idunn.service_identity.private.v1"; + const PRIVATE_KEY: &'static str = "idunn-service-identity"; + const TRUST_ANCHOR_TYPE: &'static str = "idunn.service_identity.trust_anchor.v1"; + const TRUST_ANCHOR_SCHEMA: &'static str = "idunn.service_identity.trust_anchor.v1"; + const TRUST_ANCHOR_KEY: &'static str = "idunn-service-identity-public"; + const ID_DOMAIN: &'static [u8] = b"idunn.service-identity.id.v1\0"; + const SIGNATURE_DOMAIN: &'static [u8] = b"idunn.service-identity.signature.v1\0"; + const PROTECTOR_CONTEXT: &'static str = "idunn-service-identity-v1"; +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ServiceIdentityPrivateEntry { + pub schema_version: String, + pub identity_id: String, + pub public_key: Vec, + pub protected_private_seed: Vec, + pub protector_kind: String, + pub protector_binding: String, + pub protector_version: String, + pub assurance: String, + pub created_at: String, + pub enrollment_nonce: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServiceIdentityTrustAnchor { + pub schema_version: String, + pub identity_id: String, + pub public_key: Vec, + pub assurance: String, + pub identity_created_at: String, + pub source_identity_record_sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ServiceIdentitySignature { + pub identity_id: String, + pub signature: Vec, +} + +/// The only value holding unprotected key material. It exposes signing, never +/// seed export or access to the underlying signing key. +pub struct ServiceIdentitySigner { + entry: ServiceIdentityPrivateEntry, + signing_key: SigningKey, + profile: PhantomData

, +} + +impl ServiceIdentitySigner

{ + pub fn entry(&self) -> &ServiceIdentityPrivateEntry { + &self.entry + } + + pub fn trust_anchor(&self) -> Result { + Ok(ServiceIdentityTrustAnchor { + schema_version: P::TRUST_ANCHOR_SCHEMA.into(), + identity_id: self.entry.identity_id.clone(), + public_key: self.entry.public_key.clone(), + assurance: self.entry.assurance.clone(), + identity_created_at: self.entry.created_at.clone(), + source_identity_record_sha256: format!( + "sha256-{}", + hex(&Sha256::digest(rmp_serde::to_vec(&self.entry)?)) + ), + }) + } + + pub fn sign>(&self, payload: &[u8]) -> ServiceIdentitySignature { + ServiceIdentitySignature { + identity_id: self.entry.identity_id.clone(), + signature: self + .signing_key + .sign(&signing_message::(payload)) + .to_bytes() + .to_vec(), + } + } +} + +pub fn enroll_service_identity_at( + path: &Path, +) -> Result> { + if path.exists() { + bail!( + "service identity store {} already exists; enrollment is immutable", + path.display() + ); + } + prepare_parent(path)?; + let mut seed = Zeroizing::new([0u8; 32]); + rand::rng().fill_bytes(seed.as_mut()); + let signing_key = SigningKey::from_bytes(&*seed); + let mut nonce = [0u8; 32]; + rand::rng().fill_bytes(&mut nonce); + let public_key = signing_key.verifying_key().to_bytes(); + let binding = platform_binding::

()?; + let entry = ServiceIdentityPrivateEntry { + schema_version: P::PRIVATE_SCHEMA.into(), + identity_id: identity_id::

(&public_key), + public_key: public_key.to_vec(), + protected_private_seed: protect_seed::

(&*seed, &binding)?, + protector_kind: platform_protector_kind().into(), + protector_binding: binding, + protector_version: "v1".into(), + assurance: platform_assurance().into(), + created_at: chrono::Utc::now().to_rfc3339(), + enrollment_nonce: nonce.to_vec(), + }; + validate_private::

(&entry)?; + let envelope = private_envelope::

(&entry)?; + atomic_create_private_store(path, &envelope)?; + harden_store_permissions(path)?; + open_service_identity_at::

(path) +} + +pub fn open_service_identity_at( + path: &Path, +) -> Result> { + if !path.is_file() { + bail!("service identity store {} does not exist", path.display()); + } + let entries = SingleFileMessagePackBackingStore::new(path).pull_all()?; + open_service_identity_envelopes::

(&entries) +} + +/// Opens an immutable service-identity credential from a read-only stream. +/// +/// Unlike [`open_service_identity_at`], this path has no sibling-lock or +/// writable-filesystem requirement. It is intended for immutable credential +/// copies such as systemd `LoadCredential` files. +pub fn open_service_identity_credential_reader( + mut reader: impl Read, +) -> Result> { + let mut bytes = Zeroizing::new(Vec::new()); + reader + .read_to_end(&mut bytes) + .context("failed to read immutable service identity credential")?; + open_service_identity_credential_bytes::

(&bytes) +} + +/// Opens an immutable service-identity credential from its exact bytes. +pub fn open_service_identity_credential_bytes( + bytes: &[u8], +) -> Result> { + let mut decoder = rmp_serde::Deserializer::new(std::io::Cursor::new(bytes)); + let entries = Vec::::deserialize(&mut decoder) + .context("immutable service identity credential is malformed MessagePack")?; + if decoder.position() != bytes.len() as u64 { + bail!("immutable service identity credential contains trailing data"); + } + open_service_identity_envelopes::

(&entries) +} + +fn open_service_identity_envelopes( + entries: &[CultCacheEnvelope], +) -> Result> { + let [envelope] = entries else { + bail!("service identity store must contain exactly one immutable envelope"); + }; + if envelope.r#type != P::PRIVATE_TYPE + || envelope.key != P::PRIVATE_KEY + || envelope.schema_id.as_deref() != Some(P::PRIVATE_SCHEMA) + { + bail!("service identity store belongs to a different profile or schema"); + } + let entry: ServiceIdentityPrivateEntry = rmp_serde::from_slice(&envelope.payload) + .context("service identity private payload is malformed MessagePack")?; + validate_private::

(&entry)?; + if entry.protector_kind != platform_protector_kind() || entry.assurance != platform_assurance() + { + bail!("service identity protector does not belong to this platform implementation"); + } + let binding = platform_binding::

()?; + if entry.protector_binding != binding { + bail!("service identity protector binding does not match this OS installation or profile"); + } + let seed = unprotect_seed::

(&entry.protected_private_seed, &binding)?; + let seed: &[u8; 32] = seed + .as_slice() + .try_into() + .map_err(|_| anyhow!("unprotected service identity seed has invalid length"))?; + let signing_key = SigningKey::from_bytes(seed); + if signing_key.verifying_key().to_bytes().as_slice() != entry.public_key.as_slice() { + bail!("service identity private seed does not match enrolled public key"); + } + Ok(ServiceIdentitySigner { + entry, + signing_key, + profile: PhantomData, + }) +} + +pub fn export_service_identity_trust_anchor( + signer: &ServiceIdentitySigner

, + path: &Path, +) -> Result { + let anchor = signer.trust_anchor()?; + prepare_parent(path)?; + let envelope = CultCacheEnvelope { + key: P::TRUST_ANCHOR_KEY.into(), + r#type: P::TRUST_ANCHOR_TYPE.into(), + payload: rmp_serde::to_vec(&anchor)?, + stored_at: anchor.identity_created_at.clone(), + schema_id: Some(P::TRUST_ANCHOR_SCHEMA.into()), + }; + let mut backing = SingleFileMessagePackBackingStore::new(path); + match backing.pull_all()?.as_slice() { + [] => backing.push(&envelope)?, + [current] if current == &envelope => {} + _ => bail!("service identity trust anchor output already contains different state"), + } + Ok(anchor) +} + +pub fn verify_service_identity_signature( + anchor: &ServiceIdentityTrustAnchor, + payload: &[u8], + proof: &ServiceIdentitySignature, +) -> Result<()> +where + P: ServiceIdentityProfile, + S: ServiceSignaturePurpose

, +{ + validate_anchor::

(anchor)?; + if proof.identity_id != anchor.identity_id { + bail!("service identity signature names a different identity"); + } + let key: [u8; 32] = anchor + .public_key + .as_slice() + .try_into() + .map_err(|_| anyhow!("service identity public key has invalid length"))?; + let signature = Signature::from_slice(&proof.signature) + .map_err(|_| anyhow!("service identity signature has invalid length"))?; + VerifyingKey::from_bytes(&key)? + .verify(&signing_message::(payload), &signature) + .map_err(|_| anyhow!("service identity signature verification failed")) +} + +/// Verify against a public key already admitted by an owning trust store. +/// The profile derives the identity, so callers cannot substitute a convenient +/// identity string while retaining the same signature bytes. +pub fn verify_service_identity_signature_with_public_key( + public_key: &[u8], + payload: &[u8], + proof: &ServiceIdentitySignature, +) -> Result<()> +where + P: ServiceIdentityProfile, + S: ServiceSignaturePurpose

, +{ + if proof.identity_id != derive_service_identity_id::

(public_key)? { + bail!("service identity signature names a different identity"); + } + let key: [u8; 32] = public_key + .try_into() + .map_err(|_| anyhow!("service identity public key has invalid length"))?; + let signature = Signature::from_slice(&proof.signature) + .map_err(|_| anyhow!("service identity signature has invalid length"))?; + VerifyingKey::from_bytes(&key)? + .verify(&signing_message::(payload), &signature) + .map_err(|_| anyhow!("service identity signature verification failed")) +} + +fn validate_private(entry: &ServiceIdentityPrivateEntry) -> Result<()> { + if entry.schema_version != P::PRIVATE_SCHEMA + || entry.public_key.len() != 32 + || entry.enrollment_nonce.len() != 32 + || entry.protected_private_seed.is_empty() + || entry.protector_version != "v1" + { + bail!("service identity private entry violates its profile schema"); + } + chrono::DateTime::parse_from_rfc3339(&entry.created_at) + .map_err(|_| anyhow!("service identity created_at is not RFC3339"))?; + if identity_id::

(&entry.public_key) != entry.identity_id { + bail!("service identity id does not match public key"); + } + Ok(()) +} + +fn validate_anchor(anchor: &ServiceIdentityTrustAnchor) -> Result<()> { + if anchor.schema_version != P::TRUST_ANCHOR_SCHEMA + || anchor.public_key.len() != 32 + || derive_service_identity_id::

(&anchor.public_key)? != anchor.identity_id + { + bail!("service identity trust anchor violates its profile schema"); + } + Ok(()) +} + +/// Derives the profile-bound identity id from an exact Ed25519 public key. +/// Consumers use this instead of accepting a caller-supplied identity string. +pub fn derive_service_identity_id(public_key: &[u8]) -> Result { + if public_key.len() != 32 { + bail!("service identity public key has invalid length"); + } + Ok(hex(&Sha256::digest([P::ID_DOMAIN, public_key].concat()))) +} + +fn identity_id(key: &[u8]) -> String { + derive_service_identity_id::

(key).expect("internal service identity key is Ed25519") +} + +fn signing_message>( + payload: &[u8], +) -> Vec { + let mut out = + Vec::with_capacity(P::SIGNATURE_DOMAIN.len() + S::PURPOSE.len() + payload.len() + 16); + out.extend_from_slice(P::SIGNATURE_DOMAIN); + out.extend_from_slice(&(S::PURPOSE.len() as u64).to_be_bytes()); + out.extend_from_slice(S::PURPOSE); + out.extend_from_slice(&(payload.len() as u64).to_be_bytes()); + out.extend_from_slice(payload); + out +} + +fn private_envelope( + entry: &ServiceIdentityPrivateEntry, +) -> Result { + Ok(CultCacheEnvelope { + key: P::PRIVATE_KEY.into(), + r#type: P::PRIVATE_TYPE.into(), + payload: rmp_serde::to_vec(entry)?, + stored_at: entry.created_at.clone(), + schema_id: Some(P::PRIVATE_SCHEMA.into()), + }) +} + +fn prepare_parent(path: &Path) -> Result<()> { + let parent = path + .parent() + .ok_or_else(|| anyhow!("service identity path has no parent"))?; + std::fs::create_dir_all(parent)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?; + } + Ok(()) +} + +/// Enrollment is a one-shot authority transition. `create_new` makes two +/// simultaneous enrollments unable to overwrite one another, while the encoded +/// envelope vector remains a supported CultCache single-file representation. +fn atomic_create_private_store(path: &Path, envelope: &CultCacheEnvelope) -> Result<()> { + let bytes = rmp_serde::to_vec(&vec![envelope.clone()]) + .context("failed to encode immutable service identity store")?; + let mut file = std::fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(path) + .with_context(|| { + format!( + "service identity store {} already exists or cannot be created; enrollment is immutable", + path.display() + ) + })?; + if let Err(error) = file.write_all(&bytes).and_then(|()| file.sync_all()) { + drop(file); + let _ = std::fs::remove_file(path); + return Err(error).context("failed to persist immutable service identity store"); + } + Ok(()) +} +fn harden_store_permissions(_path: &Path) -> Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(_path, std::fs::Permissions::from_mode(0o600))?; + } + Ok(()) +} + +#[cfg(windows)] +fn platform_protector_kind() -> &'static str { + "windows_dpapi_current_user" +} +#[cfg(target_os = "linux")] +fn platform_protector_kind() -> &'static str { + "linux_file_mode_machine_id_binding" +} +#[cfg(windows)] +fn platform_assurance() -> &'static str { + WINDOWS_SERVICE_IDENTITY_ASSURANCE +} +#[cfg(target_os = "linux")] +fn platform_assurance() -> &'static str { + LINUX_SERVICE_IDENTITY_ASSURANCE +} + +#[cfg(windows)] +fn platform_binding() -> Result { + Ok(format!("dpapi-current-user:{}", P::PROTECTOR_CONTEXT)) +} +#[cfg(target_os = "linux")] +fn platform_binding() -> Result { + let raw = std::fs::read_to_string("/etc/machine-id") + .or_else(|_| std::fs::read_to_string("/var/lib/dbus/machine-id")) + .context("Linux machine-id is unavailable")?; + let id = raw.trim(); + if id.is_empty() { + bail!("Linux machine-id is empty"); + } + Ok(format!( + "{}:machine-id-sha256:{}", + P::PROTECTOR_CONTEXT, + hex(&Sha256::digest(id.as_bytes())) + )) +} + +#[cfg(windows)] +fn protect_seed(seed: &[u8; 32], binding: &str) -> Result> { + Ok(dpapi::

(seed, binding, true)?.to_vec()) +} +#[cfg(windows)] +fn unprotect_seed( + seed: &[u8], + binding: &str, +) -> Result>> { + dpapi::

(seed, binding, false) +} +#[cfg(windows)] +fn dpapi( + input: &[u8], + binding: &str, + protect: bool, +) -> Result>> { + use windows_sys::Win32::Foundation::LocalFree; + use windows_sys::Win32::Security::Cryptography::{ + CRYPT_INTEGER_BLOB, CRYPTPROTECT_UI_FORBIDDEN, CryptProtectData, CryptUnprotectData, + }; + let mut input = Zeroizing::new(input.to_vec()); + let mut entropy = Zeroizing::new( + Sha256::digest( + [ + b"gamecult-service-identity-dpapi-v1\0".as_slice(), + P::PROTECTOR_CONTEXT.as_bytes(), + binding.as_bytes(), + ] + .concat(), + ) + .to_vec(), + ); + let ib = CRYPT_INTEGER_BLOB { + cbData: input.len() as u32, + pbData: input.as_mut_ptr(), + }; + let eb = CRYPT_INTEGER_BLOB { + cbData: entropy.len() as u32, + pbData: entropy.as_mut_ptr(), + }; + let mut output = CRYPT_INTEGER_BLOB { + cbData: 0, + pbData: std::ptr::null_mut(), + }; + let ok = unsafe { + if protect { + CryptProtectData( + &ib, + std::ptr::null(), + &eb, + std::ptr::null(), + std::ptr::null(), + CRYPTPROTECT_UI_FORBIDDEN, + &mut output, + ) + } else { + CryptUnprotectData( + &ib, + std::ptr::null_mut(), + &eb, + std::ptr::null(), + std::ptr::null(), + CRYPTPROTECT_UI_FORBIDDEN, + &mut output, + ) + } + }; + if ok == 0 { + return Err(std::io::Error::last_os_error()) + .context("DPAPI service identity operation failed"); + } + if output.pbData.is_null() { + bail!("DPAPI service identity operation returned a null output"); + } + let output = unsafe { std::slice::from_raw_parts_mut(output.pbData, output.cbData as usize) }; + let bytes = Zeroizing::new(output.to_vec()); + output.zeroize(); + unsafe { + LocalFree(output.as_mut_ptr().cast()); + } + Ok(bytes) +} + +#[cfg(target_os = "linux")] +fn protect_seed(seed: &[u8; 32], binding: &str) -> Result> { + xor_linux::

(seed, binding) +} +#[cfg(target_os = "linux")] +fn unprotect_seed( + seed: &[u8], + binding: &str, +) -> Result>> { + if seed.len() != 32 { + bail!("protected Linux service seed has invalid length"); + } + let mask = Sha256::digest( + [ + b"gamecult-linux-service-seed-v1\0".as_slice(), + P::PROTECTOR_CONTEXT.as_bytes(), + binding.as_bytes(), + ] + .concat(), + ); + let mut clear_seed = Zeroizing::new(Vec::with_capacity(seed.len())); + clear_seed.extend(seed.iter().zip(mask).map(|(a, b)| a ^ b)); + Ok(clear_seed) +} +#[cfg(target_os = "linux")] +fn xor_linux(seed: &[u8], binding: &str) -> Result> { + let mask = Sha256::digest( + [ + b"gamecult-linux-service-seed-v1\0".as_slice(), + P::PROTECTOR_CONTEXT.as_bytes(), + binding.as_bytes(), + ] + .concat(), + ); + Ok(seed.iter().zip(mask).map(|(a, b)| a ^ b).collect()) +} + +fn hex(bytes: &[u8]) -> String { + const D: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(bytes.len() * 2); + for b in bytes { + s.push(D[(b >> 4) as usize] as char); + s.push(D[(b & 15) as usize] as char); + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + enum OtherPurpose {} + impl ServiceSignaturePurpose for OtherPurpose { + const PURPOSE: &'static [u8] = b"idunn.other.v1"; + } + + #[test] + fn immutable_enrollment_reopens_and_is_purpose_and_payload_bound() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("idunn.ccmp"); + let signer = enroll_service_identity_at::(&path)?; + let proof = signer.sign::(b"healthy"); + let anchor = signer.trust_anchor()?; + verify_service_identity_signature::< + IdunnServiceIdentity, + IdunnAuthenticatedProviderHealthProjectionPurpose, + >(&anchor, b"healthy", &proof)?; + assert!( + verify_service_identity_signature::< + IdunnServiceIdentity, + IdunnAuthenticatedProviderHealthProjectionPurpose, + >(&anchor, b"unhealthy", &proof) + .is_err() + ); + assert!( + verify_service_identity_signature::( + &anchor, b"healthy", &proof + ) + .is_err() + ); + assert!(enroll_service_identity_at::(&path).is_err()); + assert_eq!( + derive_service_identity_id::(&anchor.public_key)?, + anchor.identity_id + ); + assert!(derive_service_identity_id::(&[0; 31]).is_err()); + assert_eq!( + open_service_identity_at::(&path)?.entry(), + signer.entry() + ); + Ok(()) + } + + #[test] + fn immutable_credential_reader_opens_without_a_path_and_retains_signing_authority() -> Result<()> + { + let temp = tempfile::tempdir()?; + let path = temp.path().join("provider-health.cc"); + let enrolled = enroll_service_identity_at::(&path)?; + let bytes = std::fs::read(path)?; + + let from_reader = open_service_identity_credential_reader::( + std::io::Cursor::new(bytes.clone()), + )?; + let from_bytes = + open_service_identity_credential_bytes::(&bytes)?; + assert_eq!(from_reader.entry(), enrolled.entry()); + assert_eq!(from_bytes.entry(), enrolled.entry()); + + let payload = b"runtime-presence"; + let proof = from_reader.sign::(payload); + verify_service_identity_signature::< + GameCultProviderHealthIdentity, + GameCultRuntimePresenceHealthPurpose, + >(&enrolled.trust_anchor()?, payload, &proof)?; + Ok(()) + } + + #[test] + fn immutable_credential_reader_rejects_ambiguous_profile_or_machine_state() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("idunn.ccmp"); + enroll_service_identity_at::(&path)?; + let bytes = std::fs::read(path)?; + + assert!( + open_service_identity_credential_bytes::(&bytes) + .is_err() + ); + + let mut envelopes: Vec = rmp_serde::from_slice(&bytes)?; + let mut duplicated = envelopes.clone(); + duplicated.push(envelopes[0].clone()); + assert!( + open_service_identity_credential_bytes::(&rmp_serde::to_vec( + &duplicated + )?) + .is_err() + ); + + let mut trailing = bytes.clone(); + trailing.push(0xc0); + assert!(open_service_identity_credential_bytes::(&trailing).is_err()); + + let mut wrong_seed_envelopes = envelopes.clone(); + let mut wrong_seed: ServiceIdentityPrivateEntry = + rmp_serde::from_slice(&wrong_seed_envelopes[0].payload)?; + wrong_seed.protected_private_seed[0] ^= 1; + wrong_seed_envelopes[0].payload = rmp_serde::to_vec(&wrong_seed)?; + assert!( + open_service_identity_credential_bytes::(&rmp_serde::to_vec( + &wrong_seed_envelopes + )?) + .is_err() + ); + + let mut entry: ServiceIdentityPrivateEntry = rmp_serde::from_slice(&envelopes[0].payload)?; + entry.protector_binding.push_str(":another-machine"); + envelopes[0].payload = rmp_serde::to_vec(&entry)?; + assert!( + open_service_identity_credential_bytes::(&rmp_serde::to_vec( + &envelopes + )?) + .is_err() + ); + Ok(()) + } + + #[test] + fn malformed_or_profile_substituted_state_fails_closed_without_replacement() -> Result<()> { + enum Alien {} + impl ServiceIdentityProfile for Alien { + const PRIVATE_TYPE: &'static str = "alien.private.v1"; + const PRIVATE_SCHEMA: &'static str = "alien.private.v1"; + const PRIVATE_KEY: &'static str = "alien"; + const TRUST_ANCHOR_TYPE: &'static str = "alien.anchor.v1"; + const TRUST_ANCHOR_SCHEMA: &'static str = "alien.anchor.v1"; + const TRUST_ANCHOR_KEY: &'static str = "alien-public"; + const ID_DOMAIN: &'static [u8] = b"alien.id\0"; + const SIGNATURE_DOMAIN: &'static [u8] = b"alien.sig\0"; + const PROTECTOR_CONTEXT: &'static str = "alien-v1"; + } + let temp = tempfile::tempdir()?; + let malformed = temp.path().join("bad.ccmp"); + std::fs::write(&malformed, b"rot")?; + let before = std::fs::read(&malformed)?; + assert!(open_service_identity_at::(&malformed).is_err()); + assert!(enroll_service_identity_at::(&malformed).is_err()); + assert_eq!(before, std::fs::read(&malformed)?); + let good = temp.path().join("good.ccmp"); + enroll_service_identity_at::(&good)?; + assert!(open_service_identity_at::(&good).is_err()); + Ok(()) + } + + #[test] + fn exported_anchor_is_public_only_immutable_and_rejects_identity_substitution() -> Result<()> { + let temp = tempfile::tempdir()?; + let signer = + enroll_service_identity_at::(&temp.path().join("private.ccmp"))?; + let output = temp.path().join("public.ccmp"); + let anchor = export_service_identity_trust_anchor(&signer, &output)?; + let bytes = std::fs::read(&output)?; + assert!( + !bytes + .windows(signer.entry().protected_private_seed.len()) + .any(|w| w == signer.entry().protected_private_seed) + ); + export_service_identity_trust_anchor(&signer, &output)?; + assert_eq!(bytes, std::fs::read(&output)?); + let other = + enroll_service_identity_at::(&temp.path().join("other.ccmp"))?; + let proof = other.sign::(b"healthy"); + assert!( + verify_service_identity_signature::< + IdunnServiceIdentity, + IdunnAuthenticatedProviderHealthProjectionPurpose, + >(&anchor, b"healthy", &proof) + .is_err() + ); + Ok(()) + } + + #[test] + fn provider_health_profile_is_domain_separated_and_purpose_bound() -> Result<()> { + let temp = tempfile::tempdir()?; + let signer = enroll_service_identity_at::( + &temp.path().join("provider-health.cc"), + )?; + let proof = signer.sign::(b"signed-health-record"); + let anchor = signer.trust_anchor()?; + verify_service_identity_signature::< + GameCultProviderHealthIdentity, + IdunnSignedDaemonHealthPurpose, + >(&anchor, b"signed-health-record", &proof)?; + verify_service_identity_signature_with_public_key::< + GameCultProviderHealthIdentity, + IdunnSignedDaemonHealthPurpose, + >(&anchor.public_key, b"signed-health-record", &proof)?; + assert_eq!( + anchor.schema_version, + "gamecult.provider_health_identity.trust_anchor.v1" + ); + assert_ne!( + derive_service_identity_id::(&anchor.public_key)?, + derive_service_identity_id::(&anchor.public_key)? + ); + Ok(()) + } + + #[test] + fn runtime_presence_and_legacy_health_purposes_cannot_be_substituted() -> Result<()> { + let temp = tempfile::tempdir()?; + let signer = enroll_service_identity_at::( + &temp.path().join("provider-runtime-presence.cc"), + )?; + let anchor = signer.trust_anchor()?; + let payload = b"runtime-presence"; + + let presence = signer.sign::(payload); + verify_service_identity_signature::< + GameCultProviderHealthIdentity, + GameCultRuntimePresenceHealthPurpose, + >(&anchor, payload, &presence)?; + assert!( + verify_service_identity_signature::< + GameCultProviderHealthIdentity, + IdunnSignedDaemonHealthPurpose, + >(&anchor, payload, &presence) + .is_err() + ); + + let legacy = signer.sign::(payload); + assert!( + verify_service_identity_signature::< + GameCultProviderHealthIdentity, + GameCultRuntimePresenceHealthPurpose, + >(&anchor, payload, &legacy) + .is_err() + ); + Ok(()) + } +} diff --git a/packages/cultnet-rs/src/snapshot_query.rs b/packages/cultnet-rs/src/snapshot_query.rs new file mode 100644 index 00000000..f6150d1d --- /dev/null +++ b/packages/cultnet-rs/src/snapshot_query.rs @@ -0,0 +1,339 @@ +use anyhow::{Result, anyhow}; +use std::collections::{BTreeMap, BTreeSet}; + +use crate::{CultNetDocumentRegistry, CultNetMessage, CultNetRawDocumentRecord}; + +/// Read-only backing surface for a CultNet snapshot server. +/// +/// Records returned here are already the stored wire records. The snapshot +/// server selects and clones them; it never decodes payloads, rewrites source +/// metadata, or applies them to another cache. +pub trait CultNetRawSnapshotSource { + fn raw_snapshot(&self) -> Result>; +} + +impl CultNetRawSnapshotSource for Vec { + fn raw_snapshot(&self) -> Result> { + Ok(self.clone()) + } +} + +impl CultNetRawSnapshotSource for F +where + F: Fn() -> Result>, +{ + fn raw_snapshot(&self) -> Result> { + self() + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CultNetReadOnlySnapshotPolicy { + allowed_records: BTreeSet<(String, String)>, +} + +impl CultNetReadOnlySnapshotPolicy { + pub fn new() -> Self { + Self::default() + } + + pub fn allow( + &mut self, + schema_id: impl Into, + record_key: impl Into, + ) -> Result<&mut Self> { + let schema_id = schema_id.into(); + let record_key = record_key.into(); + require_non_empty(&schema_id, "schema_id")?; + require_non_empty(&record_key, "record_key")?; + self.allowed_records.insert((schema_id, record_key)); + Ok(self) + } + + fn allows(&self, schema_id: &str, record_key: &str) -> bool { + self.allowed_records + .contains(&(schema_id.to_string(), record_key.to_string())) + } +} + +/// Serve one raw snapshot request from an explicitly bounded, read-only view. +/// +/// The document registry proves that every exposed schema belongs to the +/// runtime. The policy grants individual `(schema_id, record_key)` pairs. The +/// source owns the bytes and metadata; this function only selects records. +pub fn serve_read_only_raw_snapshot( + document_registry: &CultNetDocumentRegistry, + policy: &CultNetReadOnlySnapshotPolicy, + source: &S, + request: &CultNetMessage, +) -> Result { + let CultNetMessage::SnapshotRequest { + message_id, + schema_ids, + record_keys, + } = request + else { + return Err(anyhow!("expected cultnet.snapshot_request.v0")); + }; + require_non_empty(message_id, "message_id")?; + reject_duplicates(schema_ids.as_deref(), "requested schema id")?; + reject_duplicates(record_keys.as_deref(), "requested record key")?; + + let requested_schemas = schema_ids + .as_ref() + .map(|values| values.iter().map(String::as_str).collect::>()); + let requested_keys = record_keys + .as_ref() + .map(|values| values.iter().map(String::as_str).collect::>()); + let mut selected = Vec::new(); + let mut seen = BTreeSet::new(); + + for document in source.raw_snapshot()? { + let identity = (document.schema_id.clone(), document.record_key.clone()); + if !seen.insert(identity.clone()) { + return Err(anyhow!( + "snapshot source contains duplicate record {:?}/{:?}", + identity.0, + identity.1 + )); + } + if document_registry + .binding_by_schema_id(&document.schema_id) + .is_none() + { + return Err(anyhow!( + "snapshot source record {:?}/{:?} uses an unregistered schema", + document.schema_id, + document.record_key + )); + } + if !policy.allows(&document.schema_id, &document.record_key) { + continue; + } + if requested_schemas + .as_ref() + .is_some_and(|schemas| !schemas.contains(document.schema_id.as_str())) + { + continue; + } + if requested_keys + .as_ref() + .is_some_and(|keys| !keys.contains(document.record_key.as_str())) + { + continue; + } + selected.push(document); + } + + Ok(CultNetMessage::SnapshotResponseRaw { + message_id: message_id.clone(), + documents: selected, + }) +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CultNetSnapshotSourceExpectation { + pub runtime_id: Option, + pub agent_id: Option, + pub role: Option, + pub tags: Option>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultNetSnapshotRecordExpectation { + pub schema_id: String, + pub record_key: String, + pub source: CultNetSnapshotSourceExpectation, +} + +impl CultNetSnapshotRecordExpectation { + pub fn new(schema_id: impl Into, record_key: impl Into) -> Self { + Self { + schema_id: schema_id.into(), + record_key: record_key.into(), + source: CultNetSnapshotSourceExpectation::default(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultNetRawSnapshotQuery { + message_id: String, + expectations: BTreeMap<(String, String), CultNetSnapshotSourceExpectation>, +} + +impl CultNetRawSnapshotQuery { + pub fn new( + message_id: impl Into, + records: Vec, + ) -> Result { + let message_id = message_id.into(); + require_non_empty(&message_id, "message_id")?; + if records.is_empty() { + return Err(anyhow!("snapshot query must request at least one record")); + } + let mut expectations = BTreeMap::new(); + for record in records { + require_non_empty(&record.schema_id, "schema_id")?; + require_non_empty(&record.record_key, "record_key")?; + let identity = (record.schema_id, record.record_key); + if expectations + .insert(identity.clone(), record.source) + .is_some() + { + return Err(anyhow!( + "snapshot query contains duplicate requested record {:?}/{:?}", + identity.0, + identity.1 + )); + } + } + Ok(Self { + message_id, + expectations, + }) + } + + pub fn request(&self) -> CultNetMessage { + CultNetMessage::SnapshotRequest { + message_id: self.message_id.clone(), + schema_ids: Some( + self.expectations + .keys() + .map(|(schema_id, _)| schema_id.clone()) + .collect::>() + .into_iter() + .collect(), + ), + record_keys: Some( + self.expectations + .keys() + .map(|(_, record_key)| record_key.clone()) + .collect::>() + .into_iter() + .collect(), + ), + } + } + + /// Validate a response and return records without mutating any local cache. + pub fn accept_response( + &self, + response: CultNetMessage, + ) -> Result> { + let CultNetMessage::SnapshotResponseRaw { + message_id, + documents, + } = response + else { + return Err(anyhow!("expected cultnet.snapshot_response_raw.v0")); + }; + if message_id != self.message_id { + return Err(anyhow!( + "snapshot response message id {:?} does not match request {:?}", + message_id, + self.message_id + )); + } + + let mut seen = BTreeSet::new(); + for document in &documents { + let identity = (document.schema_id.clone(), document.record_key.clone()); + if !seen.insert(identity.clone()) { + return Err(anyhow!( + "snapshot response contains duplicate record {:?}/{:?}", + identity.0, + identity.1 + )); + } + let expected = self.expectations.get(&identity).ok_or_else(|| { + anyhow!( + "snapshot response contains unexpected record {:?}/{:?}", + identity.0, + identity.1 + ) + })?; + require_expected_metadata( + "source_runtime_id", + expected.runtime_id.as_deref(), + document.source_runtime_id.as_deref(), + &identity, + )?; + require_expected_metadata( + "source_agent_id", + expected.agent_id.as_deref(), + document.source_agent_id.as_deref(), + &identity, + )?; + require_expected_metadata( + "source_role", + expected.role.as_deref(), + document.source_role.as_deref(), + &identity, + )?; + if let Some(expected_tags) = expected.tags.as_ref() + && document.tags.as_ref() != Some(expected_tags) + { + return Err(anyhow!( + "snapshot response record {:?}/{:?} has unexpected tags: expected {:?}, got {:?}", + identity.0, + identity.1, + expected_tags, + document.tags + )); + } + } + Ok(documents) + } +} + +pub fn query_read_only_raw_snapshot( + query: &CultNetRawSnapshotQuery, + exchange: F, +) -> Result> +where + F: FnOnce(CultNetMessage) -> Result, +{ + query.accept_response(exchange(query.request())?) +} + +fn require_expected_metadata( + field: &str, + expected: Option<&str>, + actual: Option<&str>, + identity: &(String, String), +) -> Result<()> { + if let Some(expected) = expected + && actual != Some(expected) + { + return Err(anyhow!( + "snapshot response record {:?}/{:?} has unexpected {field}: expected {:?}, got {:?}", + identity.0, + identity.1, + expected, + actual + )); + } + Ok(()) +} + +fn reject_duplicates(values: Option<&[String]>, label: &str) -> Result<()> { + let Some(values) = values else { + return Ok(()); + }; + let mut seen = BTreeSet::new(); + for value in values { + require_non_empty(value, label)?; + if !seen.insert(value) { + return Err(anyhow!("duplicate {label} {value:?}")); + } + } + Ok(()) +} + +fn require_non_empty(value: &str, field: &str) -> Result<()> { + if value.trim().is_empty() { + return Err(anyhow!("{field} must be non-empty")); + } + Ok(()) +}