clm-kernel 0.0.21

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use super::*;

// Handshake Protocol over QUIC (Story 140.2.4)
// ---------------------------------------------------------------------------

/// Challenge message for DID challenge-response handshake (same format as TCP).
#[derive(Serialize)]
pub(super) struct ChallengeMessage<'a> {
    #[serde(rename = "type")]
    msg_type: &'static str,
    nonce: &'a str,
}

/// Response message for DID challenge-response handshake (same format as TCP).
#[derive(Deserialize)]
pub(super) struct ResponseMessage {
    #[serde(rename = "type")]
    msg_type: String,
    did: String,
    signature: String,
}

/// Perform a DID challenge-response handshake over QUIC.
///
/// This is the client side of the handshake. The client connects to a QUIC
/// server, receives a challenge nonce, signs it with its Ed25519 private key,
/// and sends the response back. The JSON message format is identical to the
/// TCP version in `discovery_engine.rs`.
///
/// # Arguments
/// * `endpoint` - The QUIC endpoint to use for the connection
/// * `server_addr` - The server address (e.g. "127.0.0.1:9095")
/// * `server_name` - The server name for TLS verification
/// * `did` - The client's DID
/// * `private_key_pem` - The client's Ed25519 private key in PKCS8 PEM format
pub async fn perform_quic_handshake(
    endpoint: &QuicEndpoint,
    server_addr: &str,
    server_name: &str,
    did: &str,
    private_key_pem: &str,
) -> Result<serde_json::Value, String> {
    use ed25519_dalek::{SigningKey, Signer};
    use ed25519_dalek::pkcs8::DecodePrivateKey;

    let conn = endpoint.connect(server_addr, server_name).await?;

    // Open a bidirectional stream for the handshake
    let (mut send_stream, mut recv_stream) = conn.conn
        .open_bi()
        .await
        .map_err(|e| format!("Failed to open handshake stream: {}", e))?;


    // Read challenge from server
    let challenge_buf = recv_stream.read_to_end(1024 * 1024)
        .await
        .map_err(|e| format!("Failed to read challenge: {}", e))?;

    let challenge_msg: serde_json::Value = serde_json::from_slice(&challenge_buf)
        .map_err(|e| format!("Failed to parse challenge JSON: {}", e))?;

    if challenge_msg["type"] != "challenge" {
        return Err("Protocol mismatch: expected challenge message".to_string());
    }

    let nonce = challenge_msg["nonce"].as_str()
        .ok_or_else(|| "Missing nonce in challenge message".to_string())?;

    // Parse private key and sign the nonce
    let signing_key = SigningKey::from_pkcs8_pem(private_key_pem)
        .map_err(|e| format!("Failed to parse private key: {}", e))?;

    let signature = signing_key.sign(nonce.as_bytes());
    let signature_hex = hex::encode(signature.to_bytes());

    // Send response
    let response = serde_json::json!({
        "type": "response",
        "did": did,
        "signature": signature_hex,
    });

    let response_bytes = serde_json::to_vec(&response)
        .map_err(|e| format!("Failed to serialize response: {}", e))?;

    send_stream.write_all(&response_bytes)
        .await
        .map_err(|e| format!("Failed to write response: {}", e))?;

    send_stream.finish()
        .map_err(|e| format!("Failed to finish send stream: {}", e))?;

    // Read final authorization
    let auth_buf = recv_stream.read_to_end(1024 * 1024)
        .await
        .map_err(|e| format!("Failed to read authorization: {}", e))?;

    let auth_result: serde_json::Value = serde_json::from_slice(&auth_buf)
        .map_err(|e| format!("Failed to parse authorization JSON: {}", e))?;

    Ok(auth_result)
}

