saddle-core 0.2.0-rc.18

Shared contracts for Saddle components
Documentation
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::sync::atomic::{AtomicBool, Ordering};

const APPROVED_WHOLE: &[u8] = include_bytes!("approved-inputs/candidate-fact-whole.json");
const APPROVED_PERMIT: &[u8] = include_bytes!("approved-inputs/permit.json");
const APPROVED_SOURCE: &str = "da64568f31bfacd38f6c0807588dd2cc59c258fe";
static CONSUMED: AtomicBool = AtomicBool::new(false);

/// The sole source-controlled input pair for the trusted 0.2 candidate set.
/// It has no caller-provided bytes or digest adapter and is non-Clone.
///
/// ```compile_fail
/// use saddle_core::ApprovedTrustedCandidateSetInput;
/// let _ = ApprovedTrustedCandidateSetInput {};
/// ```
///
/// ```compile_fail
/// use saddle_core::approved_trusted_candidate_set_input;
/// let input = approved_trusted_candidate_set_input();
/// let _ = input.clone();
/// ```
#[doc(hidden)]
pub struct ApprovedTrustedCandidateSetInput {
    whole: &'static [u8],
    permit: &'static [u8],
}

/// Complete, same-candidate set for Database, Service, Runtime,
/// Observability and Admission. Fields are private and the owner is non-Clone.
#[doc(hidden)]
pub struct VerifiedTrustedCandidateSetOwner {
    input: ApprovedTrustedCandidateSetInput,
}

/// A failed validation returns the exact opaque input for retry.
#[doc(hidden)]
pub struct TrustedCandidateSetRejection {
    input: ApprovedTrustedCandidateSetInput,
}

impl TrustedCandidateSetRejection {
    #[doc(hidden)]
    pub fn into_input(self) -> ApprovedTrustedCandidateSetInput {
        self.input
    }
}

#[doc(hidden)]
pub fn approved_trusted_candidate_set_input() -> ApprovedTrustedCandidateSetInput {
    ApprovedTrustedCandidateSetInput {
        whole: APPROVED_WHOLE,
        permit: APPROVED_PERMIT,
    }
}

/// The only production consumer of the approved whole/permit pair.
#[doc(hidden)]
pub fn verify_trusted_candidate_set(
    input: ApprovedTrustedCandidateSetInput,
) -> Result<VerifiedTrustedCandidateSetOwner, TrustedCandidateSetRejection> {
    if !matches_approved_set(&input)
        || CONSUMED
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
    {
        return Err(TrustedCandidateSetRejection { input });
    }
    Ok(VerifiedTrustedCandidateSetOwner { input })
}

/// Restores the exact approved input before the facade startup transaction
/// commits.
#[doc(hidden)]
pub fn rollback_trusted_candidate_set(
    owner: VerifiedTrustedCandidateSetOwner,
) -> ApprovedTrustedCandidateSetInput {
    CONSUMED.store(false, Ordering::Release);
    owner.input
}

