cargocrypt 0.1.1

Zero-config cryptographic operations for Rust projects
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//! Core CargoCrypt functionality
//!
//! This module provides the main CargoCrypt struct and configuration types
//! for zero-config cryptographic operations.

use crate::error::{CargoCryptError, CryptoResult};
use crate::crypto::{CryptoEngine, PerformanceProfile, EncryptedSecret};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;
use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, ZeroizeOnDrop};

/// Main CargoCrypt struct providing cryptographic operations
///
/// This struct embodies the zero-config philosophy - it works out of the box
/// with sensible defaults while allowing customization when needed.
#[derive(Debug)]
pub struct CargoCrypt {
    /// Cryptographic engine for operations
    engine: Arc<CryptoEngine>,
    /// Configuration settings
    config: Arc<RwLock<CryptoConfig>>,
    /// Project root directory
    project_root: PathBuf,
    /// Secret store for memory-safe secret management
    secret_store: Arc<dyn SecretStore>,
}

/// Configuration for CargoCrypt operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CryptoConfig {
    /// Default performance profile for encryption
    pub performance_profile: PerformanceProfile,
    /// Key derivation parameters
    pub key_params: KeyDerivationConfig,
    /// File operation settings
    pub file_ops: FileOperationConfig,
    /// Security settings
    pub security: SecurityConfig,
    /// Performance settings
    pub performance: PerformanceConfig,
}

/// Key derivation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyDerivationConfig {
    /// Memory cost in KiB (default: 65536 = 64 MB)
    pub memory_cost: u32,
    /// Time cost (iterations, default: 3)
    pub time_cost: u32,
    /// Parallelism (default: 4)
    pub parallelism: u32,
    /// Output length in bytes (default: 32)
    pub output_length: u32,
}

/// File operation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileOperationConfig {
    /// Backup original files before encryption
    pub backup_originals: bool,
    /// File extension for encrypted files
    pub encrypted_extension: String,
    /// Buffer size for file operations
    pub buffer_size: usize,
    /// Preserve file permissions
    pub preserve_permissions: bool,
}

/// Security configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    /// Require password confirmation for destructive operations
    pub require_confirmation: bool,
    /// Automatically zeroize sensitive data
    pub auto_zeroize: bool,
    /// Fail secure by default
    pub fail_secure: bool,
    /// Maximum password attempts
    pub max_password_attempts: u32,
}

/// Performance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Enable async operations
    pub async_operations: bool,
    /// Number of concurrent operations
    pub max_concurrent_ops: usize,
    /// Enable progress reporting
    pub progress_reporting: bool,
    /// Cache frequently used keys
    pub key_caching: bool,
}

/// Trait for secure secret storage with automatic zeroization
pub trait SecretStore: Send + Sync + std::fmt::Debug {
    /// Store a secret securely
    fn store_secret(&self, key: &str, secret: SecretBytes) -> CryptoResult<()>;
    
    /// Retrieve a secret (returns None if not found)
    fn get_secret(&self, key: &str) -> CryptoResult<Option<SecretBytes>>;
    
    /// Remove a secret
    fn remove_secret(&self, key: &str) -> CryptoResult<bool>;
    
    /// Clear all secrets
    fn clear_all(&self) -> CryptoResult<()>;
    
    /// Check if a secret exists
    fn contains_secret(&self, key: &str) -> bool;
    
    /// Get the number of stored secrets
    fn secret_count(&self) -> usize;
}

/// Memory-safe secret storage with automatic zeroization
#[derive(Debug, Clone, Zeroize, ZeroizeOnDrop)]
pub struct SecretBytes {
    inner: Vec<u8>,
}

impl SecretBytes {
    /// Create a new secret from bytes
    pub fn new(data: Vec<u8>) -> Self {
        Self { inner: data }
    }
    
    /// Create a new secret from a string
    pub fn from_str(s: &str) -> Self {
        Self::new(s.as_bytes().to_vec())
    }
    
