clm-kernel 0.0.18

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! QUIC Transport Layer for Sprint 140.2.
//!
//! Provides a QUIC transport using `quinn` with self-signed TLS certificates
//! from `rcgen`. Implements `QuicEndpoint` (server/client), `QuicConnection`
//! (bidirectional streams), and ports the DID challenge-response handshake
//! from TCP to QUIC.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────┐     QUIC      ┌─────────────┐
//! │ QuicEndpoint│◄────────────►│ QuicEndpoint│
//! │  (server)   │   (TLS 1.3)   │  (client)   │
//! └──────┬──────┘               └──────┬──────┘
//!        │                             │
//!        ▼                             ▼
//! ┌─────────────┐              ┌─────────────┐
//! │QuicConnection│             │QuicConnection│
//! │ (bi-streams) │             │ (bi-streams) │
//! └─────────────┘              └─────────────┘
//! ```

use std::net::SocketAddr;
use std::sync::Arc;
use serde::{Serialize, Deserialize};

// Install the ring crypto provider for rustls (required by rustls 0.23)
fn ensure_crypto_provider() {
    let _ = rustls::crypto::ring::default_provider().install_default();
}

// ---------------------------------------------------------------------------
// TLS Certificate Generation (Story 140.2.3)
// ---------------------------------------------------------------------------

/// A self-signed TLS certificate and its corresponding private key.
/// Used to configure QUIC endpoints for encrypted communication.
pub struct TlsCertificate {
    pub cert_der: Vec<u8>,
    pub key_der: Vec<u8>,
    pub subject: String,
}

/// Generate a self-signed TLS certificate using `rcgen`.
///
/// The certificate uses an Ed25519 key (same curve as the CLM DID system)
/// and is suitable for QUIC/TLS 1.3 server authentication.
///
/// # Arguments
/// * `subject` - The subject name for the certificate (e.g. "pkc-node-1")
///
/// # Returns
/// A `TlsCertificate` containing the DER-encoded certificate and private key.
pub fn generate_self_signed_cert(subject: &str) -> Result<TlsCertificate, String> {
    use rcgen::{CertificateParams, KeyPair, PKCS_ED25519};

    let params = CertificateParams::new(vec![subject.to_string()])
        .map_err(|e| format!("Failed to create cert params: {}", e))?;

    let key_pair = KeyPair::generate_for(&PKCS_ED25519)
        .map_err(|e| format!("Failed to generate key pair: {}", e))?;

    let cert = params.self_signed(&key_pair)
        .map_err(|e| format!("Failed to self-sign certificate: {}", e))?;

    let cert_der = cert.der().to_vec();
    let key_der = key_pair.serialize_der();

    Ok(TlsCertificate {
        cert_der,
        key_der,
        subject: subject.to_string(),
    })
}

// ---------------------------------------------------------------------------
// QuicEndpoint (Story 140.2.1)
// ---------------------------------------------------------------------------

/// A QUIC endpoint that can act as both server and client.
///
/// Wraps `quinn::Endpoint` and holds the server configuration (if any).
/// The endpoint binds to a UDP port and can accept incoming QUIC connections
/// or initiate outgoing connections.
pub struct QuicEndpoint {
    endpoint: quinn::Endpoint,
    #[allow(dead_code)]
    server_config: Option<quinn::ServerConfig>,
}

impl QuicEndpoint {
    /// Create a QUIC server endpoint bound to the specified port.
    ///
    /// The server uses the provided TLS certificate for encrypted QUIC
    /// connections. It can both accept incoming connections and initiate
    /// outgoing connections.
    ///
    /// # Arguments
    /// * `port` - The UDP port to bind to
    /// * `cert` - The TLS certificate for server authentication
    pub fn new_server(port: u16, cert: &TlsCertificate) -> Result<Self, String> {
        ensure_crypto_provider();
        let server_crypto = build_server_crypto(cert)?;
        let server_config = quinn::ServerConfig::with_crypto(Arc::new(server_crypto));

        let bind_addr: SocketAddr = format!("127.0.0.1:{}", port)
            .parse()
            .map_err(|e| format!("Invalid bind address: {}", e))?;

        let endpoint = quinn::Endpoint::server(server_config.clone(), bind_addr)
            .map_err(|e| format!("Failed to bind QUIC endpoint to {}: {}", bind_addr, e))?;

        Ok(Self {
            endpoint,
            server_config: Some(server_config),
        })
    }

    /// Create a QUIC client endpoint that can connect to servers.
    ///
    /// The client is configured to accept self-signed certificates
    /// (development mode). In production, a proper CA chain should be used.
    pub fn new_client() -> Result<Self, String> {
        ensure_crypto_provider();
        let bind_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let endpoint = quinn::Endpoint::client(bind_addr)
            .map_err(|e| format!("Failed to create client endpoint: {}", e))?;

        Ok(Self {
            endpoint,
            server_config: None,
        })
    }

    /// Create a QUIC client endpoint with explicit client config.
    pub fn new_client_with_config() -> Result<Self, String> {
        ensure_crypto_provider();
        let bind_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let endpoint = quinn::Endpoint::client(bind_addr)
            .map_err(|e| format!("Failed to create client endpoint: {}", e))?;

        Ok(Self {
            endpoint,
            server_config: None,
        })
    }