fn matches_approved_set(input: &ApprovedTrustedCandidateSetInput) -> bool {
    if input.whole.as_ptr() != APPROVED_WHOLE.as_ptr()
        || input.whole.len() != APPROVED_WHOLE.len()
        || input.permit.as_ptr() != APPROVED_PERMIT.as_ptr()
        || input.permit.len() != APPROVED_PERMIT.len()
    {
        return false;
    }
    let Ok(whole) = serde_json::from_slice::<CandidateWhole>(input.whole) else {
        return false;
    };
    let Ok(permit) = serde_json::from_slice::<ValidationPermit>(input.permit) else {
        return false;
    };
    let domains = whole.projection.domain_sha256.values();
    whole.schema == "saddle-0.2-semantic-fact-whole-candidate/1"
        && !whole.authority
        && whole.signed_subject == "saddle-f08-rendezvous-manifest/1"
        && canonical_identity(&whole.semantic_identity)
        && canonical_identity(&whole.projection.input_sha256)
        && canonical_identity(&whole.projection.contract_sha256)
        && whole.projection.target == "x86_64-unknown-linux-gnu"
        && canonical_identity(&whole.projection.calibration_binary_sha256)
        && domains.iter().all(|value| canonical_identity(value))
        && pairwise_distinct(&domains)
        && whole.projection.route_identities.len() == 6
        && pairwise_distinct(&whole.projection.route_identities.iter().collect::<Vec<_>>())
        && whole.projection.termination_work_identities.len() == 3
        && pairwise_distinct(
            &whole
                .projection
                .termination_work_identities
                .iter()
                .collect::<Vec<_>>(),
        )
        && permit.schema == "saddle-0.2-golden-c8-source-validation-permit/1"
        && permit.authority_scope == "golden-c8-listener-preclosure-only"
        && permit.source_candidate_identity == APPROVED_SOURCE
        && permit.candidate_fact_whole_identity == hex_sha256(input.whole)
        && permit.candidate_semantic_identity == whole.semantic_identity
        && canonical_identity(&permit.environment_identity)
        && canonical_identity(&permit.run_identity)
        && canonical_identity(&permit.reservation_identity)
        && permit.single_use
        && permit.minimum_terminal_stage == "listener"
        && !permit.signing_authority
        && !permit.enterprise_production_authority
        && !permit.rust_skill_artifact_combination_authority
        && !permit.component_production_wiring_authority
        && !permit.publish_authority
        && !permit.release_authority
        && whole.boundary.signature == "STOP"
        && whole.boundary.deployment_permit == "STOP"
        && whole.boundary.enterprise_authority == "STOP"
        && whole.boundary.component_wiring == "STOP"
        && !whole.boundary.publish
}

fn pairwise_distinct<T: PartialEq>(values: &[T]) -> bool {
    values
        .iter()
        .enumerate()
        .all(|(index, value)| !values[index + 1..].contains(value))
}

fn canonical_identity(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
        && value.bytes().any(|byte| byte != b'0')
}