    /// Get the secret data (careful with this!)
    pub fn expose_secret(&self) -> &[u8] {
        &self.inner
    }
    
    /// Get the length of the secret
    pub fn len(&self) -> usize {
        self.inner.len()
    }
    
    /// Check if the secret is empty
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
    
    /// Convert to a string (if valid UTF-8)
    pub fn to_string_lossy(&self) -> String {
        String::from_utf8_lossy(&self.inner).to_string()
    }
}

/// In-memory secret store implementation
#[derive(Debug, Default)]
pub struct InMemorySecretStore {
    secrets: Arc<RwLock<std::collections::HashMap<String, SecretBytes>>>,
}

impl InMemorySecretStore {
    /// Create a new in-memory secret store
    pub fn new() -> Self {
        Self {
            secrets: Arc::new(RwLock::new(std::collections::HashMap::new())),
        }
    }
}

impl SecretStore for InMemorySecretStore {
    fn store_secret(&self, key: &str, secret: SecretBytes) -> CryptoResult<()> {
        let mut secrets = self.secrets.blocking_write();
        secrets.insert(key.to_string(), secret);
        Ok(())
    }
    
    fn get_secret(&self, key: &str) -> CryptoResult<Option<SecretBytes>> {
        let secrets = self.secrets.blocking_read();
        Ok(secrets.get(key).cloned())
    }
    
    fn remove_secret(&self, key: &str) -> CryptoResult<bool> {
        let mut secrets = self.secrets.blocking_write();
        Ok(secrets.remove(key).is_some())
    }
    
    fn clear_all(&self) -> CryptoResult<()> {
        let mut secrets = self.secrets.blocking_write();
        secrets.clear();
        Ok(())
    }
    
    fn contains_secret(&self, key: &str) -> bool {
        let secrets = self.secrets.blocking_read();
        secrets.contains_key(key)
    }
    
    fn secret_count(&self) -> usize {
        let secrets = self.secrets.blocking_read();
        secrets.len()
    }
}

/// Default implementations for configuration structs
impl Default for CryptoConfig {
    fn default() -> Self {
        Self {
            performance_profile: PerformanceProfile::Balanced,
            key_params: KeyDerivationConfig::default(),
            file_ops: FileOperationConfig::default(),
            security: SecurityConfig::default(),
            performance: PerformanceConfig::default(),
        }
    }
}

impl Default for KeyDerivationConfig {
    fn default() -> Self {
        Self {
            memory_cost: 65536,    // 64 MB
            time_cost: 3,          // 3 iterations
            parallelism: 4,        // 4 parallel threads
            output_length: 32,     // 32 bytes (256 bits)
        }
    }
}

impl Default for FileOperationConfig {
    fn default() -> Self {
        Self {
            backup_originals: true,
            encrypted_extension: "enc".to_string(),
            buffer_size: 64 * 1024, // 64 KB buffer
            preserve_permissions: true,
        }
    }
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            require_confirmation: true,
            auto_zeroize: true,
            fail_secure: true,
            max_password_attempts: 3,
        }
    }
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            async_operations: true,
            max_concurrent_ops: 4,
            progress_reporting: true,
            key_caching: true,
        }
    }
}

/// Implementation of CargoCrypt main functionality
impl CargoCrypt {
    /// Create a new CargoCrypt instance with default configuration
    ///
    /// This is the zero-config entry point - it automatically:
    /// - Detects the current project structure
    /// - Loads or creates configuration
    /// - Initializes crypto engine with secure defaults
    /// - Sets up memory-safe secret storage
    pub async fn new() -> CryptoResult<Self> {
        let config = CryptoConfig::default();
        Self::with_config(config).await
    }
    
    /// Create a new CargoCrypt instance with custom configuration
    pub async fn with_config(config: CryptoConfig) -> CryptoResult<Self> {
        let project_root = crate::utils::find_project_root()?;
        let engine = Arc::new(CryptoEngine::with_performance_profile(config.performance_profile));
        let secret_store = Arc::new(InMemorySecretStore::new());
        
        Ok(Self {
            engine,
            config: Arc::new(RwLock::new(config)),
            project_root,
            secret_store,
        })
    }
    
