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/rad-id-sync/blob/main/src/keys.rs # rad-id-sync This project has not described itself yet. 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 `rad-id-sync / src / keys.rs` 177 lines ยท 6368 bytes Raw Blame History 1 use crate::identity::{IdentityAnchor, KeyRecord}; 2 use sha2::{Digest, Sha256}; 3 use std::fs; 4 use std::path::PathBuf; 5 6 #[derive(Debug, serde::Serialize, serde::Deserialize)] 7 pub struct SyncReport { 8 pub anchor_did: String, 9 pub entity_name: String, 10 pub radicle_key_detected: Option, 11 pub ssh_key_detected: Option, 12 pub in_sync: bool, 13 pub rotated: bool, 14 pub message: String, 15 } 16 17 pub fn get_sha256_fingerprint(key_str: &str) -> String { 18 let mut hasher = Sha256::new(); 19 hasher.update(key_str.trim().as_bytes()); 20 hex::encode(hasher.finalize()) 21 } 22 23 /// Validate format of detected public keys. 24 pub fn validate_public_key_format(key_type: &str, key_str: &str) -> Result<(), String> { 25 let trimmed = key_str.trim(); 26 if trimmed.is_empty() { 27 return Err("Public key is empty".to_string()); 28 } 29 30 match key_type { 31 "ssh-`ed25519`" => { 32 if !trimmed.starts_with("ssh-`ed25519` ") { 33 return Err("Invalid SSH Ed25519 key format: expected prefix ssh-`ed25519`".to_string()); 34 } 35 let parts: Vec<&str> = trimmed.split_whitespace().collect(); 36 if parts.len() < 2 { 37 return Err("Malformed SSH key: missing base64 token payload".to_string()); 38 } 39 if parts[1].len() < 32 { 40 return Err("SSH key payload too short for Ed25519 public key".to_string()); 41 } 42 Ok(()) 43 } 44 "radicle-`ed25519`" => { 45 if trimmed.starts_with("ssh-`ed25519` ") || trimmed.starts_with("rad:") || trimmed.len() >= 32 { 46 Ok(()) 47 } else { 48 Err("Invalid Radicle public key length or format".to_string()) 49 } 50 } 51 _ => Ok(()), 52 } 53 } 54 55 pub fn discover_local_keys() -> (Option, Option) { 56 let home = std::env::var("HOME").unwrap_or_else(|_| "/home/drakestapleton".to_string()); 57 58 // 1. Radicle Key 59 let rad_pub_path = PathBuf::from(&home).join(".radicle").join("keys").join("radicle.pub"); 60 let rad_key = if rad_pub_path.exists() { 61 fs::read_to_string(rad_pub_path).ok().map(|s| s.trim().to_string()) 62 } else { 63 None 64 }; 65 66 // 2. SSH Key 67 let ssh_pub_path = PathBuf::from(&home).join(".ssh").join("id_`ed25519`.pub"); 68 let ssh_key = if ssh_pub_path.exists() { 69 fs::read_to_string(ssh_pub_path).ok().map(|s| s.trim().to_string()) 70 } else { 71 None 72 }; 73 74 (rad_key, ssh_key) 75 } 76 77 pub fn sync_identity_keys(mut anchor: IdentityAnchor) -> Result<(IdentityAnchor, SyncReport), String> { 78 let (rad_key, ssh_key) = discover_local_keys(); 79 let mut rotated = false; 80 let mut message = "Keys are already synchronized with Identity Anchor.".to_string(); 81 82 let now = chrono::Utc::now().to_rfc3339(); 83 84 // Check Radicle Key sync 85 if let Some(ref r_key) = rad_key { 86 validate_public_key_format("radicle-`ed25519`", r_key)?; 87 if anchor.primary_radicle_key.as_ref() != Some(r_key) { 88 if anchor.primary_radicle_key.is_some() { 89 rotated = true; 90 message = "Detected rotated Radicle public key; updated Identity Anchor.".to_string(); 91 } 92 anchor.primary_radicle_key = Some(r_key.clone()); 93 anchor.key_history.push(KeyRecord { 94 key_type: "radicle-`ed25519`".to_string(), 95 public_key: r_key.clone(), 96 finger_print: get_sha256_fingerprint(r_key), 97 added_at: now.clone(), 98 status: "active".to_string(), 99 }); 100 } 101 } 102 103 // Check SSH Key sync 104 if let Some(ref s_key) = ssh_key { 105 validate_public_key_format("ssh-`ed25519`", s_key)?; 106 if anchor.primary_ssh_key.as_ref() != Some(s_key) { 107 if anchor.primary_ssh_key.is_some() { 108 rotated = true; 109 message = "Detected updated SSH public key; updated Identity Anchor.".to_string(); 110 } 111 anchor.primary_ssh_key = Some(s_key.clone()); 112 anchor.key_history.push(KeyRecord { 113 key_type: "ssh-`ed25519`".to_string(), 114 public_key: s_key.clone(), 115 finger_print: get_sha256_fingerprint(s_key), 116 added_at: now.clone(), 117 status: "active".to_string(), 118 }); 119 } 120 } 121 122 anchor.last_synced_at = now; 123 anchor.save()?; 124 125 let in_sync = anchor.primary_ssh_key.is_some() || anchor.primary_radicle_key.is_some(); 126 127 let report = SyncReport { 128 anchor_did: anchor.did.clone(), 129 entity_name: anchor.name.clone(), 130 radicle_key_detected: rad_key, 131 ssh_key_detected: ssh_key, 132 in_sync, 133 rotated, 134 message, 135 }; 136 137 Ok((anchor, report)) 138 } 139 140 #[cfg(test)] 141 mod tests { 142 use super::*; 143 144 #[test] 145 fn test_sha256_fingerprint_deterministic() { 146 let sample = "ssh-`ed25519` AAAAC3NzaC1lZDI1NTE5AAAAIExamplePublicKey user@host"; 147 let fp1 = get_sha256_fingerprint(sample); 148 let fp2 = get_sha256_fingerprint(sample); 149 assert_eq!(fp1, fp2); 150 assert_eq!(fp1.len(), 64); 151 } 152 153 #[test] 154 fn test_sync_report_serialization() { 155 let report = SyncReport { 156 anchor_did: "did:rad:aien:spark-01".to_string(), 157 entity_name: "AIEN".to_string(), 158 radicle_key_detected: Some("ssh-`ed25519` AAAAC...".to_string()), 159 ssh_key_detected: Some("ssh-`ed25519` AAAAC...".to_string()), 160 in_sync: true, 161 rotated: false, 162 message: "All keys synchronized.".to_string(), 163 }; 164 let json = serde_json::to_string(&report).expect("serializable"); 165 assert!(json.contains("did:rad:aien:spark-01")); 166 assert!(json.contains("All keys synchronized.")); 167 } 168 169 #[test] 170 fn test_validate_public_key_format() { 171 assert!(validate_public_key_format("ssh-`ed25519`", "ssh-`ed25519` AAAAC3NzaC1lZDI1NTE5AAAAIExampleValidPayloadKey user@host").is_ok()); 172 assert!(validate_public_key_format("ssh-`ed25519`", "rsa-bad AAAAC3").is_err()); 173 assert!(validate_public_key_format("ssh-`ed25519`", "ssh-`ed25519` short").is_err()); 174 assert!(validate_public_key_format("radicle-`ed25519`", "rad:z6MkuTf9Vd6F4sM6eS2y5fV9tF3p").is_ok()); 175 assert!(validate_public_key_format("radicle-`ed25519`", "").is_err()); 176 } 177 }