| 1 | use crate::signature::Signature; |
| 2 | use sequoia_openpgp::cert::CertParser; |
| 3 | use sequoia_openpgp::parse::Parse; |
| 4 | use sequoia_openpgp::Cert; |
| 5 | use std::fmt; |
| 6 | use std::time::SystemTime; |
| 7 | |
| 8 | /// Errors that can occur during key management operations |
| 9 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 10 | pub enum KeyManagementError { |
| 11 | /// Failed to parse key data |
| 12 | ParseError(String), |
| 13 | /// No valid certificates found in key data |
| 14 | NoCertificates, |
| 15 | /// Key has expired |
| 16 | KeyExpired, |
| 17 | /// Key is not yet valid or has expired |
| 18 | KeyNotValid, |
| 19 | /// Key expires soon (includes days until expiration) |
| 20 | KeyExpiringSoon(u64), |
| 21 | /// Fingerprint mismatch |
| 22 | FingerprintMismatch { |
| 23 | /// Expected fingerprint |
| 24 | expected: String, |
| 25 | /// Actual fingerprint found |
| 26 | actual: String, |
| 27 | }, |
| 28 | /// Invalid fingerprint format |
| 29 | InvalidFingerprint(String), |
| 30 | /// Invalid fingerprint length |
| 31 | InvalidFingerprintLength { |
| 32 | /// Actual length of the fingerprint |
| 33 | length: usize, |
| 34 | /// Expected length description |
| 35 | expected: String, |
| 36 | }, |
| 37 | } |
| 38 | |
| 39 | impl fmt::Display for KeyManagementError { |
| 40 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 41 | match self { |
| 42 | KeyManagementError::ParseError(msg) => write!(f, "Failed to parse key data: {}", msg), |
| 43 | KeyManagementError::NoCertificates => { |
| 44 | write!(f, "No valid certificates found in key data") |
| 45 | } |
| 46 | KeyManagementError::KeyExpired => write!(f, "Key has expired"), |
| 47 | KeyManagementError::KeyNotValid => write!(f, "Key has expired or is not yet valid"), |
| 48 | KeyManagementError::KeyExpiringSoon(days) => write!(f, "Key expires in {} days", days), |
| 49 | KeyManagementError::FingerprintMismatch { expected, actual } => { |
| 50 | write!( |
| 51 | f, |
| 52 | "Fingerprint mismatch! Expected: {}, Got: {}", |
| 53 | expected, actual |
| 54 | ) |
| 55 | } |
| 56 | KeyManagementError::InvalidFingerprint(msg) => write!(f, "{}", msg), |
| 57 | KeyManagementError::InvalidFingerprintLength { length, expected } => { |
| 58 | write!( |
| 59 | f, |
| 60 | "Invalid fingerprint length: {}. Expected {}", |
| 61 | length, expected |
| 62 | ) |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | impl std::error::Error for KeyManagementError {} |
| 69 | |
| 70 | /// Check if a GPG key is expired or about to expire |
| 71 | pub fn check_key_expiration(cert: &Cert) -> Option<KeyManagementError> { |
| 72 | use sequoia_openpgp::policy::StandardPolicy; |
| 73 | |
| 74 | let policy = StandardPolicy::new(); |
| 75 | let now = SystemTime::now(); |
| 76 | |
| 77 | // Check if the certificate is alive according to the policy |
| 78 | match cert.with_policy(&policy, now) { |
| 79 | Ok(valid_cert) => { |
| 80 | // Check if primary key has expiration |
| 81 | if let Some(expiration) = valid_cert.primary_key().key_expiration_time() { |
| 82 | if expiration <= now { |
| 83 | return Some(KeyManagementError::KeyExpired); |
| 84 | } |
| 85 | |
| 86 | // Warn if expiring within 30 days |
| 87 | if let Ok(duration_until) = expiration.duration_since(now) { |
| 88 | let days_until = duration_until.as_secs() / 86400; |
| 89 | if days_until < 30 { |
| 90 | return Some(KeyManagementError::KeyExpiringSoon(days_until)); |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | None |
| 95 | } |
| 96 | Err(_) => { |
| 97 | // Certificate or one of its components has expired or is not valid |
| 98 | Some(KeyManagementError::KeyNotValid) |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// Verify that a key's fingerprint matches the expected fingerprint |
| 104 | pub fn verify_key_fingerprint( |
| 105 | key_data: &str, |
| 106 | expected_fingerprint: &str, |
| 107 | ) -> Result<(), KeyManagementError> { |
| 108 | let parser = CertParser::from_bytes(key_data.as_bytes()) |
| 109 | .map_err(|e| KeyManagementError::ParseError(e.to_string()))?; |
| 110 | |
| 111 | let certs: Result<Vec<Cert>, _> = parser.collect(); |
| 112 | let certs = certs.map_err(|e| KeyManagementError::ParseError(e.to_string()))?; |
| 113 | |
| 114 | if certs.is_empty() { |
| 115 | return Err(KeyManagementError::NoCertificates); |
| 116 | } |
| 117 | |
| 118 | let cert = &certs[0]; |
| 119 | let fingerprint = cert.fingerprint().to_hex(); |
| 120 | |
| 121 | // Normalize fingerprints for comparison (remove spaces and make uppercase) |
| 122 | let normalized_actual = fingerprint.replace(" ", "").to_uppercase(); |
| 123 | let normalized_expected = expected_fingerprint.replace(" ", "").to_uppercase(); |
| 124 | |
| 125 | if normalized_actual != normalized_expected { |
| 126 | return Err(KeyManagementError::FingerprintMismatch { |
| 127 | expected: expected_fingerprint.to_string(), |
| 128 | actual: fingerprint, |
| 129 | }); |
| 130 | } |
| 131 | |
| 132 | Ok(()) |
| 133 | } |
| 134 | |
| 135 | /// Create an inline signature from GPG key data |
| 136 | pub fn create_inline_signature(key_data: &str) -> Result<Signature, KeyManagementError> { |
| 137 | // First, let's parse the key to validate it |
| 138 | let parser = CertParser::from_bytes(key_data.as_bytes()) |
| 139 | .map_err(|e| KeyManagementError::ParseError(e.to_string()))?; |
| 140 | |
| 141 | let certs: Result<Vec<Cert>, _> = parser.collect(); |
| 142 | let certs = certs.map_err(|e| KeyManagementError::ParseError(e.to_string()))?; |
| 143 | |
| 144 | if certs.is_empty() { |
| 145 | return Err(KeyManagementError::NoCertificates); |
| 146 | } |
| 147 | |
| 148 | // Check for expiration |
| 149 | if let Some(error) = check_key_expiration(&certs[0]) { |
| 150 | eprintln!("Warning: {}", error); |
| 151 | } |
| 152 | |
| 153 | // Create inline signature with the key data (using KeyBlock variant) |
| 154 | Ok(Signature::KeyBlock(key_data.to_string())) |
| 155 | } |
| 156 | |
| 157 | /// Validate a GPG fingerprint format |
| 158 | pub fn validate_fingerprint(fingerprint: &str) -> Result<String, KeyManagementError> { |
| 159 | // Remove spaces and convert to uppercase |
| 160 | let cleaned = fingerprint.replace(" ", "").to_uppercase(); |
| 161 | |
| 162 | // Check if it's a valid hex string |
| 163 | if !cleaned.chars().all(|c| c.is_ascii_hexdigit()) { |
| 164 | return Err(KeyManagementError::InvalidFingerprint( |
| 165 | "Fingerprint must contain only hexadecimal characters".to_string(), |
| 166 | )); |
| 167 | } |
| 168 | |
| 169 | // GPG fingerprints should be 40 characters (160 bits) for SHA-1 |
| 170 | // or 64 characters (256 bits) for SHA-256 |
| 171 | if cleaned.len() != 40 && cleaned.len() != 64 { |
| 172 | return Err(KeyManagementError::InvalidFingerprintLength { |
| 173 | length: cleaned.len(), |
| 174 | expected: "40 or 64 characters".to_string(), |
| 175 | }); |
| 176 | } |
| 177 | |
| 178 | Ok(cleaned) |
| 179 | } |
| 180 | |
| 181 | #[cfg(test)] |
| 182 | mod tests { |
| 183 | use super::*; |
| 184 | |
| 185 | #[test] |
| 186 | fn test_validate_fingerprint() { |
| 187 | // Valid SHA-1 fingerprint |
| 188 | assert!(validate_fingerprint("1234567890ABCDEF1234567890ABCDEF12345678").is_ok()); |
| 189 | |
| 190 | // Valid with spaces |
| 191 | assert!(validate_fingerprint("1234 5678 90AB CDEF 1234 5678 90AB CDEF 1234 5678").is_ok()); |
| 192 | |
| 193 | // Invalid characters |
| 194 | assert!(validate_fingerprint("XXXX567890ABCDEF1234567890ABCDEF12345678").is_err()); |
| 195 | |
| 196 | // Invalid length |
| 197 | assert!(validate_fingerprint("1234567890ABCDEF").is_err()); |
| 198 | } |
| 199 | } |