    /// Initialize CargoCrypt in a project directory
    ///
    /// This creates the necessary configuration files and directory structure
    /// if they don't already exist.
    pub async fn init_project() -> CryptoResult<()> {
        let project_root = crate::utils::find_project_root()?;
        let config_dir = project_root.join(".cargocrypt");
        
        // Create configuration directory
        if !config_dir.exists() {
            tokio::fs::create_dir_all(&config_dir).await?;
        }
        
        // Create default configuration file
        let config_path = config_dir.join("config.toml");
        if !config_path.exists() {
            let default_config = CryptoConfig::default();
            let config_toml = toml::to_string_pretty(&default_config)
                .map_err(|e| CargoCryptError::Serialization {
                    message: "Failed to serialize default configuration".to_string(),
                    source: Box::new(e),
                })?;
            tokio::fs::write(&config_path, config_toml).await?;
        }
        
        // Create .gitignore entry for secrets
        let gitignore_path = project_root.join(".gitignore");
        let gitignore_entry = "\n# CargoCrypt secrets\n.cargocrypt/secrets/\n*.enc\n";
        
        if gitignore_path.exists() {
            let existing_content = tokio::fs::read_to_string(&gitignore_path).await?;
            if !existing_content.contains(".cargocrypt/secrets/") {
                tokio::fs::write(&gitignore_path, existing_content + gitignore_entry).await?;
            }
        } else {
            tokio::fs::write(&gitignore_path, gitignore_entry).await?;
        }
        
        Ok(())
    }
    
    /// Encrypt a file with the current configuration
    pub async fn encrypt_file<P: AsRef<Path>>(&self, path: P, password: &str) -> CryptoResult<PathBuf> {
        let path = path.as_ref();
        let config = self.config.read().await;
        
        // Generate output path
        let output_path = path.with_extension(
            format!("{}.{}", 
                path.extension()
                    .and_then(|ext| ext.to_str())
                    .unwrap_or(""), 
                config.file_ops.encrypted_extension
            )
        );
        
        // Read input file
        let input_data = tokio::fs::read(path).await?;
        
        // Encrypt the data
        let encrypted = self.engine.encrypt_data(&input_data, password)?;
        
        // Write encrypted data to output file
        let encrypted_bytes = bincode::serialize(&encrypted)
            .map_err(|e| CargoCryptError::Serialization {
                message: format!("Failed to serialize encrypted data: {}", e),
                source: Box::new(e),
            })?;
        
        tokio::fs::write(&output_path, encrypted_bytes).await?;
        
        // Handle backup if configured
        if config.file_ops.backup_originals {
            let backup_path = path.with_extension(
                format!("{}.backup", 
                    path.extension()
                        .and_then(|ext| ext.to_str())
                        .unwrap_or("")
                )
            );
            tokio::fs::copy(path, backup_path).await?;
        }
        
        Ok(output_path)
    }
    
    /// Decrypt a file with the current configuration
    pub async fn decrypt_file<P: AsRef<Path>>(&self, path: P, password: &str) -> CryptoResult<PathBuf> {
        let path = path.as_ref();
        let config = self.config.read().await;
        
        // Generate output path (remove .enc extension)
        let output_path = if path.extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| ext == config.file_ops.encrypted_extension)
            .unwrap_or(false) 
        {
            path.with_extension("")
        } else {
            return Err(CargoCryptError::Config {
                message: format!("File '{}' doesn't appear to be encrypted", path.display()),
                suggestion: Some("Encrypted files should have the .enc extension".to_string()),
            });
        };
        
        // Read encrypted file
        let encrypted_data = tokio::fs::read(path).await?;
        