fn hex_sha256(bytes: &[u8]) -> String {
    let mut output = String::with_capacity(64);
    for byte in Sha256::digest(bytes) {
        use core::fmt::Write as _;
        write!(&mut output, "{byte:02x}").expect("String write cannot fail");
    }
    output
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CandidateWhole {
    schema: String,
    authority: bool,
    signed_subject: String,
    semantic_identity: String,
    projection: CandidateProjection,
    boundary: CandidateBoundary,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CandidateProjection {
    input_sha256: String,
    contract_sha256: String,
    domain_sha256: DomainDigests,
    target: String,
    route_identities: Vec<String>,
    termination_work_identities: Vec<String>,
    calibration_binary_sha256: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct DomainDigests {
    database: String,
    service: String,
    runtime: String,
    observability: String,
    admission: String,
    calibration: String,
}

impl DomainDigests {
    fn values(&self) -> Vec<&String> {
        vec![
            &self.database,
            &self.service,
            &self.runtime,
            &self.observability,
            &self.admission,
            &self.calibration,
        ]
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CandidateBoundary {
    signature: String,
    deployment_permit: String,
    enterprise_authority: String,
    component_wiring: String,
    publish: bool,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ValidationPermit {
    schema: String,
    authority_scope: String,
    source_candidate_identity: String,
    candidate_fact_whole_identity: String,
    candidate_semantic_identity: String,
    environment_identity: String,
    run_identity: String,
    reservation_identity: String,
    single_use: bool,
    minimum_terminal_stage: String,
    signing_authority: bool,
    enterprise_production_authority: bool,
    rust_skill_artifact_combination_authority: bool,
    component_production_wiring_authority: bool,
    publish_authority: bool,
    release_authority: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn changed_whole(change: impl FnOnce(&mut serde_json::Value)) -> &'static [u8] {
        let mut value: serde_json::Value =
            serde_json::from_slice(APPROVED_WHOLE).expect("approved whole is JSON");
        change(&mut value);
        Box::leak(
            serde_json::to_vec(&value)
                .expect("changed whole serializes")
                .into_boxed_slice(),
        )
    }

    fn changed_permit(change: impl FnOnce(&mut serde_json::Value)) -> &'static [u8] {
        let mut value: serde_json::Value =
            serde_json::from_slice(APPROVED_PERMIT).expect("approved permit is JSON");
        change(&mut value);
        Box::leak(
            serde_json::to_vec(&value)
                .expect("changed permit serializes")
                .into_boxed_slice(),
        )
    }

    fn reject_and_restore(whole: &'static [u8], permit: &'static [u8]) {
        let mut input = approved_trusted_candidate_set_input();
        input.whole = whole;
        input.permit = permit;
        let restored = match verify_trusted_candidate_set(input) {
            Ok(_) => panic!("invalid candidate set accepted"),
            Err(error) => error.into_input(),
        };
        assert!(core::ptr::eq(restored.whole, whole));
        assert!(core::ptr::eq(restored.permit, permit));
        assert_eq!(restored.whole, whole);
        assert_eq!(restored.permit, permit);
    }

    #[test]
    fn approved_set_is_complete_same_candidate_recoverable_and_one_shot() {
        for domain in [
            "database",
            "service",
            "runtime",
            "observability",
            "admission",
            "calibration",
        ] {
            reject_and_restore(
                changed_whole(|whole| {
                    whole["projection"]["domain_sha256"]
                        .as_object_mut()
                        .expect("domain map")
                        .remove(domain);
                }),
                APPROVED_PERMIT,
            );
            reject_and_restore(
                changed_whole(|whole| {
                    whole["projection"]["domain_sha256"][domain] =
                        serde_json::Value::String("0".repeat(64));
                }),
                APPROVED_PERMIT,
            );
        }
        reject_and_restore(
            changed_whole(|whole| {
                let database = whole["projection"]["domain_sha256"]["database"].clone();
                whole["projection"]["domain_sha256"]["observability"] = database;
            }),
            APPROVED_PERMIT,
        );
        reject_and_restore(
            changed_whole(|whole| {
                whole["semantic_identity"] = serde_json::Value::String(
                    "b51c2919246b7c214933f82aa29e96b2d279fd0e34a9ecaf77c1ce3234fe9bea".into(),
                );
            }),
            APPROVED_PERMIT,
        );
        reject_and_restore(
            changed_whole(|whole| {
                whole["projection"]["domain_sha256"]["observability"] = serde_json::Value::String(
                    "6e58f9a21935c6ccb18cee82fe65c298b1ee8ef20d3ca32a2600003c7be98103".into(),
                );
            }),
            APPROVED_PERMIT,
        );
        for field in [
            "source_candidate_identity",
            "candidate_fact_whole_identity",
            "candidate_semantic_identity",
            "environment_identity",
            "run_identity",
            "reservation_identity",
        ] {
            reject_and_restore(
                APPROVED_WHOLE,
                changed_permit(|permit| {
                    permit[field] = serde_json::Value::String("1".repeat(64));
                }),
            );
        }
        reject_and_restore(
            APPROVED_WHOLE,
            changed_permit(|permit| {
                permit["authority_scope"] =
                    serde_json::Value::String("foreign-listener-scope".into());
            }),
        );
        let owner = verify_trusted_candidate_set(approved_trusted_candidate_set_input())
            .unwrap_or_else(|_| panic!("approved set verifies"));
        assert!(verify_trusted_candidate_set(approved_trusted_candidate_set_input()).is_err());
        let input = rollback_trusted_candidate_set(owner);
        let retried = verify_trusted_candidate_set(input)
            .unwrap_or_else(|_| panic!("restored approved set retries"));
        let _ = rollback_trusted_candidate_set(retried);
    }
}