spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / fixtures / canary-target / src / main.rs
| 1 | //! First canary target. It speaks the worker side of the canary wire protocol (version 1) over |
| 2 | //! the Unix socket the supervisor passes as `--socket`, and can misbehave on purpose so the |
| 3 | //! supervisor's checks can be shown to hold. It does not depend on spark_rsi. |
| 4 | //! |
| 5 | //! Wire format: one JSON value per line, serde's externally tagged enum encoding, the same as |
| 6 | //! the supervisor's `WorkerMessage` and `SupervisorMessage`. |
| 7 | |
| 8 | use serde_json::{json, Value}; |
| 9 | use std::env; |
| 10 | use std::io::{BufRead, BufReader, Write}; |
| 11 | use std::os::unix::net::UnixStream; |
| 12 | use std::path::Path; |
| 13 | use std::thread; |
| 14 | use std::time::{Duration, Instant}; |
| 15 | |
| 16 | const PROTOCOL_VERSION: u64 = 1; |
| 17 | |
| 18 | // SHA-256, so the fixture needs no crate beyond serde and serde_json. |
| 19 | const K: [u32; 64] = [ |
| 20 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, |
| 21 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, |
| 22 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, |
| 23 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, |
| 24 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, |
| 25 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, |
| 26 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, |
| 27 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, |
| 28 | ]; |
| 29 | |
| 30 | fn sha256(data: &[u8]) -> [u8; 32] { |
| 31 | let mut h: [u32; 8] = [ |
| 32 | 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, |
| 33 | 0x5be0cd19, |
| 34 | ]; |
| 35 | let mut msg = data.to_vec(); |
| 36 | msg.push(0x80); |
| 37 | while msg.len() % 64 != 56 { |
| 38 | msg.push(0); |
| 39 | } |
| 40 | msg.extend_from_slice(&((data.len() as u64) * 8).to_be_bytes()); |
| 41 | for block in msg.chunks(64) { |
| 42 | let mut w = [0u32; 64]; |
| 43 | for i in 0..16 { |
| 44 | w[i] = u32::from_be_bytes([ |
| 45 | block[4 * i], |
| 46 | block[4 * i + 1], |
| 47 | block[4 * i + 2], |
| 48 | block[4 * i + 3], |
| 49 | ]); |
| 50 | } |
| 51 | for i in 16..64 { |
| 52 | let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); |
| 53 | let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); |
| 54 | w[i] = w[i - 16] |
| 55 | .wrapping_add(s0) |
| 56 | .wrapping_add(w[i - 7]) |
| 57 | .wrapping_add(s1); |
| 58 | } |
| 59 | let mut v = h; |
| 60 | for i in 0..64 { |
| 61 | let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25); |
| 62 | let ch = (v[4] & v[5]) ^ (!v[4] & v[6]); |
| 63 | let t1 = v[7] |
| 64 | .wrapping_add(s1) |
| 65 | .wrapping_add(ch) |
| 66 | .wrapping_add(K[i]) |
| 67 | .wrapping_add(w[i]); |
| 68 | let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22); |
| 69 | let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]); |
| 70 | let t2 = s0.wrapping_add(maj); |
| 71 | v[7] = v[6]; |
| 72 | v[6] = v[5]; |
| 73 | v[5] = v[4]; |
| 74 | v[4] = v[3].wrapping_add(t1); |
| 75 | v[3] = v[2]; |
| 76 | v[2] = v[1]; |
| 77 | v[1] = v[0]; |
| 78 | v[0] = t1.wrapping_add(t2); |
| 79 | } |
| 80 | for i in 0..8 { |
| 81 | h[i] = h[i].wrapping_add(v[i]); |
| 82 | } |
| 83 | } |
| 84 | let mut out = [0u8; 32]; |
| 85 | for (i, word) in h.iter().enumerate() { |
| 86 | out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes()); |
| 87 | } |
| 88 | out |
| 89 | } |
| 90 | |
| 91 | fn hex(bytes: &[u8]) -> String { |
| 92 | bytes.iter().map(|b| format!("{:02x}", b)).collect() |
| 93 | } |
| 94 | |
| 95 | /// RFC 2104 HMAC-SHA256, hex encoded: the same scheme as the supervisor's `SessionAuth`. |
| 96 | fn hmac_sha256_hex(secret: &str, message: &str) -> String { |
| 97 | let key = secret.as_bytes(); |
| 98 | let mut key_block = [0u8; 64]; |
| 99 | if key.len() > 64 { |
| 100 | key_block[..32].copy_from_slice(&sha256(key)); |
| 101 | } else { |
| 102 | key_block[..key.len()].copy_from_slice(key); |
| 103 | } |
| 104 | let mut inner = Vec::with_capacity(64 + message.len()); |
| 105 | let mut outer = Vec::with_capacity(96); |
| 106 | for b in key_block { |
| 107 | inner.push(b ^ 0x36); |
| 108 | } |
| 109 | inner.extend_from_slice(message.as_bytes()); |
| 110 | for b in key_block { |
| 111 | outer.push(b ^ 0x5c); |
| 112 | } |
| 113 | outer.extend_from_slice(&sha256(&inner)); |
| 114 | hex(&sha256(&outer)) |
| 115 | } |
| 116 | |
| 117 | /// What a correct worker answers: "ping" gives "pong", "add A B" gives the sum, anything else |
| 118 | /// echoes the input. |
| 119 | fn correct_answer(input: &str) -> String { |
| 120 | if input == "ping" { |
| 121 | return "pong".to_string(); |
| 122 | } |
| 123 | let parts: Vec<&str> = input.split_whitespace().collect(); |
| 124 | if parts.len() == 3 && parts[0] == "add" { |
| 125 | if let (Ok(a), Ok(b)) = (parts[1].parse::<i64>(), parts[2].parse::<i64>()) { |
| 126 | return (a + b).to_string(); |
| 127 | } |
| 128 | } |
| 129 | input.to_string() |
| 130 | } |
| 131 | |
| 132 | struct Wire { |
| 133 | reader: BufReader<UnixStream>, |
| 134 | writer: UnixStream, |
| 135 | } |
| 136 | |
| 137 | impl Wire { |
| 138 | fn connect(path: &str) -> std::io::Result<Wire> { |
| 139 | let stream = UnixStream::connect(path)?; |
| 140 | Ok(Wire { |
| 141 | reader: BufReader::new(stream.try_clone()?), |
| 142 | writer: stream, |
| 143 | }) |
| 144 | } |
| 145 | |
| 146 | fn send(&mut self, value: &Value) -> std::io::Result<()> { |
| 147 | let mut line = value.to_string(); |
| 148 | line.push('\n'); |
| 149 | self.writer.write_all(line.as_bytes())?; |
| 150 | self.writer.flush() |
| 151 | } |
| 152 | |
| 153 | fn recv(&mut self) -> Option<Value> { |
| 154 | let mut line = String::new(); |
| 155 | match self.reader.read_line(&mut line) { |
| 156 | Ok(0) | Err(_) => None, |
| 157 | Ok(_) => serde_json::from_str(line.trim()).ok(), |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | fn ready_frame(generation_id: &str, protocol_version: Option<u64>) -> Value { |
| 163 | let mut inner = json!({ |
| 164 | "generation_id": generation_id, |
| 165 | "pid": std::process::id(), |
| 166 | "auth_token": "", |
| 167 | }); |
| 168 | if let Some(v) = protocol_version { |
| 169 | inner["protocol_version"] = json!(v); |
| 170 | } |
| 171 | json!({ "Ready": inner }) |
| 172 | } |
| 173 | |
| 174 | fn result_frame(generation_id: &str, request_id: &str, output: &str, latency_us: u64) -> Value { |
| 175 | json!({ "ExecuteResult": { |
| 176 | "protocol_version": PROTOCOL_VERSION, |
| 177 | "generation_id": generation_id, |
| 178 | "request_id": request_id, |
| 179 | "output": output, |
| 180 | "worker_latency_us": latency_us, |
| 181 | }}) |
| 182 | } |
| 183 | |
| 184 | fn env_or(name: &str, default: &str) -> String { |
| 185 | env::var(name).unwrap_or_else(|_| default.to_string()) |
| 186 | } |
| 187 | |
| 188 | fn main() { |
| 189 | let mut args = env::args().skip(1); |
| 190 | let mut socket = None; |
| 191 | while let Some(arg) = args.next() { |
| 192 | if arg == "--socket" { |
| 193 | socket = args.next(); |
| 194 | } |
| 195 | } |
| 196 | let socket = socket.expect("canary-target needs --socket <path>"); |
| 197 | let generation_id = Path::new(&socket) |
| 198 | .file_stem() |
| 199 | .and_then(|s| s.to_str()) |
| 200 | .expect("socket path must be <generation_id>.sock") |
| 201 | .to_string(); |
| 202 | let secret = env_or("SUPERVISOR_SECRET", ""); |
| 203 | let mode = env_or("RSI_CANARY_FIXTURE_MODE", "correct"); |
| 204 | let fail_at: usize = env_or("RSI_CANARY_FIXTURE_FAIL_AT", "3") |
| 205 | .parse() |
| 206 | .expect("RSI_CANARY_FIXTURE_FAIL_AT must be a number"); |
| 207 | let claimed_version: u64 = env_or("RSI_CANARY_FIXTURE_PROTOCOL_VERSION", "1") |
| 208 | .parse() |
| 209 | .expect("RSI_CANARY_FIXTURE_PROTOCOL_VERSION must be a number"); |
| 210 | |
| 211 | let mut wire = Wire::connect(&socket).expect("cannot connect to the generation socket"); |
| 212 | |
| 213 | // Misbehaviours before readiness. |
| 214 | match mode.as_str() { |
| 215 | "bare_connection" => { |
| 216 | // Connect and say nothing until the supervisor gives up. |
| 217 | thread::sleep(Duration::from_secs(60)); |
| 218 | return; |
| 219 | } |
| 220 | "old_protocol" => wire.send(&ready_frame(&generation_id, None)).unwrap(), |
| 221 | "wrong_generation" => wire.send(&ready_frame("gen-other", Some(claimed_version))).unwrap(), |
| 222 | _ => wire |
| 223 | .send(&ready_frame(&generation_id, Some(claimed_version))) |
| 224 | .unwrap(), |
| 225 | } |
| 226 | |
| 227 | // Challenge, then the supervisor's Ping. |
| 228 | let nonce = match wire.recv() { |
| 229 | Some(v) => match v["AuthChallenge"]["nonce"].as_str() { |
| 230 | Some(n) => n.to_string(), |
| 231 | None => return, |
| 232 | }, |
| 233 | None => return, |
| 234 | }; |
| 235 | let response = hmac_sha256_hex(&secret, &format!("{}:{}", generation_id, nonce)); |
| 236 | wire.send(&json!({ "AuthResponse": { "response": response } })) |
| 237 | .unwrap(); |
| 238 | match wire.recv() { |
| 239 | Some(v) if v == json!("Ping") => {} |
| 240 | _ => return, |
| 241 | } |
| 242 | |
| 243 | let mut answered: Vec<(String, String)> = Vec::new(); |
| 244 | let mut served = 0usize; |
| 245 | while let Some(frame) = wire.recv() { |
| 246 | let req = &frame["ExecuteRequest"]; |
| 247 | if req.is_null() { |
| 248 | continue; // Ping and anything else need no answer. |
| 249 | } |
| 250 | served += 1; |
| 251 | let started = Instant::now(); |
| 252 | let request_id = req["request_id"].as_str().unwrap_or("").to_string(); |
| 253 | let input = req["input"].as_str().unwrap_or("").to_string(); |
| 254 | let correct = correct_answer(&input); |
| 255 | let latency = || started.elapsed().as_micros() as u64; |
| 256 | let reply = |wire: &mut Wire, id: &str, out: &str, lat: u64| { |
| 257 | let _ = wire.send(&result_frame(&generation_id, id, out, lat)); |
| 258 | }; |
| 259 | |
| 260 | match mode.as_str() { |
| 261 | "wrong_answer" => { |
| 262 | let out = if served == fail_at { |
| 263 | format!("{}-wrong", correct) |
| 264 | } else { |
| 265 | correct.clone() |
| 266 | }; |
| 267 | reply(&mut wire, &request_id, &out, latency()); |
| 268 | } |
| 269 | "fabricate_success" => { |
| 270 | // Claims success and a tiny latency while answering wrongly. |
| 271 | let _ = wire.send(&json!({ "CanaryReport": { |
| 272 | "generation_id": generation_id, |
| 273 | "transaction_id": served, |
| 274 | "success": true, |
| 275 | "latency_us": 1, |
| 276 | "error": null, |
| 277 | }})); |
| 278 | reply(&mut wire, &request_id, &format!("{}-fabricated", correct), 1); |
| 279 | } |
| 280 | "duplicate" => { |
| 281 | reply(&mut wire, &request_id, &correct, latency()); |
| 282 | reply(&mut wire, &request_id, &correct, latency()); |
| 283 | } |
| 284 | "replay" => { |
| 285 | reply(&mut wire, &request_id, &correct, latency()); |
| 286 | answered.push((request_id.clone(), correct.clone())); |
| 287 | if served == fail_at { |
| 288 | // Reconnect and resend every earlier result without a handshake. |
| 289 | if let Ok(mut again) = Wire::connect(&socket) { |
| 290 | for (id, out) in &answered { |
| 291 | let _ = again.send(&result_frame(&generation_id, id, out, 1)); |
| 292 | } |
| 293 | thread::sleep(Duration::from_millis(100)); |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | "timeout" => { |
| 298 | if served == fail_at { |
| 299 | loop { |
| 300 | thread::sleep(Duration::from_secs(1)); |
| 301 | } |
| 302 | } |
| 303 | reply(&mut wire, &request_id, &correct, latency()); |
| 304 | } |
| 305 | "wrong_request" => { |
| 306 | if served == fail_at { |
| 307 | reply(&mut wire, "req-bogus", &correct, latency()); |
| 308 | } else { |
| 309 | reply(&mut wire, &request_id, &correct, latency()); |
| 310 | } |
| 311 | } |
| 312 | "premature_promotion" => { |
| 313 | let _ = wire.send(&json!({ "DrainComplete": { "generation_id": generation_id } })); |
| 314 | let _ = wire.send(&ready_frame(&generation_id, Some(PROTOCOL_VERSION))); |
| 315 | let _ = wire.send(&json!({ "CanaryReport": { |
| 316 | "generation_id": generation_id, |
| 317 | "transaction_id": served, |
| 318 | "success": true, |
| 319 | "latency_us": 1, |
| 320 | "error": null, |
| 321 | }})); |
| 322 | reply(&mut wire, &request_id, &correct, latency()); |
| 323 | } |
| 324 | _ => reply(&mut wire, &request_id, &correct, latency()), |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | #[cfg(test)] |
| 330 | mod tests { |
| 331 | use super::*; |
| 332 | |
| 333 | #[test] |
| 334 | fn sha256_matches_known_vectors() { |
| 335 | assert_eq!( |
| 336 | hex(&sha256(b"")), |
| 337 | "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" |
| 338 | ); |
| 339 | assert_eq!( |
| 340 | hex(&sha256(b"abc")), |
| 341 | "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" |
| 342 | ); |
| 343 | let long = vec![b'a'; 1000]; |
| 344 | assert_eq!( |
| 345 | hex(&sha256(&long)), |
| 346 | "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3" |
| 347 | ); |
| 348 | } |
| 349 | |
| 350 | #[test] |
| 351 | fn hmac_matches_rfc_4231_case_2() { |
| 352 | assert_eq!( |
| 353 | hmac_sha256_hex("Jefe", "what do ya want for nothing?"), |
| 354 | "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" |
| 355 | ); |
| 356 | } |
| 357 | |
| 358 | #[test] |
| 359 | fn correct_answers() { |
| 360 | assert_eq!(correct_answer("ping"), "pong"); |
| 361 | assert_eq!(correct_answer("add 2 3"), "5"); |
| 362 | assert_eq!(correct_answer("add 100 -1"), "99"); |
| 363 | assert_eq!(correct_answer("hello world"), "hello world"); |
| 364 | } |
| 365 | } |