        // Deserialize encrypted data
        let encrypted: EncryptedSecret = bincode::deserialize(&encrypted_data)
            .map_err(|e| CargoCryptError::Serialization {
                message: format!("Failed to deserialize encrypted data: {}", e),
                source: Box::new(e),
            })?;
        
        // Decrypt the data
        let decrypted_data = self.engine.decrypt_data(&encrypted, password)?;
        
        // Write decrypted data to output file
        tokio::fs::write(&output_path, decrypted_data).await?;
        
        Ok(output_path)
    }
    
    /// Get the current configuration
    pub async fn config(&self) -> CryptoConfig {
        self.config.read().await.clone()
    }
    
    /// Update the configuration
    pub async fn update_config<F>(&self, updater: F) -> CryptoResult<()>
    where
        F: FnOnce(&mut CryptoConfig),
    {
        let mut config = self.config.write().await;
        updater(&mut *config);
        Ok(())
    }
    
    /// Get the project root directory
    pub fn project_root(&self) -> &Path {
        &self.project_root
    }
    
    /// Get a reference to the secret store
    pub fn secret_store(&self) -> &dyn SecretStore {
        self.secret_store.as_ref()
    }
    
    /// Get the crypto engine
    pub fn engine(&self) -> &CryptoEngine {
        &self.engine
    }
    
    /// Get the crypto engine
    pub fn crypto_engine(&self) -> &CryptoEngine {
        &self.engine
    }
}

/// Builder pattern for CargoCrypt configuration
pub struct CargoCryptBuilder {
    config: CryptoConfig,
    project_root: Option<PathBuf>,
    secret_store: Option<Arc<dyn SecretStore>>,
}

impl CargoCryptBuilder {
    /// Create a new builder with default configuration
    pub fn new() -> Self {
        Self {
            config: CryptoConfig::default(),
            project_root: None,
            secret_store: None,
        }
    }
    
    /// Set the performance profile
    pub fn performance_profile(mut self, profile: PerformanceProfile) -> Self {
        self.config.performance_profile = profile;
        self
    }
    
    /// Set the project root directory
    pub fn project_root<P: Into<PathBuf>>(mut self, root: P) -> Self {
        self.project_root = Some(root.into());
        self
    }
    
    /// Set a custom secret store
    pub fn secret_store(mut self, store: Arc<dyn SecretStore>) -> Self {
        self.secret_store = Some(store);
        self
    }
    
    /// Configure key derivation parameters
    pub fn key_params(mut self, params: KeyDerivationConfig) -> Self {
        self.config.key_params = params;
        self
    }
    
    /// Configure file operations
    pub fn file_ops(mut self, ops: FileOperationConfig) -> Self {
        self.config.file_ops = ops;
        self
    }
    
    /// Configure security settings
    pub fn security(mut self, security: SecurityConfig) -> Self {
        self.config.security = security;
        self
    }
    
    /// Configure performance settings
    pub fn performance(mut self, performance: PerformanceConfig) -> Self {
        self.config.performance = performance;
        self
    }
    
    /// Build the CargoCrypt instance
    pub async fn build(self) -> CryptoResult<CargoCrypt> {
        let project_root = self.project_root
            .map(Ok)
            .unwrap_or_else(crate::utils::find_project_root)?;
        
        let engine = Arc::new(CryptoEngine::with_performance_profile(self.config.performance_profile));
        let secret_store = self.secret_store
            .unwrap_or_else(|| Arc::new(InMemorySecretStore::new()));
        
        Ok(CargoCrypt {
            engine,
            config: Arc::new(RwLock::new(self.config)),
            project_root,
            secret_store,
        })
    }
}

impl Default for CargoCryptBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Implementation of useful trait methods
impl CryptoConfig {
    /// Get the list of supported performance profiles
    pub fn performance_profiles(&self) -> Vec<PerformanceProfile> {
        vec![
            PerformanceProfile::Fast,
            PerformanceProfile::Balanced,
            PerformanceProfile::Secure,
            PerformanceProfile::Paranoid,
        ]
    }
    
