open-humanity
Privacy-first peer assistance network for sovereign autonomous agents
Brought by drakestapleton
open-humanity / crates / beacon-client / src / relay.rs
| 1 | //! Asking for help and answering through an Open Humanity relay. |
| 2 | //! |
| 3 | //! The node that asks sends a signed request: a topic, a hash of the error it is |
| 4 | //! stuck on, a short title and summary that passed the Personal Data Firewall, and a |
| 5 | //! fresh X25519 key. A helper whose local store holds a solution for that hash |
| 6 | //! encrypts it to that key and sends it back through the relay. Only the node that |
| 7 | //! asked can read it. |
| 8 | |
| 9 | use crate::preflight::{PreflightError, PreflightSandbox}; |
| 10 | use crate::storage::{BeaconStorage, DEFAULT_TTL_SECONDS}; |
| 11 | use beacon_core::crypto::{decrypt_from_peer, encrypt_to_peer, Keypair, ReplayProtector}; |
| 12 | use beacon_core::firewall::{FirewallViolation, PersonalDataFirewall}; |
| 13 | use beacon_core::schema::{ |
| 14 | BeaconError, BeaconTopic, DistressNanobeacon, ErrorFingerprint, ResolutionCapsule, |
| 15 | }; |
| 16 | use beacon_core::wire::{ |
| 17 | sign_capsule, sign_signal, unix_now, verify_capsule, verify_signal, Ack, Frame, Register, |
| 18 | COOKIE_LEN, MAX_CAPSULE_DATAGRAM, |
| 19 | }; |
| 20 | use rand::rngs::OsRng; |
| 21 | use std::collections::{HashSet, VecDeque}; |
| 22 | use std::net::SocketAddr; |
| 23 | use std::time::{Duration, Instant}; |
| 24 | use thiserror::Error; |
| 25 | use tokio::net::UdpSocket; |
| 26 | use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret}; |
| 27 | |
| 28 | /// Longest gap between two registrations; the relay forgets a node after 120 s. |
| 29 | pub const KEEPALIVE: Duration = Duration::from_secs(40); |
| 30 | |
| 31 | #[derive(Error, Debug)] |
| 32 | pub enum RelayClientError { |
| 33 | #[error("IO error: {0}")] |
| 34 | Io(#[from] std::io::Error), |
| 35 | #[error("Protocol error: {0}")] |
| 36 | Protocol(#[from] BeaconError), |
| 37 | #[error("Personal Data Firewall refused the text: {0}")] |
| 38 | Firewall(#[from] FirewallViolation), |
| 39 | #[error("Local store error: {0}")] |
| 40 | Storage(#[from] rusqlite::Error), |
| 41 | #[error("The relay did not answer the registration")] |
| 42 | NoRelay, |
| 43 | #[error("The answer is not valid text")] |
| 44 | NotText, |
| 45 | #[error("The answer is for a different request")] |
| 46 | WrongRequest, |
| 47 | #[error("The check could not run: {0}")] |
| 48 | Check(String), |
| 49 | } |
| 50 | |
| 51 | /// The same error text gives the same fingerprint on every node: user folders are |
| 52 | /// replaced, runs of white space become one space, and the ends are trimmed. |
| 53 | pub fn normalize_error(error_text: &str) -> String { |
| 54 | let cleaned = PersonalDataFirewall::sanitize_paths(error_text); |
| 55 | cleaned.split_whitespace().collect::<Vec<_>>().join(" ") |
| 56 | } |
| 57 | |
| 58 | pub fn fingerprint_for(error_text: &str, compiler_code: Option<u32>, arch: &str) -> ErrorFingerprint { |
| 59 | ErrorFingerprint::from_error_str(&normalize_error(error_text), compiler_code, arch) |
| 60 | } |
| 61 | |
| 62 | /// A request for help and the secret that opens its answers. |
| 63 | pub struct HelpRequest { |
| 64 | pub signal: DistressNanobeacon, |
| 65 | pub dh_secret: StaticSecret, |
| 66 | } |
| 67 | |
| 68 | /// Build and sign a request. The error text itself never leaves the node, only its |
| 69 | /// hash does. Title and summary must pass the Personal Data Firewall. |
| 70 | pub fn build_request( |
| 71 | keypair: &Keypair, |
| 72 | topic: BeaconTopic, |
| 73 | error_text: &str, |
| 74 | compiler_code: Option<u32>, |
| 75 | arch: &str, |
| 76 | title: &str, |
| 77 | summary: &str, |
| 78 | ) -> Result<HelpRequest, RelayClientError> { |
| 79 | let title = PersonalDataFirewall::sanitize_paths(title); |
| 80 | let summary = PersonalDataFirewall::sanitize_paths(summary); |
| 81 | PersonalDataFirewall::verify_clean(&title)?; |
| 82 | PersonalDataFirewall::verify_clean(&summary)?; |
| 83 | |
| 84 | let dh_secret = StaticSecret::random_from_rng(OsRng); |
| 85 | let dh_pubkey = *X25519PublicKey::from(&dh_secret).as_bytes(); |
| 86 | let mut signal = DistressNanobeacon::new( |
| 87 | topic, |
| 88 | keypair.pubkey_bytes(), |
| 89 | dh_pubkey, |
| 90 | fingerprint_for(error_text, compiler_code, arch), |
| 91 | title, |
| 92 | summary, |
| 93 | ); |
| 94 | sign_signal(&mut signal, keypair)?; |
| 95 | signal.to_bytes()?; |
| 96 | Ok(HelpRequest { signal, dh_secret }) |
| 97 | } |
| 98 | |
| 99 | /// One decrypted answer and the key of the node that gave it. |
| 100 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 101 | pub struct Answer { |
| 102 | pub responder_pubkey: [u8; 32], |
| 103 | pub text: String, |
| 104 | } |
| 105 | |
| 106 | /// Check and decrypt an answer to `request`. |
| 107 | pub fn open_capsule( |
| 108 | capsule: &ResolutionCapsule, |
| 109 | request: &HelpRequest, |
| 110 | ) -> Result<Answer, RelayClientError> { |
| 111 | if capsule.beacon_id != request.signal.beacon_id { |
| 112 | return Err(RelayClientError::WrongRequest); |
| 113 | } |
| 114 | verify_capsule(capsule)?; |
| 115 | let plain = decrypt_from_peer( |
| 116 | &request.dh_secret, |
| 117 | &capsule.ephemeral_dh_pubkey, |
| 118 | &capsule.nonce, |
| 119 | &capsule.ciphertext, |
| 120 | )?; |
| 121 | let text = String::from_utf8(plain).map_err(|_| RelayClientError::NotText)?; |
| 122 | Ok(Answer { |
| 123 | responder_pubkey: capsule.responder_pubkey, |
| 124 | text, |
| 125 | }) |
| 126 | } |
| 127 | |
| 128 | /// Answer a request from the local store, if it holds a solution for the same |
| 129 | /// fingerprint. The request must be signed and at most seven days old. A stored |
| 130 | /// solution that fails the Personal Data Firewall is never sent. |
| 131 | pub fn answer_signal( |
| 132 | storage: &BeaconStorage, |
| 133 | keypair: &Keypair, |
| 134 | signal: &DistressNanobeacon, |
| 135 | ) -> Result<Option<ResolutionCapsule>, RelayClientError> { |
| 136 | verify_signal(signal)?; |
| 137 | let now = unix_now(); |
| 138 | let age = now.saturating_sub(signal.timestamp); |
| 139 | if age > DEFAULT_TTL_SECONDS || signal.timestamp > now + 300 { |
| 140 | return Err(RelayClientError::Protocol(BeaconError::TimestampDrift { |
| 141 | drift_secs: now.abs_diff(signal.timestamp), |
| 142 | max_allowed: DEFAULT_TTL_SECONDS, |
| 143 | })); |
| 144 | } |
| 145 | storage.record_inbound_beacon(signal)?; |
| 146 | let Some(entry) = storage.get_solved_entry(&signal.fingerprint.hash)? else { |
| 147 | return Ok(None); |
| 148 | }; |
| 149 | let text = PersonalDataFirewall::sanitize_paths(&entry.solution_patch); |
| 150 | PersonalDataFirewall::verify_clean(&text)?; |
| 151 | |
| 152 | let sealed = encrypt_to_peer(&signal.ephemeral_dh_pubkey, text.as_bytes())?; |
| 153 | let mut capsule = ResolutionCapsule::new( |
| 154 | signal.beacon_id, |
| 155 | keypair.pubkey_bytes(), |
| 156 | sealed.ephemeral_pubkey, |
| 157 | sealed.nonce, |
| 158 | sealed.ciphertext, |
| 159 | ); |
| 160 | sign_capsule(&mut capsule, keypair)?; |
| 161 | Frame::Capsule(capsule.clone()).encode()?; |
| 162 | Ok(Some(capsule)) |
| 163 | } |
| 164 | |
| 165 | /// Store a solution for an error text so this node can answer requests about it. |
| 166 | /// The solution must pass the Personal Data Firewall. |
| 167 | pub fn teach( |
| 168 | storage: &BeaconStorage, |
| 169 | topic: BeaconTopic, |
| 170 | error_text: &str, |
| 171 | solution: &str, |
| 172 | ) -> Result<ErrorFingerprint, RelayClientError> { |
| 173 | let solution = PersonalDataFirewall::sanitize_paths(solution); |
| 174 | PersonalDataFirewall::verify_clean(&solution)?; |
| 175 | let fingerprint = fingerprint_for(error_text, None, std::env::consts::ARCH); |
| 176 | storage.insert_solved_entry(&fingerprint.hash, topic, &solution)?; |
| 177 | Ok(fingerprint) |
| 178 | } |
| 179 | |
| 180 | /// A UDP socket bound to one relay. |
| 181 | pub struct RelayClient { |
| 182 | socket: UdpSocket, |
| 183 | keypair: Keypair, |
| 184 | cookie: [u8; COOKIE_LEN], |
| 185 | topics: u8, |
| 186 | pending: VecDeque<Frame>, |
| 187 | } |
| 188 | |
| 189 | impl RelayClient { |
| 190 | pub async fn connect(relay: SocketAddr, keypair: Keypair) -> Result<Self, RelayClientError> { |
| 191 | let local: SocketAddr = if relay.is_ipv4() { |
| 192 | SocketAddr::from(([0, 0, 0, 0], 0)) |
| 193 | } else { |
| 194 | SocketAddr::from(([0u16; 8], 0)) |
| 195 | }; |
| 196 | let socket = UdpSocket::bind(local).await?; |
| 197 | socket.connect(relay).await?; |
| 198 | Ok(Self { |
| 199 | socket, |
| 200 | keypair, |
| 201 | cookie: [0u8; COOKIE_LEN], |
| 202 | topics: 0, |
| 203 | pending: VecDeque::new(), |
| 204 | }) |
| 205 | } |
| 206 | |
| 207 | pub fn keypair(&self) -> &Keypair { |
| 208 | &self.keypair |
| 209 | } |
| 210 | |
| 211 | pub fn local_addr(&self) -> Result<SocketAddr, RelayClientError> { |
| 212 | Ok(self.socket.local_addr()?) |
| 213 | } |
| 214 | |
| 215 | pub fn set_cookie(&mut self, cookie: [u8; COOKIE_LEN]) { |
| 216 | self.cookie = cookie; |
| 217 | } |
| 218 | |
| 219 | /// Send one registration with the cookie held now. |
| 220 | pub async fn send_register(&mut self, topics: u8, replay: bool) -> Result<(), RelayClientError> { |
| 221 | self.topics = topics; |
| 222 | let mut register = Register::new(self.keypair.pubkey_bytes(), topics, replay, self.cookie); |
| 223 | register.sign(&self.keypair)?; |
| 224 | self.socket.send(&Frame::Register(register).encode()?).await?; |
| 225 | Ok(()) |
| 226 | } |
| 227 | |
| 228 | /// Register and wait until the relay accepts. Frames that arrive meanwhile are kept |
| 229 | /// for `recv_frame`. |
| 230 | pub async fn register(&mut self, topics: u8, replay: bool) -> Result<Ack, RelayClientError> { |
| 231 | let mut buf = vec![0u8; MAX_CAPSULE_DATAGRAM + 1]; |
| 232 | for _ in 0..5 { |
| 233 | self.send_register(topics, replay).await?; |
| 234 | let deadline = Instant::now() + Duration::from_millis(1000); |
| 235 | loop { |
| 236 | let left = deadline.saturating_duration_since(Instant::now()); |
| 237 | if left.is_zero() { |
| 238 | break; |
| 239 | } |
| 240 | let len = match tokio::time::timeout(left, self.socket.recv(&mut buf)).await { |
| 241 | Ok(Ok(len)) => len, |
| 242 | Ok(Err(_)) | Err(_) => break, |
| 243 | }; |
| 244 | match Frame::decode(&buf[..len]) { |
| 245 | Ok(Frame::Ack(ack)) => return Ok(ack), |
| 246 | Ok(Frame::Challenge(challenge)) => { |
| 247 | self.cookie = challenge.cookie; |
| 248 | break; |
| 249 | } |
| 250 | Ok(frame) => self.pending.push_back(frame), |
| 251 | Err(_) => {} |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | Err(RelayClientError::NoRelay) |
| 256 | } |
| 257 | |
| 258 | pub async fn send_signal(&self, signal: &DistressNanobeacon) -> Result<(), RelayClientError> { |
| 259 | self.socket.send(&Frame::Signal(signal.clone()).encode()?).await?; |
| 260 | Ok(()) |
| 261 | } |
| 262 | |
| 263 | pub async fn send_capsule(&self, capsule: &ResolutionCapsule) -> Result<(), RelayClientError> { |
| 264 | self.socket.send(&Frame::Capsule(capsule.clone()).encode()?).await?; |
| 265 | Ok(()) |
| 266 | } |
| 267 | |
| 268 | /// The next frame from the relay, or None when `wait` passes. |
| 269 | pub async fn recv_frame(&mut self, wait: Duration) -> Result<Option<Frame>, RelayClientError> { |
| 270 | if let Some(frame) = self.pending.pop_front() { |
| 271 | return Ok(Some(frame)); |
| 272 | } |
| 273 | let mut buf = vec![0u8; MAX_CAPSULE_DATAGRAM + 1]; |
| 274 | let deadline = Instant::now() + wait; |
| 275 | loop { |
| 276 | let left = deadline.saturating_duration_since(Instant::now()); |
| 277 | if left.is_zero() { |
| 278 | return Ok(None); |
| 279 | } |
| 280 | match tokio::time::timeout(left, self.socket.recv(&mut buf)).await { |
| 281 | Ok(Ok(len)) => { |
| 282 | if let Ok(frame) = Frame::decode(&buf[..len]) { |
| 283 | return Ok(Some(frame)); |
| 284 | } |
| 285 | } |
| 286 | Ok(Err(e)) => return Err(e.into()), |
| 287 | Err(_) => return Ok(None), |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | /// How often to repeat a registration the relay accepted for `ack.ttl_secs`: three |
| 294 | /// times per lifetime, and never less often than `KEEPALIVE`. |
| 295 | fn keepalive_for(ack: &Ack) -> Duration { |
| 296 | (Duration::from_secs(ack.ttl_secs.into()) / 3).clamp(Duration::from_secs(1), KEEPALIVE) |
| 297 | } |
| 298 | |
| 299 | /// Send `request` and collect answers until `wait` passes or `max_answers` arrived. |
| 300 | /// One answer is kept per helper key. The relay carries an answer only to an address |
| 301 | /// that is still registered, so the registration is repeated for the whole wait. |
| 302 | pub async fn ask( |
| 303 | client: &mut RelayClient, |
| 304 | request: &HelpRequest, |
| 305 | wait: Duration, |
| 306 | max_answers: usize, |
| 307 | ) -> Result<Vec<Answer>, RelayClientError> { |
| 308 | ask_skipping(client, request, wait, max_answers, &HashSet::new()).await |
| 309 | } |
| 310 | |
| 311 | /// `ask`, but an answer signed by a key in `skip` is dropped as if it never came. |
| 312 | pub async fn ask_skipping( |
| 313 | client: &mut RelayClient, |
| 314 | request: &HelpRequest, |
| 315 | wait: Duration, |
| 316 | max_answers: usize, |
| 317 | skip: &HashSet<[u8; 32]>, |
| 318 | ) -> Result<Vec<Answer>, RelayClientError> { |
| 319 | let topics = client.topics; |
| 320 | let mut keepalive = keepalive_for(&client.register(topics, false).await?); |
| 321 | client.send_signal(&request.signal).await?; |
| 322 | let deadline = Instant::now() + wait; |
| 323 | let mut next_keepalive = Instant::now() + keepalive; |
| 324 | let mut answers: Vec<Answer> = Vec::new(); |
| 325 | let mut resent = false; |
| 326 | while answers.len() < max_answers { |
| 327 | let now = Instant::now(); |
| 328 | let left = deadline.saturating_duration_since(now); |
| 329 | if left.is_zero() { |
| 330 | break; |
| 331 | } |
| 332 | if now >= next_keepalive { |
| 333 | client.send_register(topics, false).await?; |
| 334 | next_keepalive = now + keepalive; |
| 335 | } |
| 336 | match client.recv_frame(left.min(next_keepalive.saturating_duration_since(now))).await? { |
| 337 | Some(Frame::Capsule(capsule)) => { |
| 338 | if let Ok(answer) = open_capsule(&capsule, request) { |
| 339 | if skip.contains(&answer.responder_pubkey) { |
| 340 | continue; |
| 341 | } |
| 342 | if !answers.iter().any(|a| a.responder_pubkey == answer.responder_pubkey) { |
| 343 | answers.push(answer); |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | Some(Frame::Challenge(challenge)) => { |
| 348 | // The relay does not know this node (its cookie aged out, or the relay |
| 349 | // restarted): register again, and send the request once more. |
| 350 | client.set_cookie(challenge.cookie); |
| 351 | keepalive = keepalive_for(&client.register(topics, false).await?); |
| 352 | next_keepalive = Instant::now() + keepalive; |
| 353 | if !resent { |
| 354 | resent = true; |
| 355 | client.send_signal(&request.signal).await?; |
| 356 | } |
| 357 | } |
| 358 | Some(_) | None => {} |
| 359 | } |
| 360 | } |
| 361 | Ok(answers) |
| 362 | } |
| 363 | |
| 364 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 365 | pub struct ListenReport { |
| 366 | pub requests_seen: u64, |
| 367 | pub answered: u64, |
| 368 | pub no_solution: u64, |
| 369 | pub refused: u64, |
| 370 | } |
| 371 | |
| 372 | /// Register for `topics` and answer requests from the local store until `run_for` |
| 373 | /// passes (for ever when None). Stored requests of the last seven days are asked for |
| 374 | /// once at the start. |
| 375 | pub async fn listen( |
| 376 | client: &mut RelayClient, |
| 377 | storage: &mut BeaconStorage, |
| 378 | topics: u8, |
| 379 | run_for: Option<Duration>, |
| 380 | ) -> Result<ListenReport, RelayClientError> { |
| 381 | let mut report = ListenReport::default(); |
| 382 | let mut seen = ReplayProtector::new(100_000); |
| 383 | let keepalive = keepalive_for(&client.register(topics, true).await?); |
| 384 | let end = run_for.map(|d| Instant::now() + d); |
| 385 | let mut next_keepalive = Instant::now() + keepalive; |
| 386 | loop { |
| 387 | let now = Instant::now(); |
| 388 | let mut wait = next_keepalive.saturating_duration_since(now); |
| 389 | if let Some(end) = end { |
| 390 | if now >= end { |
| 391 | break; |
| 392 | } |
| 393 | wait = wait.min(end.saturating_duration_since(now)); |
| 394 | } |
| 395 | match client.recv_frame(wait).await? { |
| 396 | Some(Frame::Signal(signal)) => { |
| 397 | if seen.check_and_record(&signal.beacon_id).is_ok() { |
| 398 | report.requests_seen += 1; |
| 399 | match answer_signal(storage, client.keypair(), &signal) { |
| 400 | Ok(Some(capsule)) => { |
| 401 | client.send_capsule(&capsule).await?; |
| 402 | report.answered += 1; |
| 403 | } |
| 404 | Ok(None) => report.no_solution += 1, |
| 405 | Err(_) => report.refused += 1, |
| 406 | } |
| 407 | } |
| 408 | } |
| 409 | Some(Frame::Challenge(challenge)) => { |
| 410 | client.set_cookie(challenge.cookie); |
| 411 | client.send_register(topics, false).await?; |
| 412 | } |
| 413 | Some(_) | None => {} |
| 414 | } |
| 415 | if Instant::now() >= next_keepalive { |
| 416 | client.send_register(topics, false).await?; |
| 417 | next_keepalive = Instant::now() + keepalive; |
| 418 | } |
| 419 | } |
| 420 | Ok(report) |
| 421 | } |
| 422 | |
| 423 | /// A command that judges an answer: a program and its arguments. |
| 424 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 425 | pub struct AnswerCheck { |
| 426 | pub program: String, |
| 427 | pub args: Vec<String>, |
| 428 | } |
| 429 | |
| 430 | impl AnswerCheck { |
| 431 | /// Words separated by white space; the first is the program. No shell reads the text. |
| 432 | pub fn parse(text: &str) -> Option<Self> { |
| 433 | let mut words = text.split_whitespace().map(str::to_string); |
| 434 | let program = words.next()?; |
| 435 | Some(Self { |
| 436 | program, |
| 437 | args: words.collect(), |
| 438 | }) |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | /// Run the check in a new empty folder that holds the answer as `solution.txt` and is |
| 443 | /// deleted afterwards. True when the command ends with 0. The folder keeps the check |
| 444 | /// away from the work tree; what else the command may touch is up to the command. |
| 445 | pub fn check_answer(check: &AnswerCheck, answer: &Answer) -> Result<bool, RelayClientError> { |
| 446 | let sandbox = PreflightSandbox::new().map_err(|e| RelayClientError::Check(e.to_string()))?; |
| 447 | sandbox |
| 448 | .write_file("solution.txt", &answer.text) |
| 449 | .map_err(|e| RelayClientError::Check(e.to_string()))?; |
| 450 | let args: Vec<&str> = check.args.iter().map(String::as_str).collect(); |
| 451 | match sandbox.run_check(&check.program, &args) { |
| 452 | Ok(_) => Ok(true), |
| 453 | Err(PreflightError::VerificationFailed { .. }) => Ok(false), |
| 454 | Err(e) => Err(RelayClientError::Check(e.to_string())), |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | /// Check an answer, count the result for the helper that signed it, and keep the answer |
| 459 | /// as a solution on this node only when it passed. An answer that fails the Personal |
| 460 | /// Data Firewall counts as failed whatever the check says. |
| 461 | pub fn settle_answer( |
| 462 | storage: &BeaconStorage, |
| 463 | request: &HelpRequest, |
| 464 | answer: &Answer, |
| 465 | check: &AnswerCheck, |
| 466 | ) -> Result<bool, RelayClientError> { |
| 467 | let text = PersonalDataFirewall::sanitize_paths(&answer.text); |
| 468 | let passed = PersonalDataFirewall::verify_clean(&text).is_ok() && check_answer(check, answer)?; |
| 469 | storage.record_peer_result(&answer.responder_pubkey, passed)?; |
| 470 | if passed { |
| 471 | storage.insert_solved_entry(&request.signal.fingerprint.hash, request.signal.topic, &text)?; |
| 472 | } |
| 473 | Ok(passed) |
| 474 | } |