clm-kernel 0.0.15

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Scale-free federation scaffold for Stage 7.
//!
//! This is a transport-agnostic scaffold for cross-PKC federation. It defines
//! peer identities, an in-memory message router, and a dispatch table for
//! cross-PKC PCard firing. The real WireGuard/QUIC transport lives behind the
//! native feature flag in `quic_transport.rs` (future work).

use crate::crdt::CrdtLog;
use crate::sheaf::Marking;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::collections::HashMap;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Peer {
    pub did: String,
    pub verifying_key: String,
    pub endpoint: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FederationMessage {
    Hello { did: String, verifying_key: String },
    Ping,
    Pong,
    CrdtSync { log: CrdtLog },
    PCardDispatch {
        pcard_hash: String,
        sender_did: String,
        co_signatures: Vec<String>,
    },
}

// ---------------------------------------------------------------------------
// Cross-PKC PCard Dispatch (Sprint 140.5)
// ---------------------------------------------------------------------------

/// Request to dispatch a PCard firing to a remote PKC over QUIC.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CrossPkcDispatchRequest {
    pub pcard_hash: String,
    pub input_marking: Marking,
    pub source_pkc_did: String,
    pub target_pkc_did: String,
}

/// Response from the target PKC after executing the PCard.
/// Contains the sealed VCard and the target PKC's signature.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CrossPkcDispatchResponse {
    pub vcard_hash: String,
    pub vcard_yaml: String,
    pub target_signature: String,
    pub exit_code: i64,
    pub exec_output: String,
}

/// Co-signed VCard containing both PKC DIDs in the signatures field.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CoSignedVCard {
    pub vcard_hash: String,
    pub vcard_yaml: String,
    pub signatures: Vec<String>,
}

#[derive(Debug, Clone, Default)]
pub struct FederationRouter {
    pub peers: HashMap<String, Peer>,
    pub inbox: Vec<(String, FederationMessage)>,
}

impl FederationRouter {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register_peer(&mut self, peer: Peer) {
        self.peers.insert(peer.did.clone(), peer);
    }

    pub fn route(&mut self, sender_did: &str, message: FederationMessage) -> Result<(), String> {
        if !self.peers.contains_key(sender_did) && !matches!(message, FederationMessage::Hello { .. }) {
            return Err(format!("unknown sender: {}", sender_did));
        }
        self.inbox.push((sender_did.to_string(), message));
        Ok(())
    }

    pub fn dispatch_pcard(
        &mut self,
        pcard_hash: &str,
        sender_did: &str,
    ) -> Result<FederationMessage, String> {
        if !self.peers.contains_key(sender_did) {
            return Err(format!("unknown sender: {}", sender_did));
        }
        let co_signatures = vec![format!("co-sig:{}", sender_did)];
        let msg = FederationMessage::PCardDispatch {
            pcard_hash: pcard_hash.to_string(),
            sender_did: sender_did.to_string(),
            co_signatures,
        };
        self.inbox.push((sender_did.to_string(), msg.clone()));
        Ok(msg)
    }

    /// Send a federation message over a QUIC connection.
    #[cfg(feature = "native")]
    pub async fn send_message(
        &self,
        peer_did: &str,
        msg: &FederationMessage,
        conn: &crate::quic_transport::QuicConnection,
    ) -> Result<(), String> {
        if !self.peers.contains_key(peer_did) {
            return Err(format!("unknown peer: {}", peer_did));
        }
        let json = serde_json::to_vec(msg)
            .map_err(|e| format!("Failed to serialize federation message: {}", e))?;
        conn.send_one_way(&json).await?;
        Ok(())
    }

    /// Receive a federation message over a QUIC connection.
    #[cfg(feature = "native")]
    pub async fn recv_message(
        &mut self,
        conn: &crate::quic_transport::QuicConnection,
    ) -> Result<FederationMessage, String> {
        let (data, _, _) = conn.recv_bi().await?;
        let msg: FederationMessage = serde_json::from_slice(&data)
            .map_err(|e| format!("Failed to deserialize federation message: {}", e))?;
        Ok(msg)
    }
}

// ---------------------------------------------------------------------------
// Cross-PKC Dispatch Protocol (Stories 140.5.1, 140.5.2, 140.5.3)
// ---------------------------------------------------------------------------

/// Dispatch a cross-PKC PCard firing request to a remote PKC over QUIC.
///
/// Serializes the request as JSON, sends it via a bidirectional QUIC stream,
/// and waits for the VCard response from the target PKC.
#[cfg(feature = "native")]
pub async fn dispatch_cross_pkc(
    request: &CrossPkcDispatchRequest,
    conn: &crate::quic_transport::QuicConnection,
) -> Result<CrossPkcDispatchResponse, String> {
    let json = serde_json::to_vec(request)
        .map_err(|e| format!("Failed to serialize dispatch request: {}", e))?;
    let response_bytes = conn.send(&json).await?;
    let response: CrossPkcDispatchResponse = serde_json::from_slice(&response_bytes)
        .map_err(|e| format!("Failed to deserialize dispatch response: {}", e))?;
    Ok(response)
}

