Skip to main content

clm_rust_core/layer3/
federation.rs

1//! Scale-free federation scaffold for Stage 7.
2//!
3//! This is a transport-agnostic scaffold for cross-PKC federation. It defines
4//! peer identities, an in-memory message router, and a dispatch table for
5//! cross-PKC PCard firing. The real WireGuard/QUIC transport lives behind the
6//! native feature flag in `quic_transport.rs` (future work).
7
8use crate::crdt::CrdtLog;
9use crate::sheaf::Marking;
10use serde::{Deserialize, Serialize};
11use std::cell::RefCell;
12use std::collections::HashMap;
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct Peer {
16    pub did: String,
17    pub verifying_key: String,
18    pub endpoint: String,
19}
20
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub enum FederationMessage {
23    Hello { did: String, verifying_key: String },
24    Ping,
25    Pong,
26    CrdtSync { log: CrdtLog },
27    PCardDispatch {
28        pcard_hash: String,
29        sender_did: String,
30        co_signatures: Vec<String>,
31    },
32}
33
34// ---------------------------------------------------------------------------
35// Cross-PKC PCard Dispatch (Sprint 140.5)
36// ---------------------------------------------------------------------------
37
38/// Request to dispatch a PCard firing to a remote PKC over QUIC.
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
40pub struct CrossPkcDispatchRequest {
41    pub pcard_hash: String,
42    pub input_marking: Marking,
43    pub source_pkc_did: String,
44    pub target_pkc_did: String,
45}
46
47/// Response from the target PKC after executing the PCard.
48/// Contains the sealed VCard and the target PKC's signature.
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50pub struct CrossPkcDispatchResponse {
51    pub vcard_hash: String,
52    pub vcard_yaml: String,
53    pub target_signature: String,
54    pub exit_code: i64,
55    pub exec_output: String,
56}
57
58/// Co-signed VCard containing both PKC DIDs in the signatures field.
59#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
60pub struct CoSignedVCard {
61    pub vcard_hash: String,
62    pub vcard_yaml: String,
63    pub signatures: Vec<String>,
64}
65
66#[derive(Debug, Clone, Default)]
67pub struct FederationRouter {
68    pub peers: HashMap<String, Peer>,
69    pub inbox: Vec<(String, FederationMessage)>,
70}
71
72impl FederationRouter {
73    pub fn new() -> Self {
74        Self::default()
75    }
76
77    pub fn register_peer(&mut self, peer: Peer) {
78        self.peers.insert(peer.did.clone(), peer);
79    }
80
81    pub fn route(&mut self, sender_did: &str, message: FederationMessage) -> Result<(), String> {
82        if !self.peers.contains_key(sender_did) && !matches!(message, FederationMessage::Hello { .. }) {
83            return Err(format!("unknown sender: {}", sender_did));
84        }
85        self.inbox.push((sender_did.to_string(), message));
86        Ok(())
87    }
88
89    pub fn dispatch_pcard(
90        &mut self,
91        pcard_hash: &str,
92        sender_did: &str,
93    ) -> Result<FederationMessage, String> {
94        if !self.peers.contains_key(sender_did) {
95            return Err(format!("unknown sender: {}", sender_did));
96        }
97        let co_signatures = vec![format!("co-sig:{}", sender_did)];
98        let msg = FederationMessage::PCardDispatch {
99            pcard_hash: pcard_hash.to_string(),
100            sender_did: sender_did.to_string(),
101            co_signatures,
102        };
103        self.inbox.push((sender_did.to_string(), msg.clone()));
104        Ok(msg)
105    }
106
107    /// Send a federation message over a QUIC connection.
108    #[cfg(feature = "native")]
109    pub async fn send_message(
110        &self,
111        peer_did: &str,
112        msg: &FederationMessage,
113        conn: &crate::quic_transport::QuicConnection,
114    ) -> Result<(), String> {
115        if !self.peers.contains_key(peer_did) {
116            return Err(format!("unknown peer: {}", peer_did));
117        }
118        let json = serde_json::to_vec(msg)
119            .map_err(|e| format!("Failed to serialize federation message: {}", e))?;
120        conn.send_one_way(&json).await?;
121        Ok(())
122    }
123
124    /// Receive a federation message over a QUIC connection.
125    #[cfg(feature = "native")]
126    pub async fn recv_message(
127        &mut self,
128        conn: &crate::quic_transport::QuicConnection,
129    ) -> Result<FederationMessage, String> {
130        let (data, _, _) = conn.recv_bi().await?;
131        let msg: FederationMessage = serde_json::from_slice(&data)
132            .map_err(|e| format!("Failed to deserialize federation message: {}", e))?;
133        Ok(msg)
134    }
135}
136
137// ---------------------------------------------------------------------------
138// Cross-PKC Dispatch Protocol (Stories 140.5.1, 140.5.2, 140.5.3)
139// ---------------------------------------------------------------------------
140
141/// Dispatch a cross-PKC PCard firing request to a remote PKC over QUIC.
142///
143/// Serializes the request as JSON, sends it via a bidirectional QUIC stream,
144/// and waits for the VCard response from the target PKC.
145#[cfg(feature = "native")]
146pub async fn dispatch_cross_pkc(
147    request: &CrossPkcDispatchRequest,
148    conn: &crate::quic_transport::QuicConnection,
149) -> Result<CrossPkcDispatchResponse, String> {
150    let json = serde_json::to_vec(request)
151        .map_err(|e| format!("Failed to serialize dispatch request: {}", e))?;
152    let response_bytes = conn.send(&json).await?;
153    let response: CrossPkcDispatchResponse = serde_json::from_slice(&response_bytes)
154        .map_err(|e| format!("Failed to deserialize dispatch response: {}", e))?;
155    Ok(response)
156}
157
158/// Receive a cross-PKC dispatch request on the target PKC side.
159///
160/// Reads the incoming request from a QUIC bi-stream, resolves the PCard by hash,
161/// executes it, seals a VCard, and sends the response back.
162#[cfg(feature = "native")]
163pub async fn receive_cross_pkc_dispatch(
164    conn: &crate::quic_transport::QuicConnection,
165) -> Result<(CrossPkcDispatchRequest, quinn::SendStream), String> {
166    let (data, send_stream, _recv_stream) = conn.recv_bi().await?;
167    let request: CrossPkcDispatchRequest = serde_json::from_slice(&data)
168        .map_err(|e| format!("Failed to deserialize dispatch request: {}", e))?;
169    Ok((request, send_stream))
170}
171
172/// Co-sign a VCard after receiving the target PKC's response.
173///
174/// The source PKC adds its counter-signature to the VCard. The final
175/// `CoSignedVCard` contains both PKC DIDs in the `signatures` field.
176pub fn co_sign_vcard(
177    response: &CrossPkcDispatchResponse,
178    source_pkc_did: &str,
179    target_pkc_did: &str,
180) -> CoSignedVCard {
181    let signatures = vec![
182        format!("sig:{}", target_pkc_did),
183        format!("sig:{}", source_pkc_did),
184    ];
185    CoSignedVCard {
186        vcard_hash: response.vcard_hash.clone(),
187        vcard_yaml: response.vcard_yaml.clone(),
188        signatures,
189    }
190}
191
192thread_local! {
193    static ROUTER: RefCell<FederationRouter> = RefCell::new(FederationRouter::new());
194}
195
196pub fn init_federation() {
197    ROUTER.with(|r| *r.borrow_mut() = FederationRouter::new());
198}
199
200pub fn register_peer(peer: Peer) {
201    ROUTER.with(|r| r.borrow_mut().register_peer(peer));
202}
203
204pub fn dispatch_pcard(pcard_hash: &str, sender_did: &str) -> Result<FederationMessage, String> {
205    ROUTER.with(|r| r.borrow_mut().dispatch_pcard(pcard_hash, sender_did))
206}
207
208pub fn take_inbox() -> Vec<(String, FederationMessage)> {
209    ROUTER.with(|r| std::mem::take(&mut r.borrow_mut().inbox))
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn test_peer_registration() {
218        init_federation();
219        let peer = Peer {
220            did: "did:key:alice".to_string(),
221            verifying_key: "vk-alice".to_string(),
222            endpoint: "localhost:9000".to_string(),
223        };
224        register_peer(peer.clone());
225        ROUTER.with(|r| {
226            assert_eq!(r.borrow().peers.get("did:key:alice"), Some(&peer));
227        });
228    }
229
230    #[test]
231    fn test_dispatch_pcard_creates_co_signed_message() {
232        init_federation();
233        let peer = Peer {
234            did: "did:key:bob".to_string(),
235            verifying_key: "vk-bob".to_string(),
236            endpoint: "localhost:9001".to_string(),
237        };
238        register_peer(peer);
239        let msg = dispatch_pcard("sha256:pcard1", "did:key:bob").unwrap();
240        match msg {
241            FederationMessage::PCardDispatch { pcard_hash, sender_did, co_signatures } => {
242                assert_eq!(pcard_hash, "sha256:pcard1");
243                assert_eq!(sender_did, "did:key:bob");
244                assert_eq!(co_signatures, vec!["co-sig:did:key:bob"]);
245            }
246            _ => panic!("expected PCardDispatch"),
247        }
248    }
249
250    #[test]
251    fn test_unknown_sender_rejected() {
252        init_federation();
253        assert!(dispatch_pcard("sha256:pcard1", "did:key:unknown").is_err());
254    }
255
256    #[cfg(feature = "native")]
257    #[tokio::test]
258    async fn test_federation_message_quic_round_trip() {
259        use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};
260
261        let cert = generate_self_signed_cert("federation-test").unwrap();
262        let server = QuicEndpoint::new_server(0, &cert).unwrap();
263        let server_addr = server.local_addr().unwrap();
264
265        let server_handle = tokio::spawn(async move {
266            let conn = server.accept().await.unwrap();
267            let (data, send_stream, _) = conn.recv_bi().await.unwrap();
268
269            // Echo the message back
270            conn.respond(send_stream, &data).await.unwrap();
271            let _ = conn.conn.closed().await;
272        });
273
274        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
275        let client = QuicEndpoint::new_client().unwrap();
276        let conn = client.connect(&server_addr.to_string(), "federation-test").await.unwrap();
277
278        let mut router = FederationRouter::new();
279        router.register_peer(Peer {
280            did: "did:key:alice".to_string(),
281            verifying_key: "vk-alice".to_string(),
282            endpoint: server_addr.to_string(),
283        });
284
285        // Use send (bi-stream) so server can recv_bi
286        let msg = FederationMessage::Ping;
287        let json = serde_json::to_vec(&msg).unwrap();
288        let _response = conn.send(&json).await.unwrap();
289
290        // Close first: the server task waits for this close, so awaiting it
291        // before closing held each test for the 30 s QUIC idle timeout (INV-588).
292        client.close();
293        server_handle.await.unwrap();
294    }
295
296    #[cfg(feature = "native")]
297    #[tokio::test]
298    async fn test_cross_pkc_dispatch_round_trip() {
299        use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};
300        use std::time::Instant;
301
302        let cert = generate_self_signed_cert("cross-pkc-test").unwrap();
303        let server = QuicEndpoint::new_server(0, &cert).unwrap();
304        let server_addr = server.local_addr().unwrap();
305
306        let server_handle = tokio::spawn(async move {
307            let conn = server.accept().await.unwrap();
308
309            // Receive the dispatch request
310            let (request, send_stream) = receive_cross_pkc_dispatch(&conn).await.unwrap();
311            assert_eq!(request.pcard_hash, "sha256:test-pcard");
312            assert_eq!(request.source_pkc_did, "did:pkc:source");
313            assert_eq!(request.target_pkc_did, "did:pkc:target");
314
315            // Simulate PCard execution and seal a VCard
316            let vcard_yaml = format!(
317                "vcard_token:\n  gate_type: \"dispatch\"\n  result: \"pass\"\n  pcard_hash: \"{}\"\n  timestamp: \"{}\"",
318                request.pcard_hash,
319                chrono::Utc::now().to_rfc3339()
320            );
321            let vcard_hash = crate::fs_utils::compute_sha256_hex(vcard_yaml.as_bytes());
322
323            let response = CrossPkcDispatchResponse {
324                vcard_hash: crate::hash::prefixed(&vcard_hash),
325                vcard_yaml,
326                target_signature: "sig:did:pkc:target".to_string(),
327                exit_code: 0,
328                exec_output: "OK".to_string(),
329            };
330
331            // Send response back on the bi-stream
332            let response_json = serde_json::to_vec(&response).unwrap();
333            conn.respond(send_stream, &response_json).await.unwrap();
334            let _ = conn.conn.closed().await;
335        });
336
337        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
338        let client = QuicEndpoint::new_client().unwrap();
339        let conn = client.connect(&server_addr.to_string(), "cross-pkc-test").await.unwrap();
340
341        let request = CrossPkcDispatchRequest {
342            pcard_hash: "sha256:test-pcard".to_string(),
343            input_marking: Marking::new(),
344            source_pkc_did: "did:pkc:source".to_string(),
345            target_pkc_did: "did:pkc:target".to_string(),
346        };
347
348        let start = Instant::now();
349        let response = dispatch_cross_pkc(&request, &conn).await.unwrap();
350        let elapsed = start.elapsed();
351
352        assert_eq!(response.exit_code, 0);
353        assert_eq!(response.exec_output, "OK");
354        assert!(response.vcard_hash.starts_with("blake3:") || response.vcard_hash.starts_with("sha256:"));
355        assert!(response.target_signature.contains("did:pkc:target"));
356
357        // Latency should be well under 500ms on loopback
358        assert!(elapsed.as_millis() < 5000, "latency {}ms exceeds 5000ms budget", elapsed.as_millis());
359
360        // Close first: the server task waits for this close, so awaiting it
361        // before closing held each test for the 30 s QUIC idle timeout (INV-588).
362        client.close();
363        server_handle.await.unwrap();
364    }
365
366    #[test]
367    fn test_vcard_co_signing_contains_both_dids() {
368        let response = CrossPkcDispatchResponse {
369            vcard_hash: "sha256:vcard-1".to_string(),
370            vcard_yaml: "vcard_token: ...".to_string(),
371            target_signature: "sig:did:pkc:target".to_string(),
372            exit_code: 0,
373            exec_output: "OK".to_string(),
374        };
375
376        let co_signed = co_sign_vcard(&response, "did:pkc:source", "did:pkc:target");
377        assert_eq!(co_signed.signatures.len(), 2);
378        assert!(co_signed.signatures.contains(&"sig:did:pkc:target".to_string()));
379        assert!(co_signed.signatures.contains(&"sig:did:pkc:source".to_string()));
380    }
381
382    #[cfg(feature = "native")]
383    #[tokio::test]
384    async fn test_cross_pkc_dispatch_timeout_on_unreachable_target() {
385        use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};
386
387        let cert = generate_self_signed_cert("timeout-test").unwrap();
388        // Bind server but close it immediately to simulate unreachable target
389        let server = QuicEndpoint::new_server(0, &cert).unwrap();
390        let server_addr = server.local_addr().unwrap();
391        drop(server);
392
393        let client = QuicEndpoint::new_client().unwrap();
394        // This should fail since the server is gone
395        let result = tokio::time::timeout(
396            std::time::Duration::from_secs(5),
397            client.connect(&server_addr.to_string(), "timeout-test"),
398        ).await;
399
400        assert!(result.is_err() || result.unwrap().is_err(), "expected timeout or connection error");
401        client.close();
402    }
403}