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 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-03 22:56:41 +02:00
commit a539d4fb1c
8 changed files with 6055 additions and 0 deletions

View file

@ -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"

View file

@ -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<u64>,
#[cultcache(key = 9)]
pub authorization_id: Option<String>,
#[cultcache(key = 10)]
pub authorization_purpose: Option<String>,
#[cultcache(key = 11)]
pub authorized_release_id: Option<String>,
#[cultcache(key = 12)]
pub authorized_deployment_id: Option<String>,
#[cultcache(key = 13)]
pub authorized_by: Option<String>,
#[cultcache(key = 14)]
pub authorization_issued_at_unix_millis: Option<u64>,
#[cultcache(key = 15)]
pub authorization_expires_at_unix_millis: Option<u64>,
#[cultcache(key = 16)]
pub signature_algorithm: Option<String>,
#[cultcache(key = 17)]
pub signature: Option<Vec<u8>>,
#[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::<IdunnDeploymentBrakeOperatorIdentity>(
&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::<IdunnDeploymentBrakeReleasePurpose>(&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(())
}
}

View file

@ -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<u64>,
}
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<Vec<u8>> {
self.validate()?;
Ok(rmp_serde::to_vec(self)?)
}
pub fn decode_canonical(payload: &[u8]) -> Result<Self> {
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<usize> {
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)
);
}
}

View file

@ -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::*;

View file