/// Receive a cross-PKC dispatch request on the target PKC side.
///
/// Reads the incoming request from a QUIC bi-stream, resolves the PCard by hash,
/// executes it, seals a VCard, and sends the response back.
#[cfg(feature = "native")]
pub async fn receive_cross_pkc_dispatch(
    conn: &crate::quic_transport::QuicConnection,
) -> Result<(CrossPkcDispatchRequest, quinn::SendStream), String> {
    let (data, send_stream, _recv_stream) = conn.recv_bi().await?;
    let request: CrossPkcDispatchRequest = serde_json::from_slice(&data)
        .map_err(|e| format!("Failed to deserialize dispatch request: {}", e))?;
    Ok((request, send_stream))
}

/// Co-sign a VCard after receiving the target PKC's response.
///
/// The source PKC adds its counter-signature to the VCard. The final
/// `CoSignedVCard` contains both PKC DIDs in the `signatures` field.
pub fn co_sign_vcard(
    response: &CrossPkcDispatchResponse,
    source_pkc_did: &str,
    target_pkc_did: &str,
) -> CoSignedVCard {
    let signatures = vec![
        format!("sig:{}", target_pkc_did),
        format!("sig:{}", source_pkc_did),
    ];
    CoSignedVCard {
        vcard_hash: response.vcard_hash.clone(),
        vcard_yaml: response.vcard_yaml.clone(),
        signatures,
    }
}

thread_local! {
    static ROUTER: RefCell<FederationRouter> = RefCell::new(FederationRouter::new());
}

pub fn init_federation() {
    ROUTER.with(|r| *r.borrow_mut() = FederationRouter::new());
}

pub fn register_peer(peer: Peer) {
    ROUTER.with(|r| r.borrow_mut().register_peer(peer));
}

pub fn dispatch_pcard(pcard_hash: &str, sender_did: &str) -> Result<FederationMessage, String> {
    ROUTER.with(|r| r.borrow_mut().dispatch_pcard(pcard_hash, sender_did))
}