/// Handle the server side of a DID challenge-response handshake over QUIC.
///
/// This is called by the QUIC server after accepting a bidirectional stream.
/// It generates a nonce, sends it as a challenge, reads the signed response,
/// and verifies the signature against the agent's public key in the identity DB.
///
/// # Arguments
/// * `send_stream` - The send side of the bidirectional QUIC stream
/// * `recv_stream` - The receive side of the bidirectional QUIC stream
/// * `db_path` - Path to the agent identity SQLite database
pub async fn handle_quic_handshake(
    mut send_stream: quinn::SendStream,
    mut recv_stream: quinn::RecvStream,
    db_path: &str,
) -> Result<serde_json::Value, String> {
    use ed25519_dalek::{VerifyingKey, Verifier, Signature};
    use ed25519_dalek::pkcs8::DecodePublicKey;

    // Generate challenge nonce
    let nonce = crate::discovery_engine::encode_hex(
        &crate::discovery_engine::generate_random_bytes(16),
    );

    let challenge = ChallengeMessage {
        msg_type: "challenge",
        nonce: &nonce,
    };

    let challenge_bytes = serde_json::to_vec(&challenge)
        .map_err(|e| format!("Failed to serialize challenge: {}", e))?;

    send_stream.write_all(&challenge_bytes)
        .await
        .map_err(|e| format!("Failed to send challenge: {}", e))?;

    send_stream.finish()
        .map_err(|e| format!("Failed to finish challenge stream: {}", e))?;

    // Wait for the next bidirectional stream for the response
    // Actually, we need to re-think this. In QUIC, we should use a single
    // bidirectional stream for the full handshake. Let me restructure.
    // For now, read the response from the recv stream.
    let response_buf = recv_stream.read_to_end(1024 * 1024)
        .await
        .map_err(|e| format!("Failed to read response: {}", e))?;

    let response: ResponseMessage = serde_json::from_slice(&response_buf)
        .map_err(|e| format!("Failed to parse response: {}", e))?;

    if response.msg_type != "response" {
        let rej = serde_json::json!({"status": "rejected", "reason": "invalid_protocol_step"});
        return Ok(rej);
    }

    // Look up agent card from DB
    let agent_card = match crate::discovery_engine::get_agent_card_from_db(db_path, &response.did) {
        Ok(Some(card)) => card,
        Ok(None) => {
            return Ok(serde_json::json!({"status": "rejected", "reason": "unauthorized_did"}));
        }
        Err(_) => {
            return Ok(serde_json::json!({"status": "rejected", "reason": "db_error"}));
        }
    };

    // Parse public key
    let public_key = match VerifyingKey::from_public_key_pem(&agent_card.public_key) {
        Ok(key) => key,
        Err(_) => {
            return Ok(serde_json::json!({"status": "rejected", "reason": "invalid_identity_profile"}));
        }
    };

    // Verify signature
    let signature_bytes = match crate::discovery_engine::decode_hex(&response.signature) {
        Ok(bytes) => bytes,
        Err(_) => {
            return Ok(serde_json::json!({"status": "rejected", "reason": "invalid_signature"}));
        }
    };

    let signature = match Signature::from_slice(&signature_bytes) {
        Ok(sig) => sig,
        Err(_) => {
            return Ok(serde_json::json!({"status": "rejected", "reason": "invalid_signature"}));
        }
    };

    if public_key.verify(nonce.as_bytes(), &signature).is_err() {
        return Ok(serde_json::json!({"status": "rejected", "reason": "invalid_signature"}));
    }

    // Authorized
    Ok(serde_json::json!({
        "status": "authorized",
        "did": response.did,
        "capabilities": agent_card.capabilities,
    }))
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

pub(super) fn build_server_crypto(cert: &TlsCertificate) -> Result<quinn::crypto::rustls::QuicServerConfig, String> {
    let cert_chain = vec![rustls::pki_types::CertificateDer::from(cert.cert_der.clone())];
    let private_key = rustls::pki_types::PrivateKeyDer::try_from(cert.key_der.clone())
        .map_err(|e| format!("Failed to parse private key: {}", e))?;

    let server_crypto = rustls::ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(cert_chain, private_key)
        .map_err(|e| format!("Failed to build server TLS config: {}", e))?;

    let quic_server_config = quinn::crypto::rustls::QuicServerConfig::try_from(server_crypto)
        .map_err(|e| format!("Failed to create QUIC server config: {}", e))?;

    Ok(quic_server_config)
}

#[allow(dead_code)]
pub(super) fn build_client_crypto() -> rustls::ClientConfig {
    // Development mode: use dangerous verifier that accepts self-signed certs.
    build_dangerous_client_crypto()
}

/// A dangerous client config that accepts any server certificate.
/// Used for development and testing only.
pub fn build_dangerous_client_crypto() -> rustls::ClientConfig {
    use rustls::client::danger::ServerCertVerifier;
    use std::sync::Arc;

    #[derive(Debug)]
    struct NoVerifier;

    impl ServerCertVerifier for NoVerifier {
        fn verify_server_cert(
            &self,
            _end_entity: &rustls::pki_types::CertificateDer<'_>,
            _intermediates: &[rustls::pki_types::CertificateDer<'_>],
            _server_name: &rustls::pki_types::ServerName<'_>,
            _ocsp_response: &[u8],
            _now: rustls::pki_types::UnixTime,
        ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
            Ok(rustls::client::danger::ServerCertVerified::assertion())
        }

        fn verify_tls12_signature(
            &self,
            _message: &[u8],
            _cert: &rustls::pki_types::CertificateDer<'_>,
            _dss: &rustls::DigitallySignedStruct,
        ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
            Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
        }

        fn verify_tls13_signature(
            &self,
            _message: &[u8],
            _cert: &rustls::pki_types::CertificateDer<'_>,
            _dss: &rustls::DigitallySignedStruct,
        ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
            Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
        }

        fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
            vec![
                rustls::SignatureScheme::ED25519,
                rustls::SignatureScheme::RSA_PSS_SHA256,
                rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
                rustls::SignatureScheme::RSA_PKCS1_SHA256,
            ]
        }
    }

    

    rustls::ClientConfig::builder()
        .dangerous()
        .with_custom_certificate_verifier(Arc::new(NoVerifier))
        .with_no_client_auth()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------