spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / supervisor / ipc.rs
| 1 | use serde::{Deserialize, Serialize}; |
| 2 | use sha2::{Digest, Sha256}; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::time::Duration; |
| 5 | use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; |
| 6 | use tokio::net::{UnixListener, UnixStream}; |
| 7 | |
| 8 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 9 | pub enum SupervisorMessage { |
| 10 | DrainStart { |
| 11 | timeout_secs: u64, |
| 12 | }, |
| 13 | RevertOrder { |
| 14 | reason: String, |
| 15 | }, |
| 16 | ShutdownAck { |
| 17 | pid: u32, |
| 18 | }, |
| 19 | Ping, |
| 20 | AuthChallenge { |
| 21 | nonce: String, |
| 22 | }, |
| 23 | /// Canary execute protocol, version `crate::canary::CANARY_PROTOCOL_VERSION`: one |
| 24 | /// challenge the supervisor issues on an authenticated generation connection. The |
| 25 | /// supervisor starts its own clock when it sends this frame. The worker sees only `input`; |
| 26 | /// the expected outcome stays in the operator's pinned workload. |
| 27 | ExecuteRequest { |
| 28 | protocol_version: u16, |
| 29 | generation_id: String, |
| 30 | request_id: String, |
| 31 | request_digest: String, |
| 32 | workload_digest: String, |
| 33 | input: String, |
| 34 | deadline_ms: u64, |
| 35 | }, |
| 36 | } |
| 37 | |
| 38 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 39 | pub enum WorkerMessage { |
| 40 | Ready { |
| 41 | generation_id: String, |
| 42 | pid: u32, |
| 43 | auth_token: String, |
| 44 | /// Execute protocol version the worker speaks. Absent in records from older workers, |
| 45 | /// which read as 0 and are never ready for canary execution. |
| 46 | #[serde(default)] |
| 47 | protocol_version: u16, |
| 48 | }, |
| 49 | Heartbeat { |
| 50 | generation_id: String, |
| 51 | timestamp_secs: u64, |
| 52 | active_requests: u32, |
| 53 | memory_mb: u64, |
| 54 | }, |
| 55 | DrainComplete { |
| 56 | generation_id: String, |
| 57 | }, |
| 58 | CanaryReport { |
| 59 | generation_id: String, |
| 60 | transaction_id: u64, |
| 61 | success: bool, |
| 62 | latency_us: u64, |
| 63 | error: Option<String>, |
| 64 | }, |
| 65 | Pong, |
| 66 | AuthResponse { |
| 67 | response: String, |
| 68 | }, |
| 69 | /// The worker's answer to one `ExecuteRequest`. Nothing in it is trusted: the supervisor |
| 70 | /// hashes `output` itself, compares it with the pinned expectation and measures elapsed |
| 71 | /// time on its own clock. `worker_latency_us` is a diagnostic, never an observation. |
| 72 | ExecuteResult { |
| 73 | protocol_version: u16, |
| 74 | generation_id: String, |
| 75 | request_id: String, |
| 76 | output: String, |
| 77 | #[serde(default)] |
| 78 | worker_latency_us: Option<u64>, |
| 79 | }, |
| 80 | } |
| 81 | |
| 82 | /// Authentication state the supervisor keeps per accepted connection. A connection starts |
| 83 | /// `Unauthenticated` and becomes `Authenticated` only when a versioned `Ready` for the expected |
| 84 | /// generation completed the HMAC challenge. Messages on an unauthenticated connection, or |
| 85 | /// naming another generation, are rejected and the connection is closed. The enforcement is |
| 86 | /// the supervisor's (plan step 3); the type lives here so every worker uses the same one. |
| 87 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 88 | pub enum ConnectionAuthState { |
| 89 | Unauthenticated, |
| 90 | Authenticated { |
| 91 | generation_id: String, |
| 92 | pid: u32, |
| 93 | protocol_version: u16, |
| 94 | }, |
| 95 | } |
| 96 | |
| 97 | impl ConnectionAuthState { |
| 98 | pub fn is_authenticated_for(&self, generation_id: &str) -> bool { |
| 99 | matches!(self, ConnectionAuthState::Authenticated { generation_id: g, .. } if g == generation_id) |
| 100 | } |
| 101 | |
| 102 | /// Authenticated for `generation_id` and speaking the current execute protocol. |
| 103 | pub fn can_execute_for(&self, generation_id: &str) -> bool { |
| 104 | matches!( |
| 105 | self, |
| 106 | ConnectionAuthState::Authenticated { generation_id: g, protocol_version, .. } |
| 107 | if g == generation_id && *protocol_version == crate::canary::CANARY_PROTOCOL_VERSION |
| 108 | ) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | pub struct IpcConnection { |
| 113 | reader: BufReader<tokio::net::unix::OwnedReadHalf>, |
| 114 | writer: tokio::net::unix::OwnedWriteHalf, |
| 115 | } |
| 116 | |
| 117 | impl IpcConnection { |
| 118 | pub fn new(stream: UnixStream) -> Self { |
| 119 | let (read_half, write_half) = stream.into_split(); |
| 120 | Self { |
| 121 | reader: BufReader::new(read_half), |
| 122 | writer: write_half, |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | pub async fn send<T: Serialize>(&mut self, message: &T) -> Result<(), String> { |
| 127 | let mut data = serde_json::to_string(message) |
| 128 | .map_err(|e| format!("Failed to serialize IPC message: {}", e))?; |
| 129 | data.push('\n'); |
| 130 | self.writer |
| 131 | .write_all(data.as_bytes()) |
| 132 | .await |
| 133 | .map_err(|e| format!("Failed to write IPC frame: {}", e))?; |
| 134 | self.writer |
| 135 | .flush() |
| 136 | .await |
| 137 | .map_err(|e| format!("Failed to flush IPC stream: {}", e))?; |
| 138 | Ok(()) |
| 139 | } |
| 140 | |
| 141 | pub async fn recv<T: serde::de::DeserializeOwned>(&mut self) -> Result<T, String> { |
| 142 | let mut line = String::new(); |
| 143 | let bytes_read = self |
| 144 | .reader |
| 145 | .read_line(&mut line) |
| 146 | .await |
| 147 | .map_err(|e| format!("Failed to read IPC frame: {}", e))?; |
| 148 | |
| 149 | if bytes_read == 0 { |
| 150 | return Err("IPC connection closed by peer".to_string()); |
| 151 | } |
| 152 | |
| 153 | serde_json::from_str(line.trim()) |
| 154 | .map_err(|e| format!("Failed to deserialize IPC message: {}", e)) |
| 155 | } |
| 156 | |
| 157 | pub async fn perform_worker_handshake( |
| 158 | &mut self, |
| 159 | generation_id: &str, |
| 160 | pid: u32, |
| 161 | shared_secret: &str, |
| 162 | ) -> Result<SupervisorMessage, String> { |
| 163 | self.send(&WorkerMessage::Ready { |
| 164 | generation_id: generation_id.to_string(), |
| 165 | pid, |
| 166 | auth_token: String::new(), |
| 167 | protocol_version: crate::canary::CANARY_PROTOCOL_VERSION, |
| 168 | }) |
| 169 | .await?; |
| 170 | |
| 171 | let challenge_msg: SupervisorMessage = self.recv().await?; |
| 172 | let nonce = match challenge_msg { |
| 173 | SupervisorMessage::AuthChallenge { nonce } => nonce, |
| 174 | other => { |
| 175 | return Err(format!( |
| 176 | "Expected AuthChallenge from supervisor, got {:?}", |
| 177 | other |
| 178 | )) |
| 179 | } |
| 180 | }; |
| 181 | |
| 182 | let message = format!("{}:{}", generation_id, nonce); |
| 183 | let hmac = SessionAuth::compute_hmac(shared_secret, &message); |
| 184 | |
| 185 | self.send(&WorkerMessage::AuthResponse { response: hmac }) |
| 186 | .await?; |
| 187 | self.recv().await |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | pub struct IpcServer { |
| 192 | listener: UnixListener, |
| 193 | socket_path: PathBuf, |
| 194 | } |
| 195 | |
| 196 | impl IpcServer { |
| 197 | pub fn bind(socket_path: &Path) -> Result<Self, String> { |
| 198 | if socket_path.exists() { |
| 199 | let _ = std::fs::remove_file(socket_path); |
| 200 | } |
| 201 | if let Some(parent) = socket_path.parent() { |
| 202 | let _ = std::fs::create_dir_all(parent); |
| 203 | } |
| 204 | |
| 205 | let listener = UnixListener::bind(socket_path) |
| 206 | .map_err(|e| format!("Failed to bind Unix socket at {:?}: {}", socket_path, e))?; |
| 207 | |
| 208 | Ok(Self { |
| 209 | listener, |
| 210 | socket_path: socket_path.to_path_buf(), |
| 211 | }) |
| 212 | } |
| 213 | |
| 214 | pub async fn accept(&self) -> Result<IpcConnection, String> { |
| 215 | let (stream, _addr) = self |
| 216 | .listener |
| 217 | .accept() |
| 218 | .await |
| 219 | .map_err(|e| format!("Failed to accept IPC connection: {}", e))?; |
| 220 | |
| 221 | #[cfg(target_os = "linux")] |
| 222 | { |
| 223 | let cred = stream |
| 224 | .peer_cred() |
| 225 | .map_err(|e| format!("Failed to get peer credentials: {}", e))?; |
| 226 | let current_uid = unsafe { libc::getuid() }; |
| 227 | if cred.uid() != current_uid { |
| 228 | return Err(format!( |
| 229 | "Unauthorized peer UID: {} != expected current UID {}", |
| 230 | cred.uid(), |
| 231 | current_uid |
| 232 | )); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | Ok(IpcConnection::new(stream)) |
| 237 | } |
| 238 | |
| 239 | pub fn path(&self) -> &Path { |
| 240 | &self.socket_path |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | impl Drop for IpcServer { |
| 245 | fn drop(&mut self) { |
| 246 | if self.socket_path.exists() { |
| 247 | let _ = std::fs::remove_file(&self.socket_path); |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | pub struct IpcClient; |
| 253 | |
| 254 | impl IpcClient { |
| 255 | pub async fn connect(socket_path: &Path, timeout: Duration) -> Result<IpcConnection, String> { |
| 256 | let start = std::time::Instant::now(); |
| 257 | while start.elapsed() < timeout { |
| 258 | if socket_path.exists() { |
| 259 | if let Ok(stream) = UnixStream::connect(socket_path).await { |
| 260 | return Ok(IpcConnection::new(stream)); |
| 261 | } |
| 262 | } |
| 263 | tokio::time::sleep(Duration::from_millis(50)).await; |
| 264 | } |
| 265 | |
| 266 | Err(format!( |
| 267 | "Timed out connecting to IPC socket at {:?} after {:?}", |
| 268 | socket_path, timeout |
| 269 | )) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | pub struct SessionAuth; |
| 274 | |
| 275 | impl SessionAuth { |
| 276 | /// Computes RFC 2104 HMAC-SHA256 of `message` using `shared_secret`. |
| 277 | pub fn compute_hmac(shared_secret: &str, message: &str) -> String { |
| 278 | let key = shared_secret.as_bytes(); |
| 279 | let mut key_block = [0u8; 64]; |
| 280 | if key.len() > 64 { |
| 281 | let mut hasher = Sha256::new(); |
| 282 | hasher.update(key); |
| 283 | let digest = hasher.finalize(); |
| 284 | key_block[..32].copy_from_slice(&digest); |
| 285 | } else { |
| 286 | key_block[..key.len()].copy_from_slice(key); |
| 287 | } |
| 288 | |
| 289 | let mut ipad = [0x36u8; 64]; |
| 290 | let mut opad = [0x5cu8; 64]; |
| 291 | for i in 0..64 { |
| 292 | ipad[i] ^= key_block[i]; |
| 293 | opad[i] ^= key_block[i]; |
| 294 | } |
| 295 | |
| 296 | let mut inner = Sha256::new(); |
| 297 | inner.update(&ipad); |
| 298 | inner.update(message.as_bytes()); |
| 299 | let inner_hash = inner.finalize(); |
| 300 | |
| 301 | let mut outer = Sha256::new(); |
| 302 | outer.update(&opad); |
| 303 | outer.update(&inner_hash); |
| 304 | hex::encode(outer.finalize()) |
| 305 | } |
| 306 | |
| 307 | /// Verifies candidate HMAC in constant time against expected HMAC. |
| 308 | pub fn verify_hmac(shared_secret: &str, message: &str, candidate: &str) -> bool { |
| 309 | let expected = Self::compute_hmac(shared_secret, message); |
| 310 | if expected.len() != candidate.len() { |
| 311 | return false; |
| 312 | } |
| 313 | let mut diff = 0u8; |
| 314 | for (a, b) in expected.as_bytes().iter().zip(candidate.as_bytes().iter()) { |
| 315 | diff |= a ^ b; |
| 316 | } |
| 317 | diff == 0 |
| 318 | } |
| 319 | |
| 320 | /// Backward-compatible alias for compute_hmac. |
| 321 | pub fn compute_token(nonce: &str, shared_secret: &str) -> String { |
| 322 | Self::compute_hmac(shared_secret, nonce) |
| 323 | } |
| 324 | |
| 325 | /// Backward-compatible alias for verify_hmac. |
| 326 | pub fn verify_token(nonce: &str, shared_secret: &str, candidate_token: &str) -> bool { |
| 327 | Self::verify_hmac(shared_secret, nonce, candidate_token) |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | #[cfg(test)] |
| 332 | mod tests { |
| 333 | use super::*; |
| 334 | |
| 335 | #[tokio::test] |
| 336 | async fn test_ipc_roundtrip_message_exchange() { |
| 337 | let tmp = tempfile::tempdir().unwrap(); |
| 338 | let sock_path = tmp.path().join("test_ipc.sock"); |
| 339 | |
| 340 | let server = IpcServer::bind(&sock_path).unwrap(); |
| 341 | |
| 342 | let client_task = tokio::spawn({ |
| 343 | let path = sock_path.clone(); |
| 344 | async move { |
| 345 | let mut client = IpcClient::connect(&path, Duration::from_secs(5)) |
| 346 | .await |
| 347 | .unwrap(); |
| 348 | |
| 349 | client |
| 350 | .send(&WorkerMessage::Ready { |
| 351 | generation_id: "gen-001".to_string(), |
| 352 | pid: 12345, |
| 353 | auth_token: "auth-token-xyz".to_string(), |
| 354 | protocol_version: crate::canary::CANARY_PROTOCOL_VERSION, |
| 355 | }) |
| 356 | .await |
| 357 | .unwrap(); |
| 358 | |
| 359 | let sup_msg: SupervisorMessage = client.recv().await.unwrap(); |
| 360 | assert_eq!(sup_msg, SupervisorMessage::Ping); |
| 361 | |
| 362 | client.send(&WorkerMessage::Pong).await.unwrap(); |
| 363 | } |
| 364 | }); |
| 365 | |
| 366 | let mut server_conn = server.accept().await.unwrap(); |
| 367 | let worker_msg: WorkerMessage = server_conn.recv().await.unwrap(); |
| 368 | match worker_msg { |
| 369 | WorkerMessage::Ready { |
| 370 | generation_id, |
| 371 | pid, |
| 372 | auth_token, |
| 373 | protocol_version, |
| 374 | } => { |
| 375 | assert_eq!(generation_id, "gen-001"); |
| 376 | assert_eq!(pid, 12345); |
| 377 | assert_eq!(auth_token, "auth-token-xyz"); |
| 378 | assert_eq!(protocol_version, crate::canary::CANARY_PROTOCOL_VERSION); |
| 379 | } |
| 380 | _ => panic!("Expected Ready message"), |
| 381 | } |
| 382 | |
| 383 | server_conn.send(&SupervisorMessage::Ping).await.unwrap(); |
| 384 | let pong: WorkerMessage = server_conn.recv().await.unwrap(); |
| 385 | assert_eq!(pong, WorkerMessage::Pong); |
| 386 | |
| 387 | client_task.await.unwrap(); |
| 388 | } |
| 389 | |
| 390 | #[test] |
| 391 | fn test_session_auth_verification() { |
| 392 | let nonce = "random-nonce-123"; |
| 393 | let secret = "tpm-bound-cluster-secret"; |
| 394 | let token = SessionAuth::compute_token(nonce, secret); |
| 395 | |
| 396 | assert!(SessionAuth::verify_token(nonce, secret, &token)); |
| 397 | assert!(!SessionAuth::verify_token(nonce, "wrong-secret", &token)); |
| 398 | assert!(!SessionAuth::verify_token("wrong-nonce", secret, &token)); |
| 399 | } |
| 400 | } |