cargocrypt 0.2.0

Zero-config cryptographic operations for Rust projects with HIVE MIND collective intelligence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Error types for CargoCrypt
//!
//! This module provides comprehensive error handling with actionable error messages
//! that help developers understand and fix issues quickly.

// use std::fmt; // Currently unused

/// Error severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorSeverity {
    Info,
    Warning,
    Critical,
}

/// Result type alias for CargoCrypt operations
pub type CryptoResult<T> = Result<T, CargoCryptError>;

/// Main error type for CargoCrypt operations
#[derive(Debug, thiserror::Error)]
pub enum CargoCryptError {
    /// I/O errors (file operations, network, etc.)
    #[error("File operation failed: {message}")]
    Io {
        message: String,
        #[source]
        source: std::io::Error,
    },

    /// Cryptographic operation errors
    #[error("Cryptographic operation failed: {message}")]
    Crypto {
        message: String,
        kind: CryptoErrorKind,
    },

    /// Configuration errors
    #[error("Configuration error: {message}")]
    Config {
        message: String,
        suggestion: Option<String>,
    },

    /// Project structure errors
    #[error("Project structure error: {message}")]
    Project {
        message: String,
        suggestion: Option<String>,
    },

    /// Authentication/Authorization errors
    #[error("Authentication failed: {message}")]
    Auth {
        message: String,
        retry_suggestion: Option<String>,
    },

    /// Key management errors
    #[error("Key management error: {message}")]
    KeyManagement {
        message: String,
        recovery_suggestion: Option<String>,
    },