    /// Connect to a remote QUIC server.
    ///
    /// # Arguments
    /// * `addr` - The server address to connect to
    /// * `server_name` - The server name for TLS verification (matches cert subject)
    pub async fn connect(&self, addr: &str, server_name: &str) -> Result<QuicConnection, String> {
        ensure_crypto_provider();
        let client_crypto = build_dangerous_client_crypto();
        let quic_client_config = quinn::crypto::rustls::QuicClientConfig::try_from(client_crypto)
            .map_err(|e| format!("Failed to create QUIC client config: {}", e))?;
        let client_config = quinn::ClientConfig::new(Arc::new(quic_client_config));

        let socket_addr: SocketAddr = addr
            .parse()
            .map_err(|e| format!("Invalid server address {}: {}", addr, e))?;

        let connection = self.endpoint
            .connect_with(client_config, socket_addr, server_name)
            .map_err(|e| format!("Failed to initiate connection: {}", e))?
            .await
            .map_err(|e| format!("QUIC connection failed: {}", e))?;

        Ok(QuicConnection { conn: connection })
    }

    /// Accept an incoming QUIC connection.
    pub async fn accept(&self) -> Result<QuicConnection, String> {
        let incoming = self.endpoint.accept()
            .await
            .ok_or_else(|| "No incoming QUIC connection".to_string())?;

        let connection = incoming.await
            .map_err(|e| format!("Failed to accept QUIC connection: {}", e))?;

        Ok(QuicConnection { conn: connection })
    }

    /// Get the local address the endpoint is bound to.
    pub fn local_addr(&self) -> Result<SocketAddr, String> {
        self.endpoint.local_addr()
            .map_err(|e| format!("Failed to get local addr: {}", e))
    }

    /// Close the endpoint and stop accepting connections.
    pub fn close(&self) {
        self.endpoint.close(0u32.into(), b"shutdown");
    }

    /// Accept an incoming QUIC connection with support for cancellation.
    pub async fn accept_with_cancellation(
        &self,
        token: &tokio_util::sync::CancellationToken,
    ) -> Result<Option<QuicConnection>, String> {
        tokio::select! {
            _ = token.cancelled() => Ok(None),
            res = self.accept() => res.map(Some),
        }
    }

    /// Run an accept loop with a CancellationToken until cancelled.
    pub async fn run_accept_loop<F, Fut>(
        &self,
        token: tokio_util::sync::CancellationToken,
        handler: F,
    ) -> Result<(), String>
    where
        F: Fn(QuicConnection) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = ()> + Send + 'static,
    {
        loop {
            tokio::select! {
                _ = token.cancelled() => {
                    self.close();
                    break;
                }
                res = self.accept() => {
                    match res {
                        Ok(conn) => {
                            tokio::spawn(handler(conn));
                        }
                        Err(e) => {
                            if token.is_cancelled() {
                                break;
                            }
                            return Err(e);
                        }
                    }
                }
            }
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// QuicConnection (Story 140.2.2)
// ---------------------------------------------------------------------------

/// A QUIC connection wrapping `quinn::Connection`.
///
/// Supports bidirectional streams for sending and receiving data.
/// Multiple streams can be multiplexed over a single connection.
pub struct QuicConnection {
    pub conn: quinn::Connection,
}

impl QuicConnection {
    /// Send data over a new bidirectional stream and return the stream ID.
    ///
    /// Opens a new bidirectional QUIC stream, writes the data, and closes
    /// the send side. The receive side remains open for the peer's response.
    pub async fn send(&self, data: &[u8]) -> Result<Vec<u8>, String> {
        let (mut send_stream, mut recv_stream) = self.conn
            .open_bi()
            .await
            .map_err(|e| format!("Failed to open bidirectional stream: {}", e))?;

        send_stream.write_all(data)
            .await
            .map_err(|e| format!("Failed to write to QUIC stream: {}", e))?;

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

        let response = recv_stream.read_to_end(1024 * 1024)
            .await
            .map_err(|e| format!("Failed to read response from QUIC stream: {}", e))?;

        Ok(response)
    }

    /// Send data and don't wait for a response (fire-and-forget).
    pub async fn send_one_way(&self, data: &[u8]) -> Result<(), String> {
        let mut send_stream = self.conn
            .open_uni()
            .await
            .map_err(|e| format!("Failed to open unidirectional stream: {}", e))?;

        send_stream.write_all(data)
            .await
            .map_err(|e| format!("Failed to write to QUIC stream: {}", e))?;

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

        Ok(())
    }

    /// Receive data from a bidirectional stream opened by the peer.
    ///
    /// This is used on the server side to read incoming requests and send
    /// responses back.
    pub async fn recv_bi(&self) -> Result<(Vec<u8>, quinn::SendStream, quinn::RecvStream), String> {
        let (send_stream, mut recv_stream) = self.conn
            .accept_bi()
            .await
            .map_err(|e| format!("Failed to accept bidirectional stream: {}", e))?;

        let data = recv_stream.read_to_end(1024 * 1024)
            .await
            .map_err(|e| format!("Failed to read from QUIC stream: {}", e))?;

        Ok((data, send_stream, recv_stream))
    }

    /// Send a response back on a bidirectional stream.
    pub async fn respond(
        &self,
        mut send_stream: quinn::SendStream,
        data: &[u8],
    ) -> Result<(), String> {

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

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

        Ok(())
    }

    /// Get the remote peer's address.
    pub fn remote_address(&self) -> SocketAddr {
        self.conn.remote_address()
    }

    /// Get the connection's stable ID.
    pub fn stable_id(&self) -> usize {
        self.conn.stable_id()
    }

    /// Close the connection.
    pub fn close(&self, reason: &str) {
        self.conn.close(0u32.into(), reason.as_bytes());
    }
}

// ---------------------------------------------------------------------------

#[path = "quic_transport_handshake.rs"]
mod quic_transport_handshake;
#[allow(unused_imports)]
pub use quic_transport_handshake::*;
#[cfg(test)]
#[path = "quic_transport_tests.rs"]
mod tests;