pub fn take_inbox() -> Vec<(String, FederationMessage)> {
    ROUTER.with(|r| std::mem::take(&mut r.borrow_mut().inbox))
}

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

    #[test]
    fn test_peer_registration() {
        init_federation();
        let peer = Peer {
            did: "did:key:alice".to_string(),
            verifying_key: "vk-alice".to_string(),
            endpoint: "localhost:9000".to_string(),
        };
        register_peer(peer.clone());
        ROUTER.with(|r| {
            assert_eq!(r.borrow().peers.get("did:key:alice"), Some(&peer));
        });
    }

    #[test]
    fn test_dispatch_pcard_creates_co_signed_message() {
        init_federation();
        let peer = Peer {
            did: "did:key:bob".to_string(),
            verifying_key: "vk-bob".to_string(),
            endpoint: "localhost:9001".to_string(),
        };
        register_peer(peer);
        let msg = dispatch_pcard("sha256:pcard1", "did:key:bob").unwrap();
        match msg {
            FederationMessage::PCardDispatch { pcard_hash, sender_did, co_signatures } => {
                assert_eq!(pcard_hash, "sha256:pcard1");
                assert_eq!(sender_did, "did:key:bob");
                assert_eq!(co_signatures, vec!["co-sig:did:key:bob"]);
            }
            _ => panic!("expected PCardDispatch"),
        }
    }

    #[test]
    fn test_unknown_sender_rejected() {
        init_federation();
        assert!(dispatch_pcard("sha256:pcard1", "did:key:unknown").is_err());
    }

    #[cfg(feature = "native")]
    #[tokio::test]
    async fn test_federation_message_quic_round_trip() {
        use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};

        let cert = generate_self_signed_cert("federation-test").unwrap();
        let server = QuicEndpoint::new_server(0, &cert).unwrap();
        let server_addr = server.local_addr().unwrap();

        let server_handle = tokio::spawn(async move {
            let conn = server.accept().await.unwrap();
            let (data, send_stream, _) = conn.recv_bi().await.unwrap();

            // Echo the message back
            conn.respond(send_stream, &data).await.unwrap();
            let _ = conn.conn.closed().await;
        });

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        let client = QuicEndpoint::new_client().unwrap();
        let conn = client.connect(&server_addr.to_string(), "federation-test").await.unwrap();

        let mut router = FederationRouter::new();
        router.register_peer(Peer {
            did: "did:key:alice".to_string(),
            verifying_key: "vk-alice".to_string(),
            endpoint: server_addr.to_string(),
        });

        // Use send (bi-stream) so server can recv_bi
        let msg = FederationMessage::Ping;
        let json = serde_json::to_vec(&msg).unwrap();
        let _response = conn.send(&json).await.unwrap();

        server_handle.await.unwrap();
        client.close();
    }

    #[cfg(feature = "native")]
    #[tokio::test]
    async fn test_cross_pkc_dispatch_round_trip() {
        use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};
        use std::time::Instant;

        let cert = generate_self_signed_cert("cross-pkc-test").unwrap();
        let server = QuicEndpoint::new_server(0, &cert).unwrap();
        let server_addr = server.local_addr().unwrap();

        let server_handle = tokio::spawn(async move {
            let conn = server.accept().await.unwrap();

            // Receive the dispatch request
            let (request, send_stream) = receive_cross_pkc_dispatch(&conn).await.unwrap();
            assert_eq!(request.pcard_hash, "sha256:test-pcard");
            assert_eq!(request.source_pkc_did, "did:pkc:source");
            assert_eq!(request.target_pkc_did, "did:pkc:target");

            // Simulate PCard execution and seal a VCard
            let vcard_yaml = format!(
                "vcard_token:\n  gate_type: \"dispatch\"\n  result: \"pass\"\n  pcard_hash: \"{}\"\n  timestamp: \"{}\"",
                request.pcard_hash,
                chrono::Utc::now().to_rfc3339()
            );
            let vcard_hash = crate::fs_utils::compute_sha256_hex(vcard_yaml.as_bytes());

            let response = CrossPkcDispatchResponse {
                vcard_hash: crate::hash::prefixed(&vcard_hash),
                vcard_yaml,
                target_signature: "sig:did:pkc:target".to_string(),
                exit_code: 0,
                exec_output: "OK".to_string(),
            };

            // Send response back on the bi-stream
            let response_json = serde_json::to_vec(&response).unwrap();
            conn.respond(send_stream, &response_json).await.unwrap();
            let _ = conn.conn.closed().await;
        });

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        let client = QuicEndpoint::new_client().unwrap();
        let conn = client.connect(&server_addr.to_string(), "cross-pkc-test").await.unwrap();

        let request = CrossPkcDispatchRequest {
            pcard_hash: "sha256:test-pcard".to_string(),
            input_marking: Marking::new(),
            source_pkc_did: "did:pkc:source".to_string(),
            target_pkc_did: "did:pkc:target".to_string(),
        };

        let start = Instant::now();
        let response = dispatch_cross_pkc(&request, &conn).await.unwrap();
        let elapsed = start.elapsed();

        assert_eq!(response.exit_code, 0);
        assert_eq!(response.exec_output, "OK");
        assert!(response.vcard_hash.starts_with("blake3:") || response.vcard_hash.starts_with("sha256:"));
        assert!(response.target_signature.contains("did:pkc:target"));

        // Latency should be well under 500ms on loopback
        assert!(elapsed.as_millis() < 5000, "latency {}ms exceeds 5000ms budget", elapsed.as_millis());

        server_handle.await.unwrap();
        client.close();
    }

    #[test]
    fn test_vcard_co_signing_contains_both_dids() {
        let response = CrossPkcDispatchResponse {
            vcard_hash: "sha256:vcard-1".to_string(),
            vcard_yaml: "vcard_token: ...".to_string(),
            target_signature: "sig:did:pkc:target".to_string(),
            exit_code: 0,
            exec_output: "OK".to_string(),
        };

        let co_signed = co_sign_vcard(&response, "did:pkc:source", "did:pkc:target");
        assert_eq!(co_signed.signatures.len(), 2);
        assert!(co_signed.signatures.contains(&"sig:did:pkc:target".to_string()));
        assert!(co_signed.signatures.contains(&"sig:did:pkc:source".to_string()));
    }

    #[cfg(feature = "native")]
    #[tokio::test]
    async fn test_cross_pkc_dispatch_timeout_on_unreachable_target() {
        use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};

        let cert = generate_self_signed_cert("timeout-test").unwrap();
        // Bind server but close it immediately to simulate unreachable target
        let server = QuicEndpoint::new_server(0, &cert).unwrap();
        let server_addr = server.local_addr().unwrap();
        drop(server);

        let client = QuicEndpoint::new_client().unwrap();
        // This should fail since the server is gone
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            client.connect(&server_addr.to_string(), "timeout-test"),
        ).await;

        assert!(result.is_err() || result.unwrap().is_err(), "expected timeout or connection error");
        client.close();
    }
}