    /// Serialization/Deserialization errors
    #[error("Serialization error: {message}")]
    Serialization {
        message: String,
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// Network-related errors
    #[error("Network error: {message}")]
    Network {
        message: String,
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// Git operations errors
    #[error("Git operation failed: {message}")]
    Git {
        message: String,
        #[source]
        source: Option<git2::Error>,
    },

    /// Validation errors
    #[error("Validation failed: {message}")]
    Validation {
        message: String,
        errors: Vec<String>,
        warnings: Vec<String>,
    },
}

/// Specific kinds of cryptographic errors
#[derive(Debug, Clone, PartialEq)]
pub enum CryptoErrorKind {
    /// Key derivation failed
    KeyDerivation,
    /// Encryption failed
    Encryption,
    /// Decryption failed
    Decryption,
    /// Invalid key format or length
    InvalidKey,
    /// Invalid nonce or IV
    InvalidNonce,
    /// Authentication tag verification failed
    AuthenticationFailed,
    /// Unsupported algorithm
    UnsupportedAlgorithm,
    /// Random number generation failed
    RandomGenerationFailed,
}

/// Commonly used error constructors for better ergonomics
impl CargoCryptError {
    /// Get the severity level of this error
    pub fn severity(&self) -> ErrorSeverity {
        match self {
            CargoCryptError::Crypto { kind, .. } => match kind {
                CryptoErrorKind::AuthenticationFailed |
                CryptoErrorKind::Decryption |
                CryptoErrorKind::InvalidKey => ErrorSeverity::Critical,
                _ => ErrorSeverity::Warning,
            },
            CargoCryptError::Validation { .. } => ErrorSeverity::Warning,
            CargoCryptError::Auth { .. } => ErrorSeverity::Critical,
            CargoCryptError::KeyManagement { .. } => ErrorSeverity::Critical,
            CargoCryptError::Network { .. } => ErrorSeverity::Warning,
            CargoCryptError::Git { .. } => ErrorSeverity::Warning,
            CargoCryptError::Io { .. } => ErrorSeverity::Warning,
            CargoCryptError::Config { .. } => ErrorSeverity::Info,
            CargoCryptError::Project { .. } => ErrorSeverity::Info,
            CargoCryptError::Serialization { .. } => ErrorSeverity::Warning,
        }
    }
    /// Create a project not found error with helpful suggestion
    pub fn project_not_found() -> Self {
        Self::Project {
            message: "Could not find Cargo.toml in current directory or any parent directories".to_string(),
            suggestion: Some("Run this command from within a Rust project directory, or use 'cargo new' to create a new project".to_string()),
        }
    }

    /// Create a configuration file not found error
    pub fn config_not_found() -> Self {
        Self::Config {
            message: "CargoCrypt configuration file not found".to_string(),
            suggestion: Some("Run 'cargo crypt init' to create a new configuration".to_string()),
        }
    }

    /// Create an invalid password error
    pub fn invalid_password() -> Self {
        Self::Auth {
            message: "Password verification failed".to_string(),
            retry_suggestion: Some("Please check your password and try again".to_string()),
        }
    }

    /// Create a file not found error with context
    pub fn file_not_found(path: &std::path::Path) -> Self {
        Self::Io {
            message: format!("File not found: {}", path.display()),
            source: std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("File '{}' does not exist", path.display()),
            ),
        }
    }

    /// Create a decryption failure error
    pub fn decryption_failed(details: &str) -> Self {
        Self::Crypto {
            message: format!("Decryption failed: {}", details),
            kind: CryptoErrorKind::Decryption,
        }
    }

    /// Create an encryption failure error
    pub fn encryption_failed(details: &str) -> Self {
        Self::Crypto {
            message: format!("Encryption failed: {}", details),
            kind: CryptoErrorKind::Encryption,
        }
    }

    /// Create a key derivation failure error
    pub fn key_derivation_failed(details: &str) -> Self {
        Self::Crypto {
            message: format!("Key derivation failed: {}", details),
            kind: CryptoErrorKind::KeyDerivation,
        }
    }

    /// Create an invalid key error
    pub fn invalid_key(details: &str) -> Self {
        Self::Crypto {
            message: format!("Invalid key: {}", details),
            kind: CryptoErrorKind::InvalidKey,
        }
    }

    /// Create an authentication failure error
    pub fn authentication_failed() -> Self {
        Self::Crypto {
            message: "Authentication tag verification failed - data may be corrupted or tampered with".to_string(),
            kind: CryptoErrorKind::AuthenticationFailed,
        }
    }

    /// Create a random generation failure error
    pub fn random_generation_failed() -> Self {
        Self::Crypto {
            message: "Failed to generate cryptographically secure random data".to_string(),
            kind: CryptoErrorKind::RandomGenerationFailed,
        }
    }

    /// Create a detection error
    pub fn detection_error(message: &str) -> Self {
        Self::Config {
            message: format!("Detection error: {}", message),
            suggestion: Some("Check detection configuration and patterns".to_string()),
        }
    }

    /// Get the error kind if this is a crypto error
    pub fn crypto_kind(&self) -> Option<&CryptoErrorKind> {
        match self {
            CargoCryptError::Crypto { kind, .. } => Some(kind),
            _ => None,
        }
    }

    /// Check if this error is recoverable (user can retry)
    pub fn is_recoverable(&self) -> bool {
        match self {
            CargoCryptError::Auth { .. } => true,
            CargoCryptError::Network { .. } => true,
            CargoCryptError::Io { source, .. } => matches!(
                source.kind(),
                std::io::ErrorKind::NotFound
                    | std::io::ErrorKind::PermissionDenied
                    | std::io::ErrorKind::ConnectionRefused
                    | std::io::ErrorKind::TimedOut
            ),
            CargoCryptError::Crypto { kind, .. } => matches!(
                kind,
                CryptoErrorKind::RandomGenerationFailed
            ),
            _ => false,
        }
    }

    /// Get a user-friendly suggestion for resolving this error
    pub fn suggestion(&self) -> Option<&str> {
        match self {
            CargoCryptError::Config { suggestion, .. } => suggestion.as_deref(),
            CargoCryptError::Project { suggestion, .. } => suggestion.as_deref(),
            CargoCryptError::Auth { retry_suggestion, .. } => retry_suggestion.as_deref(),
            CargoCryptError::KeyManagement { recovery_suggestion, .. } => recovery_suggestion.as_deref(),
            _ => None,
        }
    }
}

/// Convert from standard I/O errors
impl From<std::io::Error> for CargoCryptError {
    fn from(error: std::io::Error) -> Self {
        Self::Io {
            message: error.to_string(),
            source: error,
        }
    }
}

/// Convert from CryptoError
impl From<crate::crypto::CryptoError> for CargoCryptError {
    fn from(error: crate::crypto::CryptoError) -> Self {
        use crate::crypto::CryptoError;
        
        let kind = match &error {
            CryptoError::KeyDerivation { .. } => CryptoErrorKind::KeyDerivation,
            CryptoError::Encryption { .. } => CryptoErrorKind::Encryption,
            CryptoError::Decryption { .. } => CryptoErrorKind::Decryption,
            CryptoError::AuthenticationFailed => CryptoErrorKind::AuthenticationFailed,
            CryptoError::InvalidKey { .. } => CryptoErrorKind::InvalidKey,
            CryptoError::InvalidNonce { .. } => CryptoErrorKind::InvalidNonce,
            CryptoError::RandomGeneration { .. } => CryptoErrorKind::RandomGenerationFailed,
            _ => CryptoErrorKind::Encryption, // Default fallback
        };
        
        Self::Crypto {
            message: error.to_string(),
            kind,
        }
    }
}

/// Convert from serde JSON errors
impl From<serde_json::Error> for CargoCryptError {
    fn from(error: serde_json::Error) -> Self {
        Self::Serialization {
            message: format!("JSON serialization failed: {}", error),
            source: Box::new(error),
        }
    }
}

/// Convert from TOML errors
impl From<toml::de::Error> for CargoCryptError {
    fn from(error: toml::de::Error) -> Self {
        Self::Serialization {
            message: format!("TOML parsing failed: {}", error),
            source: Box::new(error),
        }
    }
}

/// Convert from reqwest errors
impl From<reqwest::Error> for CargoCryptError {
    fn from(error: reqwest::Error) -> Self {
        Self::Network {
            message: format!("HTTP request failed: {}", error),
            source: Box::new(error),
        }
    }
}

/// Convert from git2 errors
impl From<git2::Error> for CargoCryptError {
    fn from(error: git2::Error) -> Self {
        Self::Git {
            message: format!("Git operation failed: {}", error.message()),
            source: Some(error),
        }
    }
}

impl From<crate::git::GitError> for CargoCryptError {
    fn from(error: crate::git::GitError) -> Self {
        Self::Git {
            message: format!("Git integration failed: {}", error),
            source: None,
        }
    }
}

/// Error kind enumeration for programmatic error handling
#[derive(Debug, Clone, PartialEq)]
pub enum ErrorKind {
    /// Configuration-related errors
    Config,
    /// File system operation errors
    Io,
    /// Cryptographic operation errors
    Crypto,
    /// Network operation errors
    Network,
    /// Authentication/authorization errors
    Auth,
    /// Git operation errors
    Git,
    /// Project structure errors
    Project,
    /// Key management errors
    KeyManagement,
    /// Serialization errors
    Serialization,
}

impl CargoCryptError {
    /// Get the general error kind
    pub fn kind(&self) -> ErrorKind {
        match self {
            CargoCryptError::Config { .. } => ErrorKind::Config,
            CargoCryptError::Io { .. } => ErrorKind::Io,
            CargoCryptError::Crypto { .. } => ErrorKind::Crypto,
            CargoCryptError::Network { .. } => ErrorKind::Network,
            CargoCryptError::Auth { .. } => ErrorKind::Auth,
            CargoCryptError::Git { .. } => ErrorKind::Git,
            CargoCryptError::Project { .. } => ErrorKind::Project,
            CargoCryptError::KeyManagement { .. } => ErrorKind::KeyManagement,
            CargoCryptError::Serialization { .. } => ErrorKind::Serialization,
            CargoCryptError::Validation { .. } => ErrorKind::Config,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_constructors() {
        let err = CargoCryptError::project_not_found();
        assert!(matches!(err.kind(), ErrorKind::Project));
        assert!(err.suggestion().is_some());

        let err = CargoCryptError::invalid_password();
        assert!(matches!(err.kind(), ErrorKind::Auth));
        assert!(err.is_recoverable());
    }

    #[test]
    fn test_crypto_error_kinds() {
        let err = CargoCryptError::decryption_failed("test");
        assert_eq!(err.crypto_kind(), Some(&CryptoErrorKind::Decryption));

        let err = CargoCryptError::encryption_failed("test");
        assert_eq!(err.crypto_kind(), Some(&CryptoErrorKind::Encryption));
    }

    #[test]
    fn test_error_conversions() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "test");
        let crypto_err: CargoCryptError = io_err.into();
        assert!(matches!(crypto_err.kind(), ErrorKind::Io));
    }

    #[test]
    fn test_recoverable_errors() {
        let auth_err = CargoCryptError::invalid_password();
        assert!(auth_err.is_recoverable());

        let config_err = CargoCryptError::config_not_found();
        assert!(!config_err.is_recoverable());
    }
}