Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/open-humanity/blob/main/crates/beacon-core/src/lib.rs # open-humanity Privacy-first peer assistance network for sovereign autonomous agents Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `open-humanity / crates / beacon-core / src / lib.rs` 410 lines ยท 16504 bytes Raw Blame History 1 pub mod crypto; 2 pub mod cuckoo; 3 pub mod firewall; 4 pub mod schema; 5 pub mod wire; 6 7 pub use crypto::*; 8 pub use cuckoo::*; 9 pub use firewall::*; 10 pub use schema::*; 11 pub use wire::*; 12 13 #[cfg(test)] 14 mod tests { 15 use super::*; 16 use rand::rngs::OsRng; 17 use std::time::Instant; 18 use uuid::Uuid; 19 use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret}; 20 21 #[test] 22 fn test_nanobeacon_packet_size() { 23 let keypair = Keypair::generate(); 24 let dh_secret = StaticSecret::random_from_rng(OsRng); 25 let dh_pubkey = *X25519PublicKey::from(&dh_secret).as_bytes(); 26 27 let error_str = "error[E0308]: mismatched types expected struct String, found &str in crates/core/src/lib.rs:42:15"; 28 let fp = ErrorFingerprint::from_error_str(error_str, Some(308), "aarch64"); 29 30 let beacon = DistressNanobeacon::new( 31 BeaconTopic::RustCompilation, 32 keypair.pubkey_bytes(), 33 dh_pubkey, 34 fp, 35 "Rust E0308 string mismatch".to_string(), 36 "Compiler expects owned String instead of string slice in handler".to_string(), 37 ); 38 39 let bytes = beacon.to_bytes().expect("serialization should succeed"); 40 assert!( 41 bytes.len() <= MAX_DATAGRAM_SIZE, 42 "Datagram size {} exceeds limit of {}", 43 bytes.len(), 44 MAX_DATAGRAM_SIZE 45 ); 46 47 let decoded = DistressNanobeacon::from_bytes(&bytes).expect("deserialization should succeed"); 48 assert_eq!(decoded.magic, MAGIC_BYTES); 49 assert_eq!(decoded.version, PROTOCOL_VERSION); 50 assert_eq!(decoded.topic, BeaconTopic::RustCompilation); 51 assert_eq!(decoded.title, "Rust E0308 string mismatch"); 52 } 53 54 #[test] 55 fn test_cuckoo_lookup_speed() { 56 let mut filter = CuckooFilter::new(); 57 let mut items = Vec::new(); 58 59 for i in 0..1000 { 60 let item = *blake3::hash(format!("error-signature-{}", i).as_bytes()).as_bytes(); 61 filter.insert(&item); 62 items.push(item); 63 } 64 65 assert_eq!(filter.len(), 1000); 66 67 for item in &items { 68 assert!(filter.contains(item)); 69 } 70 71 let iterations = 100_000; 72 let start = Instant::now(); 73 for i in 0..iterations { 74 let item = &items[i % items.len()]; 75 std::hint::black_box(filter.contains(item)); 76 } 77 let elapsed = start.elapsed(); 78 let nanos_per_op = elapsed.as_nanos() as f64 / iterations as f64; 79 80 #[cfg(debug_assertions)] 81 let max_nanos = 250.0; 82 #[cfg(not(debug_assertions))] 83 let max_nanos = 10.0; 84 85 assert!(nanos_per_op < max_nanos, "Cuckoo lookup too slow: {:.2} ns (limit: {:.2} ns)", nanos_per_op, max_nanos); 86 } 87 88 #[test] 89 fn test_firewall_blocks_api_keys() { 90 let aws = "Here is my secret AKIAIOSFODNN7EXAMPLE in code"; 91 assert!(PersonalDataFirewall::verify_clean(aws).is_err()); 92 93 let gh = "Authorization: ghp_`123456789012345678901234567890123456`"; 94 assert!(PersonalDataFirewall::verify_clean(gh).is_err()); 95 96 let oai = "openai_key = sk-`123456789012345678901234567890123456`"; 97 assert!(PersonalDataFirewall::verify_clean(oai).is_err()); 98 99 let ant = "anthropic_key = sk-ant-`123456789012345678901234567890123456`"; 100 assert!(PersonalDataFirewall::verify_clean(ant).is_err()); 101 102 let pkey = "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA\n-----END OPENSSH PRIVATE KEY-----"; 103 assert!(PersonalDataFirewall::verify_clean(pkey).is_err()); 104 105 let clean = "fn calculate_hash(data: &[u8]) -> [u8; 32] { blake3::hash(data).into() }"; 106 assert!(PersonalDataFirewall::verify_clean(clean).is_ok()); 107 } 108 109 #[test] 110 fn test_firewall_sanitizes_paths() { 111 let dirty = "Failure occurred at /home/drakestapleton/workspace/open-humanity/crates/lib.rs:10"; 112 let cleaned = PersonalDataFirewall::sanitize_paths(dirty); 113 assert_eq!(cleaned, "Failure occurred at ~/workspace/open-humanity/crates/lib.rs:10"); 114 assert!(!cleaned.contains("/home/drakestapleton/")); 115 } 116 117 #[test] 118 fn test_firewall_comprehensive_api_key_detection_and_redaction() { 119 let oai_proj = "export OPENAI_API_KEY=sk-proj-`abcdef1234567890abcdef1234567890`"; 120 assert!(matches!( 121 PersonalDataFirewall::verify_clean(oai_proj), 122 Err(FirewallViolation::OpenAiKey(_)) 123 )); 124 125 let ant_key = "ANTHROPIC_KEY=sk-ant-api03-`abcdef1234567890123456789012`"; 126 assert!(matches!( 127 PersonalDataFirewall::verify_clean(ant_key), 128 Err(FirewallViolation::AnthropicKey(_)) 129 )); 130 131 let gh_pat = format!("token = \"{}{}\"", "ghp_", "`123456789012345678901234567890123456`"); 132 let gh_oauth = "token = \"gho_`abcdef12345678901234567890123456789012`\""; 133 assert!(matches!( 134 PersonalDataFirewall::verify_clean(&gh_pat), 135 Err(FirewallViolation::GitHubToken(_)) 136 )); 137 assert!(matches!( 138 PersonalDataFirewall::verify_clean(gh_oauth), 139 Err(FirewallViolation::GitHubToken(_)) 140 )); 141 142 let aws_key = format!("AWS_ACCESS_KEY_ID={}{}", "AKIA", "IOSFODNN7EXAMPLE"); 143 assert!(matches!( 144 PersonalDataFirewall::verify_clean(&aws_key), 145 Err(FirewallViolation::AwsKey(_)) 146 )); 147 148 let google_key = "google_api_key = \"AIzaSyD-1234567890abcdefghijklmnopqrst\""; 149 assert!(matches!( 150 PersonalDataFirewall::verify_clean(google_key), 151 Err(FirewallViolation::GoogleApiKey(_)) 152 )); 153 154 let stripe_prefix = format!("{}_{}", "sk", "live"); 155 let stripe_live = format!("STRIPE_KEY={}_51Abcd1234567890abcdef1234567890", stripe_prefix); 156 let stripe_rk_prefix = format!("{}_{}", "rk", "live"); 157 let stripe_rk = format!("RESTRICTED_KEY={}_51Abcd1234567890abcdef1234567890", stripe_rk_prefix); 158 assert!(matches!( 159 PersonalDataFirewall::verify_clean(&stripe_live), 160 Err(FirewallViolation::StripeKey(_)) 161 )); 162 assert!(matches!( 163 PersonalDataFirewall::verify_clean(&stripe_rk), 164 Err(FirewallViolation::StripeKey(_)) 165 )); 166 167 let hf_token = "HF_AUTH=hf_Abcdefghijklmnopqrstuvwxyz12345678"; 168 assert!(matches!( 169 PersonalDataFirewall::verify_clean(hf_token), 170 Err(FirewallViolation::HuggingFaceToken(_)) 171 )); 172 173 let test_gh_pat = format!("{}{}", "ghp_", "`123456789012345678901234567890123456`"); 174 let test_aws_key = format!("{}{}", "AKIA", "IOSFODNN7EXAMPLE"); 175 let test_stripe_token = format!("{}_{}", "sk_live", "51Abcd1234567890abcdef1234567890"); 176 let combined = format!( 177 "Keys: sk-proj-`abcdef1234567890abcdef1234567890`, sk-ant-api03-`abcdef1234567890123456789012`, {}, {}, AIzaSyD-1234567890abcdefghijklmnopqrst, {}, hf_Abcdefghijklmnopqrstuvwxyz12345678", 178 test_gh_pat, test_aws_key, test_stripe_token 179 ); 180 let redacted = PersonalDataFirewall::redact_secrets(&combined); 181 assert!(!redacted.contains("sk-proj-")); 182 assert!(!redacted.contains("sk-ant-")); 183 assert!(!redacted.contains("ghp_")); 184 assert!(!redacted.contains("AKIA")); 185 assert!(!redacted.contains("AIza")); 186 assert!(!redacted.contains("sk_live_")); 187 assert!(!redacted.contains("hf_")); 188 assert!(redacted.contains("[REDACTED_OPENAI_KEY]")); 189 assert!(redacted.contains("[REDACTED_ANTHROPIC_KEY]")); 190 assert!(redacted.contains("[REDACTED_GITHUB_TOKEN]")); 191 assert!(redacted.contains("[REDACTED_AWS_KEY]")); 192 assert!(redacted.contains("[REDACTED_GOOGLE_KEY]")); 193 assert!(redacted.contains("[REDACTED_STRIPE_KEY]")); 194 assert!(redacted.contains("[REDACTED_HF_TOKEN]")); 195 } 196 197 #[test] 198 fn test_firewall_filesystem_path_sanitization_all_platforms() { 199 let linux_path = "/home/drakestapleton/workspace/open-humanity/target/debug/lib.rs"; 200 let cleaned_linux = PersonalDataFirewall::sanitize_paths(linux_path); 201 assert_eq!(cleaned_linux, "~/workspace/open-humanity/target/debug/lib.rs"); 202 203 let macos_path = "/Users/drakestapleton/Library/Application Support/OpenHumanity/config.json"; 204 let cleaned_macos = PersonalDataFirewall::sanitize_paths(macos_path); 205 assert_eq!(cleaned_macos, "~/Library/Application Support/OpenHumanity/config.json"); 206 207 let win_path = "C:\\Users\\drakestapleton\\AppData\\Local\\OpenHumanity\\vault.key"; 208 let cleaned_win = PersonalDataFirewall::sanitize_paths(win_path); 209 assert_eq!(cleaned_win, "~\\AppData\\Local\\OpenHumanity\\vault.key"); 210 211 let win_slash_path = "C:/Users/drakestapleton/AppData/Local/OpenHumanity/vault.key"; 212 let cleaned_win_slash = PersonalDataFirewall::sanitize_paths(win_slash_path); 213 assert_eq!(cleaned_win_slash, "~/AppData/Local/OpenHumanity/vault.key"); 214 215 let traversal = "../../../../etc/shadow"; 216 let cleaned_traversal = PersonalDataFirewall::sanitize_paths(traversal); 217 assert_eq!(cleaned_traversal, "./etc/shadow"); 218 219 let traversal_attempt = "cat ../../etc/passwd"; 220 assert!(matches!( 221 PersonalDataFirewall::verify_clean(traversal_attempt), 222 Err(FirewallViolation::PathTraversal(_)) 223 )); 224 } 225 226 #[test] 227 fn test_firewall_unicode_normalization_and_obfuscation() { 228 let zwsp_ant = "sk-\u{200B}ant-api03-`abcdef1234567890123456789012`"; 229 assert!(PersonalDataFirewall::verify_clean(zwsp_ant).is_err()); 230 231 let zwsp_aws = "A\u{200C}K\u{200D}IAIOSFODNN7EXAMPLE"; 232 assert!(PersonalDataFirewall::verify_clean(zwsp_aws).is_err()); 233 234 let urlenc_ant = "%73%6b%2d%61%6e%74%2dapi03%`2dabcdef1234567890123456789012`"; 235 assert!(PersonalDataFirewall::verify_clean(urlenc_ant).is_err()); 236 237 let urlenc_traversal = "%2e%2e%2f%2e%2e%2fetc/passwd"; 238 assert!(PersonalDataFirewall::verify_clean(urlenc_traversal).is_err()); 239 240 let leet_secret = "4pi_k3y = '`abcdef01234567890123456789`'"; 241 assert!(PersonalDataFirewall::verify_clean(leet_secret).is_err()); 242 } 243 244 #[test] 245 fn test_crypto_encryption_cycle() { 246 let recipient_secret = StaticSecret::random_from_rng(OsRng); 247 let recipient_pubkey = *X25519PublicKey::from(&recipient_secret).as_bytes(); 248 249 let message = b"fn solve() { println!(\"Fix applied\"); }"; 250 let encrypted = encrypt_to_peer(&recipient_pubkey, message) 251 .expect("encryption should succeed"); 252 253 let decrypted = decrypt_from_peer( 254 &recipient_secret, 255 &encrypted.ephemeral_pubkey, 256 &encrypted.nonce, 257 &encrypted.ciphertext, 258 ).expect("decryption should succeed"); 259 260 assert_eq!(decrypted, message); 261 } 262 263 #[test] 264 fn test_crypto_chacha20_poly1305_randomized_roundtrips() { 265 let payload_sizes = [0usize, 1, 16, 64, 256, 1024, 4096]; 266 for size in payload_sizes { 267 let recipient_secret = StaticSecret::random_from_rng(OsRng); 268 let recipient_pubkey = *X25519PublicKey::from(&recipient_secret).as_bytes(); 269 270 let mut message = vec![0u8; size]; 271 rand::RngCore::fill_bytes(&mut OsRng, &mut message); 272 273 let encrypted = encrypt_to_peer(&recipient_pubkey, &message) 274 .expect("encryption of random payload should succeed"); 275 276 let decrypted = decrypt_from_peer( 277 &recipient_secret, 278 &encrypted.ephemeral_pubkey, 279 &encrypted.nonce, 280 &encrypted.ciphertext, 281 ).expect("decryption of random payload should succeed"); 282 283 assert_eq!(decrypted, message, "Payload roundtrip failed for size {}", size); 284 } 285 } 286 287 #[test] 288 fn test_crypto_tampering_detection_single_bit_flip() { 289 let recipient_secret = StaticSecret::random_from_rng(OsRng); 290 let recipient_pubkey = *X25519PublicKey::from(&recipient_secret).as_bytes(); 291 let message = b"Confidential diagnosis payload for peer review"; 292 293 let encrypted = encrypt_to_peer(&recipient_pubkey, message) 294 .expect("encryption should succeed"); 295 296 for byte_idx in 0..encrypted.ciphertext.len() { 297 for bit in 0..8 { 298 let mut tampered_ciphertext = encrypted.ciphertext.clone(); 299 tampered_ciphertext[byte_idx] ^= 1 << bit; 300 301 let result = decrypt_from_peer( 302 &recipient_secret, 303 &encrypted.ephemeral_pubkey, 304 &encrypted.nonce, 305 &tampered_ciphertext, 306 ); 307 assert_eq!( 308 result, 309 Err(BeaconError::DecryptionFailed), 310 "Single bit flip at byte {} bit {} went undetected", 311 byte_idx, 312 bit 313 ); 314 } 315 } 316 } 317 318 #[test] 319 fn test_crypto_tampering_detection_altered_auth_tags() { 320 let recipient_secret = StaticSecret::random_from_rng(OsRng); 321 let recipient_pubkey = *X25519PublicKey::from(&recipient_secret).as_bytes(); 322 let message = b"Authenticated payload integrity test"; 323 324 let encrypted = encrypt_to_peer(&recipient_pubkey, message) 325 .expect("encryption should succeed"); 326 327 let tag_start = encrypted.ciphertext.len().saturating_sub(16); 328 for tag_idx in tag_start..encrypted.ciphertext.len() { 329 let mut corrupted = encrypted.ciphertext.clone(); 330 corrupted[tag_idx] ^= 0xFF; 331 332 let result = decrypt_from_peer( 333 &recipient_secret, 334 &encrypted.ephemeral_pubkey, 335 &encrypted.nonce, 336 &corrupted, 337 ); 338 assert_eq!( 339 result, 340 Err(BeaconError::DecryptionFailed), 341 "Corrupted authentication tag at byte {} went undetected", 342 tag_idx 343 ); 344 } 345 } 346 347 #[test] 348 fn test_crypto_tampering_detection_mismatched_keys() { 349 let recipient_a_secret = StaticSecret::random_from_rng(OsRng); 350 let recipient_a_pubkey = *X25519PublicKey::from(&recipient_a_secret).as_bytes(); 351 352 let recipient_b_secret = StaticSecret::random_from_rng(OsRng); 353 354 let message = b"Targeted payload for recipient A"; 355 let encrypted = encrypt_to_peer(&recipient_a_pubkey, message) 356 .expect("encryption should succeed"); 357 358 let result = decrypt_from_peer( 359 &recipient_b_secret, 360 &encrypted.ephemeral_pubkey, 361 &encrypted.nonce, 362 &encrypted.ciphertext, 363 ); 364 assert_eq!( 365 result, 366 Err(BeaconError::DecryptionFailed), 367 "Decryption by mismatched key unexpectedly succeeded" 368 ); 369 } 370 371 #[test] 372 fn test_crypto_replay_attack_resistance() { 373 let mut protector = ReplayProtector::new(100); 374 let packet_id = Uuid::now_v7(); 375 376 assert!(protector.check_and_record(&packet_id).is_ok()); 377 378 let replay_result = protector.check_and_record(&packet_id); 379 assert_eq!( 380 replay_result, 381 Err(BeaconError::ReplayDetected(packet_id)), 382 "Replay of identical packet ID must be rejected" 383 ); 384 385 let distinct_id = Uuid::now_v7(); 386 assert!(protector.check_and_record(&distinct_id).is_ok()); 387 } 388 389 #[test] 390 fn test_crypto_timestamp_drift_verification() { 391 let base_time: u64 = 1_700_000_000; 392 let max_drift: u64 = 300; 393 394 assert!(verify_timestamp_drift(base_time, base_time, max_drift).is_ok()); 395 assert!(verify_timestamp_drift(base_time + 120, base_time, max_drift).is_ok()); 396 assert!(verify_timestamp_drift(base_time - 120, base_time, max_drift).is_ok()); 397 assert!(verify_timestamp_drift(base_time + 300, base_time, max_drift).is_ok()); 398 assert!(verify_timestamp_drift(base_time - 300, base_time, max_drift).is_ok()); 399 400 assert!(matches!( 401 verify_timestamp_drift(base_time + 301, base_time, max_drift), 402 Err(BeaconError::TimestampDrift { drift_secs: 301, max_allowed: 300 }) 403 )); 404 405 assert!(matches!( 406 verify_timestamp_drift(base_time - 500, base_time, max_drift), 407 Err(BeaconError::TimestampDrift { drift_secs: 500, max_allowed: 300 }) 408 )); 409 } 410 }