    /// Validate the configuration
    pub fn validate(&self) -> CryptoResult<()> {
        // Validate key derivation parameters
        if self.key_params.memory_cost < 1024 {
            return Err(CargoCryptError::Config {
                message: "Memory cost too low (minimum 1024 KiB)".to_string(),
                suggestion: Some("Increase memory_cost to at least 1024 for security".to_string()),
            });
        }
        
        if self.key_params.time_cost < 1 {
            return Err(CargoCryptError::Config {
                message: "Time cost too low (minimum 1)".to_string(),
                suggestion: Some("Increase time_cost to at least 1".to_string()),
            });
        }
        
        if self.key_params.parallelism < 1 {
            return Err(CargoCryptError::Config {
                message: "Parallelism too low (minimum 1)".to_string(),
                suggestion: Some("Increase parallelism to at least 1".to_string()),
            });
        }
        
        // Validate file operations
        if self.file_ops.buffer_size < 1024 {
            return Err(CargoCryptError::Config {
                message: "Buffer size too small (minimum 1024 bytes)".to_string(),
                suggestion: Some("Increase buffer_size to at least 1024".to_string()),
            });
        }
        
        // Validate security settings
        if self.security.max_password_attempts < 1 {
            return Err(CargoCryptError::Config {
                message: "Max password attempts too low (minimum 1)".to_string(),
                suggestion: Some("Increase max_password_attempts to at least 1".to_string()),
            });
        }
        
        // Validate performance settings
        if self.performance.max_concurrent_ops < 1 {
            return Err(CargoCryptError::Config {
                message: "Max concurrent operations too low (minimum 1)".to_string(),
                suggestion: Some("Increase max_concurrent_ops to at least 1".to_string()),
            });
        }
        
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_default_config() {
        let config = CryptoConfig::default();
        assert_eq!(config.performance_profile, PerformanceProfile::Balanced);
        assert_eq!(config.key_params.memory_cost, 65536);
        assert_eq!(config.key_params.time_cost, 3);
        assert_eq!(config.key_params.parallelism, 4);
        assert_eq!(config.file_ops.encrypted_extension, "enc");
        assert!(config.security.fail_secure);
        assert!(config.performance.async_operations);
    }
    
    #[test]
    fn test_config_validation() {
        let mut config = CryptoConfig::default();
        assert!(config.validate().is_ok());
        
        config.key_params.memory_cost = 512; // Too low
        assert!(config.validate().is_err());
        
        config.key_params.memory_cost = 65536; // Reset
        config.security.max_password_attempts = 0; // Too low
        assert!(config.validate().is_err());
    }
    
    #[tokio::test]
    async fn test_secret_store() {
        let store = InMemorySecretStore::new();
        let secret = SecretBytes::from_str("test-secret");
        
        // Store and retrieve
        store.store_secret("test-key", secret.clone()).unwrap();
        let retrieved = store.get_secret("test-key").unwrap().unwrap();
        assert_eq!(retrieved.expose_secret(), secret.expose_secret());
        
        // Check existence
        assert!(store.contains_secret("test-key"));
        assert!(!store.contains_secret("non-existent"));
        
        // Remove
        assert!(store.remove_secret("test-key").unwrap());
        assert!(!store.contains_secret("test-key"));
    }
    
    #[test]
    fn test_secret_bytes_zeroization() {
        let mut secret = SecretBytes::from_str("sensitive-data");
        assert!(!secret.is_empty());
        assert_eq!(secret.len(), 14);
        
        // Zeroize should be called automatically on drop
        drop(secret);
        // Note: We can't test the actual zeroization since the data is dropped
        // but the Zeroize trait ensures it happens
    }
    
    #[test]
    fn test_builder_pattern() {
        let builder = CargoCryptBuilder::new()
            .performance_profile(PerformanceProfile::Secure)
            .project_root("/tmp/test");
        
        // The builder should be configurable
        assert_eq!(builder.config.performance_profile, PerformanceProfile::Secure);
    }
}