@ -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<String>,
#[cultcache(key = 11)]
pub release_witness_sha256: Option<String>,
#[cultcache(key = 12)]
pub source_commit: Option<String>,
#[cultcache(key = 13)]
pub deployment_id: Option<String>,
#[cultcache(key = 14)]
pub signature_algorithm: String,
#[cultcache(key = 15, bytes)]
pub signature: Vec<u8>,
#[cultcache(key = 16)]
pub private_state_exposed: bool,
#[cultcache(key = 17, default)]
pub activation_witness_sha256: Option<String>,
}
#[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<String>,
release_witness_sha256: Option<String>,
source_commit: Option<String>,
deployment_id: Option<String>,
signature_algorithm: String,
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
private_state_exposed: bool,
}
impl From<LegacyIdunnSignedDaemonHealthWire> 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<u8>)> {
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<usize> {
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<u8>,
#[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<u64>,
#[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::<IdunnServiceIdentity>(&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::<GameCultProviderHealthIdentity>(
&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::<OdinTopologyIdentity>(&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<String>,
#[cultcache(key = 17)]
pub release_witness_sha256: Option<String>,
#[cultcache(key = 18)]
pub source_commit: Option<String>,
#[cultcache(key = 19)]
pub deployment_id: Option<String>,
#[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<u8>,
#[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<String>, label: &str) -> Result<()> {
if let Some(value) = value {
validate_identifier(value, label)?;
}
Ok(())
}
fn validate_optional_sha256(value: &Option<String>, 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<String>,
witness: &Option<String>,
source_commit: &Option<String>,
) -> 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::<IdunnServiceIdentity>(&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::<IdunnSignedDaemonHealthRecord>(&encoded)?,
health
);
assert_eq!(
rmp_serde::from_slice::<GameCultServiceTrustAnchorRecord>(&rmp_serde::to_vec(
&anchor
)?)?,
anchor
);
assert_eq!(
rmp_serde::from_slice::<IdunnAuthenticatedProviderHealthProjectionRecord>(
&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());
}
}

File diff suppressed because it is too large Load diff

View file

@ -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<P: ServiceIdentityProfile>: 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<OdinTopologyIdentity> 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<IdunnDeploymentBrakeOperatorIdentity>
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<GameCultProviderHealthIdentity> 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<GameCultProviderHealthIdentity>
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<IdunnServiceIdentity>
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<IdunnServiceIdentity> 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<u8>,
pub protected_private_seed: Vec<u8>,
pub protector_kind: String,
pub protector_binding: String,
pub protector_version: String,
pub assurance: String,
pub created_at: String,
pub enrollment_nonce: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceIdentityTrustAnchor {
pub schema_version: String,
pub identity_id: String,
pub public_key: Vec<u8>,
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<u8>,
}
/// The only value holding unprotected key material. It exposes signing, never
/// seed export or access to the underlying signing key.
pub struct ServiceIdentitySigner<P: ServiceIdentityProfile> {
entry: ServiceIdentityPrivateEntry,
signing_key: SigningKey,
profile: PhantomData<P>,
}
impl<P: ServiceIdentityProfile> ServiceIdentitySigner<P> {
pub fn entry(&self) -> &ServiceIdentityPrivateEntry {
&self.entry
}
pub fn trust_anchor(&self) -> Result<ServiceIdentityTrustAnchor> {
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<S: ServiceSignaturePurpose<P>>(&self, payload: &[u8]) -> ServiceIdentitySignature {
ServiceIdentitySignature {
identity_id: self.entry.identity_id.clone(),
signature: self
.signing_key
.sign(&signing_message::<P, S>(payload))
.to_bytes()
.to_vec(),
}
}
}
pub fn enroll_service_identity_at<P: ServiceIdentityProfile>(
path: &Path,
) -> Result<ServiceIdentitySigner<P>> {
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::<P>()?;
let entry = ServiceIdentityPrivateEntry {
schema_version: P::PRIVATE_SCHEMA.into(),
identity_id: identity_id::<P>(&public_key),
public_key: public_key.to_vec(),
protected_private_seed: protect_seed::<P>(&*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::<P>(&entry)?;
let envelope = private_envelope::<P>(&entry)?;
atomic_create_private_store(path, &envelope)?;
harden_store_permissions(path)?;
open_service_identity_at::<P>(path)
}
pub fn open_service_identity_at<P: ServiceIdentityProfile>(
path: &Path,
) -> Result<ServiceIdentitySigner<P>> {
if !path.is_file() {
bail!("service identity store {} does not exist", path.display());
}
let entries = SingleFileMessagePackBackingStore::new(path).pull_all()?;
open_service_identity_envelopes::<P>(&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<P: ServiceIdentityProfile>(
mut reader: impl Read,
) -> Result<ServiceIdentitySigner<P>> {
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::<P>(&bytes)
}
/// Opens an immutable service-identity credential from its exact bytes.
pub fn open_service_identity_credential_bytes<P: ServiceIdentityProfile>(
bytes: &[u8],
) -> Result<ServiceIdentitySigner<P>> {
let mut decoder = rmp_serde::Deserializer::new(std::io::Cursor::new(bytes));
let entries = Vec::<CultCacheEnvelope>::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::<P>(&entries)
}
fn open_service_identity_envelopes<P: ServiceIdentityProfile>(
entries: &[CultCacheEnvelope],
) -> Result<ServiceIdentitySigner<P>> {
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::<P>(&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::<P>()?;
if entry.protector_binding != binding {
bail!("service identity protector binding does not match this OS installation or profile");
}
let seed = unprotect_seed::<P>(&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<P: ServiceIdentityProfile>(
signer: &ServiceIdentitySigner<P>,
path: &Path,
) -> Result<ServiceIdentityTrustAnchor> {
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<P, S>(
anchor: &ServiceIdentityTrustAnchor,
payload: &[u8],
proof: &ServiceIdentitySignature,
) -> Result<()>
where
P: ServiceIdentityProfile,
S: ServiceSignaturePurpose<P>,
{
validate_anchor::<P>(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::<P, S>(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<P, S>(
public_key: &[u8],
payload: &[u8],
proof: &ServiceIdentitySignature,
) -> Result<()>
where
P: ServiceIdentityProfile,
S: ServiceSignaturePurpose<P>,
{
if proof.identity_id != derive_service_identity_id::<P>(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::<P, S>(payload), &signature)
.map_err(|_| anyhow!("service identity signature verification failed"))
}
fn validate_private<P: ServiceIdentityProfile>(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::<P>(&entry.public_key) != entry.identity_id {
bail!("service identity id does not match public key");
}
Ok(())
}
fn validate_anchor<P: ServiceIdentityProfile>(anchor: &ServiceIdentityTrustAnchor) -> Result<()> {
if anchor.schema_version != P::TRUST_ANCHOR_SCHEMA
|| anchor.public_key.len() != 32
|| derive_service_identity_id::<P>(&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<P: ServiceIdentityProfile>(public_key: &[u8]) -> Result<String> {
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<P: ServiceIdentityProfile>(key: &[u8]) -> String {
derive_service_identity_id::<P>(key).expect("internal service identity key is Ed25519")
}
fn signing_message<P: ServiceIdentityProfile, S: ServiceSignaturePurpose<P>>(
payload: &[u8],
) -> Vec<u8> {
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<P: ServiceIdentityProfile>(
entry: &ServiceIdentityPrivateEntry,
) -> Result<CultCacheEnvelope> {
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<P: ServiceIdentityProfile>() -> Result<String> {
Ok(format!("dpapi-current-user:{}", P::PROTECTOR_CONTEXT))
}
#[cfg(target_os = "linux")]
fn platform_binding<P: ServiceIdentityProfile>() -> Result<String> {
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<P: ServiceIdentityProfile>(seed: &[u8; 32], binding: &str) -> Result<Vec<u8>> {
Ok(dpapi::<P>(seed, binding, true)?.to_vec())
}
#[cfg(windows)]
fn unprotect_seed<P: ServiceIdentityProfile>(
seed: &[u8],
binding: &str,
) -> Result<Zeroizing<Vec<u8>>> {
dpapi::<P>(seed, binding, false)
}
#[cfg(windows)]
fn dpapi<P: ServiceIdentityProfile>(
input: &[u8],
binding: &str,
protect: bool,
) -> Result<Zeroizing<Vec<u8>>> {
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<P: ServiceIdentityProfile>(seed: &[u8; 32], binding: &str) -> Result<Vec<u8>> {
xor_linux::<P>(seed, binding)
}
#[cfg(target_os = "linux")]
fn unprotect_seed<P: ServiceIdentityProfile>(
seed: &[u8],
binding: &str,
) -> Result<Zeroizing<Vec<u8>>> {
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<P: ServiceIdentityProfile>(seed: &[u8], binding: &str) -> Result<Vec<u8>> {
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<IdunnServiceIdentity> 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::<IdunnServiceIdentity>(&path)?;
let proof = signer.sign::<IdunnAuthenticatedProviderHealthProjectionPurpose>(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::<IdunnServiceIdentity, OtherPurpose>(
&anchor, b"healthy", &proof
)
.is_err()
);
assert!(enroll_service_identity_at::<IdunnServiceIdentity>(&path).is_err());
assert_eq!(
derive_service_identity_id::<IdunnServiceIdentity>(&anchor.public_key)?,
anchor.identity_id
);
assert!(derive_service_identity_id::<IdunnServiceIdentity>(&[0; 31]).is_err());
assert_eq!(
open_service_identity_at::<IdunnServiceIdentity>(&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::<GameCultProviderHealthIdentity>(&path)?;
let bytes = std::fs::read(path)?;
let from_reader = open_service_identity_credential_reader::<GameCultProviderHealthIdentity>(
std::io::Cursor::new(bytes.clone()),
)?;
let from_bytes =
open_service_identity_credential_bytes::<GameCultProviderHealthIdentity>(&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::<GameCultRuntimePresenceHealthPurpose>(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::<IdunnServiceIdentity>(&path)?;
let bytes = std::fs::read(path)?;
assert!(
open_service_identity_credential_bytes::<GameCultProviderHealthIdentity>(&bytes)
.is_err()
);
let mut envelopes: Vec<CultCacheEnvelope> = rmp_serde::from_slice(&bytes)?;
let mut duplicated = envelopes.clone();
duplicated.push(envelopes[0].clone());
assert!(
open_service_identity_credential_bytes::<IdunnServiceIdentity>(&rmp_serde::to_vec(
&duplicated
)?)
.is_err()
);
let mut trailing = bytes.clone();
trailing.push(0xc0);
assert!(open_service_identity_credential_bytes::<IdunnServiceIdentity>(&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::<IdunnServiceIdentity>(&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::<IdunnServiceIdentity>(&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::<IdunnServiceIdentity>(&malformed).is_err());
assert!(enroll_service_identity_at::<IdunnServiceIdentity>(&malformed).is_err());
assert_eq!(before, std::fs::read(&malformed)?);
let good = temp.path().join("good.ccmp");
enroll_service_identity_at::<IdunnServiceIdentity>(&good)?;
assert!(open_service_identity_at::<Alien>(&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::<IdunnServiceIdentity>(&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::<IdunnServiceIdentity>(&temp.path().join("other.ccmp"))?;
let proof = other.sign::<IdunnAuthenticatedProviderHealthProjectionPurpose>(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::<GameCultProviderHealthIdentity>(
&temp.path().join("provider-health.cc"),
)?;
let proof = signer.sign::<IdunnSignedDaemonHealthPurpose>(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::<GameCultProviderHealthIdentity>(&anchor.public_key)?,
derive_service_identity_id::<IdunnServiceIdentity>(&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::<GameCultProviderHealthIdentity>(
&temp.path().join("provider-runtime-presence.cc"),
)?;
let anchor = signer.trust_anchor()?;
let payload = b"runtime-presence";
let presence = signer.sign::<GameCultRuntimePresenceHealthPurpose>(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::<IdunnSignedDaemonHealthPurpose>(payload);
assert!(
verify_service_identity_signature::<
GameCultProviderHealthIdentity,
GameCultRuntimePresenceHealthPurpose,
>(&anchor, payload, &legacy)
.is_err()
);
Ok(())
}
}

View file

@ -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<Vec<CultNetRawDocumentRecord>>;
}
impl CultNetRawSnapshotSource for Vec<CultNetRawDocumentRecord> {
fn raw_snapshot(&self) -> Result<Vec<CultNetRawDocumentRecord>> {
Ok(self.clone())
}
}
impl<F> CultNetRawSnapshotSource for F
where
F: Fn() -> Result<Vec<CultNetRawDocumentRecord>>,
{
fn raw_snapshot(&self) -> Result<Vec<CultNetRawDocumentRecord>> {
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<String>,
record_key: impl Into<String>,
) -> 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<S: CultNetRawSnapshotSource>(
document_registry: &CultNetDocumentRegistry,
policy: &CultNetReadOnlySnapshotPolicy,
source: &S,
request: &CultNetMessage,
) -> Result<CultNetMessage> {
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::<BTreeSet<_>>());
let requested_keys = record_keys
.as_ref()
.map(|values| values.iter().map(String::as_str).collect::<BTreeSet<_>>());
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<String>,
pub agent_id: Option<String>,
pub role: Option<String>,
pub tags: Option<Vec<String>>,
}
#[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<String>, record_key: impl Into<String>) -> 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<String>,
records: Vec<CultNetSnapshotRecordExpectation>,
) -> Result<Self> {
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::<BTreeSet<_>>()
.into_iter()
.collect(),
),
record_keys: Some(
self.expectations
.keys()
.map(|(_, record_key)| record_key.clone())
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
),
}
}
/// Validate a response and return records without mutating any local cache.
pub fn accept_response(
&self,
response: CultNetMessage,
) -> Result<Vec<CultNetRawDocumentRecord>> {
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<F>(
query: &CultNetRawSnapshotQuery,
exchange: F,
) -> Result<Vec<CultNetRawDocumentRecord>>
where
F: FnOnce(CultNetMessage) -> Result<CultNetMessage>,
{
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(())
}