naru-config 0.7.0

A security-first configuration manager with encryption and audit logging
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
/// Deep Security Testing - Advanced Attack Vectors
/// Comprehensive security analysis untuk mencari bug & vulnerabilities

#[cfg(test)]
mod deep_security_tests {
    use std::fs;
    use std::thread;
    use std::time::{Duration, Instant};
    use tempfile::TempDir;

    // ========================================================================
    // CRYPTOGRAPHIC IMPLEMENTATION ANALYSIS
    // ========================================================================

    #[test]
    fn test_crypto_key_zeroization() {
        println!("\n🔍 [CRYPTO] Testing key material in memory...");

        let key = [0x42u8; 32];
        let data = "sensitive_data";

        let encrypted = crate::core::crypto::encrypt_data(data, &key).unwrap();

        // Test: Apakah key masih bisa digunakan setelah operasi?
        let decrypted = crate::core::crypto::decrypt_data(&encrypted, &key).unwrap();
        assert_eq!(decrypted, data);

        // ISSUE: Rust tidak automatically zeroize key dari memory
        // Key masih ada di stack sampai function return
        println!("  âš ī¸  WARNING: Keys not zeroized from memory after use");
        println!("  💡 RECOMMENDATION: Use zeroize crate untuk clear sensitive data\n");
    }

    #[test]
    fn test_crypto_timing_attack() {
        println!("🔍 [CRYPTO] Testing for timing attacks...");

        let key = [0x42u8; 32];
        let correct_data = "correct_password_123";

        let encrypted = crate::core::crypto::encrypt_data(correct_data, &key).unwrap();

        // Test dengan ciphertext yang dimodifikasi
        let tampered = hex::decode(&encrypted).unwrap();

        // Modifikasi 1 byte di posisi berbeda
        let mut timings = Vec::new();
        for pos in 0..tampered.len().min(20) {
            let mut test_bytes = tampered.clone();
            test_bytes[pos] ^= 0xFF;
            let test_cipher = hex::encode(&test_bytes);

            let start = Instant::now();
            let _ = crate::core::crypto::decrypt_data(&test_cipher, &key);
            let elapsed = start.elapsed();

            timings.push((pos, elapsed));
            println!("  Position {}: {:?}", pos, elapsed);
        }

        // Check apakah ada timing variation yang signifikan
        let max_time = timings.iter().map(|(_, t)| t).max().unwrap();
        let min_time = timings.iter().map(|(_, t)| t).min().unwrap();
        let variance = *max_time - *min_time;

        if variance.as_micros() > 100 {
            println!("  âš ī¸  WARNING: Timing variance detected: {:?}", variance);
            println!("  💡 Possible timing side-channel\n");
        } else {
            println!("  ✅ No significant timing variance detected\n");
        }
    }

    #[test]
    fn test_crypto_weak_key_detection() {
        println!("🔍 [CRYPTO] Testing weak key handling...");

        // Test dengan key yang semua byte-nya sama
        let weak_keys = vec![
            [0x00u8; 32], // All zeros
            [0xFFu8; 32], // All ones
            [0x42u8; 32], // Repeating pattern
        ];

        for (i, key) in weak_keys.iter().enumerate() {
            let encrypted = crate::core::crypto::encrypt_data("test", key).unwrap();
            let decrypted = crate::core::crypto::decrypt_data(&encrypted, key).unwrap();

            assert_eq!(decrypted, "test");
            println!(
                "  Weak key {} (all 0x{:02X}): Encryption works",
                i + 1,
                key[0]
            );
        }

        println!("  âš ī¸  WARNING: No weak key detection implemented");
        println!("  💡 RECOMMENDATION: Add key strength validation\n");
    }

    #[test]
    fn test_crypto_empty_data() {
        println!("🔍 [CRYPTO] Testing empty data encryption...");

        let key = [0x42u8; 32];

        // Encrypt empty string
        let encrypted = crate::core::crypto::encrypt_data("", &key).unwrap();
        let decrypted = crate::core::crypto::decrypt_data(&encrypted, &key).unwrap();

        assert_eq!(decrypted, "");
        println!("  ✅ Empty string encryption works");

        // Encrypt very large data
        let large_data = "A".repeat(10 * 1024 * 1024); // 10MB
        let start = Instant::now();
        let encrypted = crate::core::crypto::encrypt_data(&large_data, &key).unwrap();
        let encrypt_time = start.elapsed();

        let start = Instant::now();
        let decrypted = crate::core::crypto::decrypt_data(&encrypted, &key).unwrap();
        let decrypt_time = start.elapsed();

        assert_eq!(decrypted, large_data);
        println!(
            "  ✅ 10MB data: encrypt={:?}, decrypt={:?}",
            encrypt_time, decrypt_time
        );
        println!();
    }

    // ========================================================================
    // RACE CONDITION & CONCURRENCY TESTING
    // ========================================================================

    #[test]
    fn test_race_condition_file_write_old_api() {
        println!("🔍 [RACE] Testing OLD API (demonstrates race condition)...");

        let temp_dir = TempDir::new().unwrap();
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&temp_dir).unwrap();

        unsafe { std::env::set_var("NARU_ENCRYPTION_KEY", "test_key_for_race") };

        if let Err(e) = crate::core::persistence::init_project() {
            println!("  Init failed: {:?}\n", e);
            let _ = std::env::set_current_dir(&original_dir);
            unsafe { std::env::remove_var("NARU_ENCRYPTION_KEY") };
            return;
        }

        let mut handles = vec![];

        for i in 0..10 {
            let handle = thread::spawn(move || {
                let key = format!("KEY_{}", i);
                let value = format!("VALUE_{}", i);

                let mut config: crate::core::models::ConfigFile =
                    match crate::core::persistence::load_json(crate::core::constants::CONFIG_FILE) {
                        Ok(c) => c,
                        Err(_) => return false,
                    };

                thread::sleep(Duration::from_millis(10));

                if let Some(env_config) = config.environments.get_mut("development") {
                    env_config.entries.insert(
                        key,
                        crate::core::models::ConfigValueEntry::new(&value, "string", false),
                    );
                }

                crate::core::persistence::save_json(crate::core::constants::CONFIG_FILE, &config)
                    .is_ok()
            });
            handles.push(handle);
        }

        let _: Vec<bool> = handles.into_iter().map(|h| h.join().unwrap()).collect();

        let config: crate::core::models::ConfigFile =
            match crate::core::persistence::load_json(crate::core::constants::CONFIG_FILE) {
                Ok(c) => c,
                Err(_) => {
                    println!("  Failed to load config after race test\n");
                    std::env::set_current_dir(&original_dir).unwrap();
                    unsafe { std::env::remove_var("NARU_ENCRYPTION_KEY") };
                    return;
                }
            };

        let entry_count = config
            .environments
            .get("development")
            .map(|e| e.entries.len())
            .unwrap_or(0);

        println!(
            "  OLD API - Final entry count: {} (expected 10, shows data loss)",
            entry_count
        );
        println!("  âš ī¸  Race condition causes data loss with old API\n");

        let _ = std::env::set_current_dir(&original_dir);
        unsafe { std::env::remove_var("NARU_ENCRYPTION_KEY") };
    }

    #[test]
    fn test_race_condition_file_write_new_api() {
        println!("🔍 [RACE] Testing NEW atomic API (should prevent race condition)...");

        let temp_dir = TempDir::new().unwrap();
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&temp_dir).unwrap();

        unsafe { std::env::set_var("NARU_ENCRYPTION_KEY", "test_key_for_race_new") };

        if let Err(e) = crate::core::persistence::init_project() {
            println!("  Init failed: {:?}\n", e);
            let _ = std::env::set_current_dir(&original_dir);
            unsafe { std::env::remove_var("NARU_ENCRYPTION_KEY") };
            return;
        }

        let mut handles = vec![];

        for i in 0..10 {
            let handle = thread::spawn(move || {
                let key = format!("KEY_{}", i);

                crate::core::persistence::atomic_update_config(|config| {
                    if let Some(env_config) = config.environments.get_mut("development") {
                        env_config.entries.insert(
                            key,
                            crate::core::models::ConfigValueEntry::new("value", "string", false),
                        );
                    }
                    Ok(())
                })
                .is_ok()
            });
            handles.push(handle);
        }

        let results: Vec<bool> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        let success_count = results.iter().filter(|&&r| r).count();

        let entry_count = crate::core::persistence::atomic_read_config(|config| {
            config
                .environments
                .get("development")
                .map(|e| e.entries.len())
        })
        .ok()
        .flatten()
        .unwrap_or(0);

        println!(
            "  NEW API - Concurrent writes: {}/10 succeeded",
            success_count
        );
        println!(
            "  NEW API - Final entry count: {} (expected 10)",
            entry_count
        );

        if entry_count == 10 {
            println!("  ✅ Atomic API prevents race condition!\n");
        } else {
            println!("  âš ī¸  Some data loss still possible\n");
        }

        let _ = std::env::set_current_dir(&original_dir);
        unsafe { std::env::remove_var("NARU_ENCRYPTION_KEY") };
    }

    #[test]
    fn test_race_condition_lock_timeout() {
        println!("🔍 [RACE] Testing file lock timeout behavior...");

        let temp_dir = TempDir::new().unwrap();
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&temp_dir).unwrap();

        crate::core::persistence::init_project().unwrap();

        // Acquire lock in one thread
        let _lock_path = temp_dir
            .path()
            .join(crate::core::constants::NARU_DIR)
            .join("config.json.lock");

        let lock = crate::core::locking::FileLock::acquire_exclusive(
            &temp_dir
                .path()
                .join(crate::core::constants::NARU_DIR)
                .join("config.json"),
        )
        .unwrap();

        println!("  Lock acquired: {:?}", lock.path().exists());

        // Try to acquire same lock in main thread (should block)
        let start = Instant::now();

        let lock_handle = thread::spawn(move || {
            thread::sleep(Duration::from_millis(100));
            drop(lock); // Release after 100ms
        });

        // This should succeed after first lock is released
        let _lock2 = crate::core::locking::FileLock::acquire_exclusive(
            &temp_dir
                .path()
                .join(crate::core::constants::NARU_DIR)
                .join("config.json"),
        )
        .unwrap();

        let elapsed = start.elapsed();
        println!("  Lock wait time: {:?}", elapsed);

        if elapsed.as_millis() > 50 {
            println!("  ✅ Lock properly blocks until released");
        }

        lock_handle.join().unwrap();
        let _ = std::env::set_current_dir(&original_dir);
        println!();
    }

    // ========================================================================
    // INFORMATION LEAK TESTING
    // ========================================================================

    #[test]
    fn test_error_message_information_leak() {
        println!("🔍 [INFOLEAK] Testing error messages for information disclosure...");

        // Test: Apakah error messagesæŗ„éœ˛ informasi sensitif?
        let result = crate::core::security::sanitize_file_path("../etc/passwd");
        if let Err(e) = result {
            println!("  Path traversal error: {}", e);
            // Check if error reveals internal structure
            assert!(!e.contains("/etc/"), "Error should not reveal system paths");
        }

        let result = crate::core::security::validate_environment_name("dev; rm -rf /");
        if let Err(e) = result {
            println!("  Injection error: {}", e);
            // Check if error reveals validation logic
            assert!(
                !e.contains("regex"),
                "Error should not reveal implementation"
            );
        }

        println!("  ✅ Error messages don't leak sensitive information\n");
    }

    #[test]
    fn test_memory_dump_sensitive_data() {
        println!("🔍 [INFOLEAK] Testing for sensitive data in memory...");

        let key = [0x42u8; 32];
        let secret = "SUPER_SECRET_PASSWORD_123!";

        let encrypted = crate::core::crypto::encrypt_data(secret, &key).unwrap();

        // After encryption, secret should only exist in encrypted form
        println!("  Plaintext length: {}", secret.len());
        println!("  Ciphertext length: {}", encrypted.len());
        println!("  âš ī¸  WARNING: Plaintext may remain in stack memory");
        println!("  💡 RECOMMENDATION: Use secure memory allocation\n");
    }

    #[test]
    fn test_audit_log_secret_masking() {
        println!("🔍 [INFOLEAK] Testing audit log secret masking...");

        let temp_dir = TempDir::new().unwrap();
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&temp_dir).unwrap();

        unsafe { std::env::set_var("NARU_ENCRYPTION_KEY", "test_key_for_audit_log") };

        if let Err(e) = crate::core::persistence::init_project() {
            println!("  Init failed: {:?}\n", e);
            let _ = std::env::set_current_dir(&original_dir);
            unsafe { std::env::remove_var("NARU_ENCRYPTION_KEY") };
            return;
        }

        // Add a secret value
        let _ = crate::core::persistence::atomic_update_config(|config| {
            if let Some(env_config) = config.environments.get_mut("development") {
                env_config.entries.insert(
                    "DB_PASSWORD".to_string(),
                    crate::core::models::ConfigValueEntry::new("super_secret_123", "string", true),
                );
            }
            Ok(())
        });

        // Check audit log
        let audit_path = temp_dir
            .path()
            .join(crate::core::constants::NARU_DIR)
            .join("audit.log");

        if audit_path.exists() {
            let log_content = fs::read_to_string(&audit_path).unwrap();

            if log_content.contains("super_secret_123") {
                println!("  ❌ FAIL: Secret found in audit log!");
            } else {
                println!("  ✅ Secrets properly masked in audit log");
            }
        } else {
            println!("  â„šī¸  No audit log created for this operation");
        }

        let _ = std::env::set_current_dir(&original_dir);
        unsafe { std::env::remove_var("NARU_ENCRYPTION_KEY") };
        println!();
    }

    // ========================================================================
    // LOGIC BUGS IN VALIDATION
    // ========================================================================

    #[test]
    fn test_validation_bypass_null_byte() {
        println!("🔍 [LOGIC] Testing validation bypass with null bytes...");

        // Test if null byte in middle of string bypasses validation
        let test_cases = vec![
            "valid_key\0invalid",
            "dev\0production",
            "value\0../etc/passwd",
        ];

        for test in test_cases {
            let result = crate::core::security::validate_config_key(test);
            println!("  {:30} → {:?}", test, result);
        }
        println!();
    }

    #[test]
    fn test_validation_unicode_normalization() {
        println!("🔍 [LOGIC] Testing Unicode normalization attacks...");

        // Different Unicode representations of same character
        let test_cases = vec![
            ("cafÊ", "composed"),           // e + ˁ = Ê (composed)
            ("cafe\u{0301}", "decomposed"), // e + combining accent = Ê (decomposed)
        ];

        for (input, desc) in test_cases {
            let result = crate::core::security::validate_environment_name(input);
            println!("  {} ({}): {:?}", desc, input, result);
        }

        println!("  âš ī¸  Check for Unicode normalization consistency\n");
    }

    #[test]
    fn test_validation_boundary_conditions() {
        println!("🔍 [LOGIC] Testing boundary conditions...");

        use crate::core::models::{FieldDefinition, ValidationRules};
        use crate::core::validation::validate_value;

        // Test exact boundary values
        let field = FieldDefinition {
            key: "test".to_string(),
            r#type: "integer".to_string(),
            description: None,
            validation: Some(ValidationRules {
                min_length: None,
                max_length: None,
                min_value: Some(0),
                max_value: Some(100),
                pattern: None,
            }),
            is_secret: false,
        };

        let test_values = vec![
            ("-1", false),       // Below min
            ("0", true),         // Exact min
            ("50", true),        // Middle
            ("100", true),       // Exact max
            ("101", false),      // Above max
            ("i64::MAX", false), // Overflow attempt
        ];

        for (value, should_pass) in test_values {
            let actual_value = match value {
                "i64::MAX" => i64::MAX.to_string(),
                v => v.to_string(),
            };
            let result = validate_value(&actual_value, &field);
            let passed = result.is_ok();
            let status = if passed == should_pass { "✅" } else { "❌" };
            println!(
                "  {} {:15} → {}",
                status,
                value,
                if passed { "PASS" } else { "FAIL" }
            );
        }
        println!();
    }

    // ========================================================================
    // DOS & RESOURCE EXHAUSTION
    // ========================================================================

    #[test]
    fn test_dos_regex_catastrophic_backtracking() {
        println!("🔍 [DOS] Testing regex catastrophic backtracking...");

        use crate::core::models::{FieldDefinition, ValidationRules};
        use crate::core::validation::validate_value;

        // Pattern prone to catastrophic backtracking
        let vulnerable_patterns = vec![r"^(a+)+$", r"^(.*)(.*)+$", r"^(([a-z])+.)+$"];

        for pattern in vulnerable_patterns {
            let field = FieldDefinition {
                key: "test".to_string(),
                r#type: "string".to_string(),
                description: None,
                validation: Some(ValidationRules {
                    min_length: None,
                    max_length: None,
                    min_value: None,
                    max_value: None,
                    pattern: Some(pattern.to_string()),
                }),
                is_secret: false,
            };

            // Input designed to cause backtracking
            let input = "a".repeat(25) + "b";

            let start = Instant::now();
            let _ = validate_value(&input, &field);
            let elapsed = start.elapsed();

            println!("  Pattern {:20} → {:?}", pattern, elapsed);

            if elapsed.as_millis() > 100 {
                println!("    âš ī¸  SLOW: Potential ReDoS vulnerability");
            }
        }
        println!();
    }

    #[test]
    fn test_dos_memory_exhaustion() {
        println!("🔍 [DOS] Testing memory exhaustion attacks...");

        let key = [0x42u8; 32];

        // Try to encrypt increasingly large data
        let sizes = vec![1, 10, 50, 100]; // MB

        for size_mb in sizes {
            let data = "A".repeat(size_mb * 1024 * 1024);

            let start = Instant::now();
            let result = crate::core::crypto::encrypt_data(&data, &key);
            let elapsed = start.elapsed();

            match result {
                Ok(_) => println!("  {}MB: encrypt={:?}", size_mb, elapsed),
                Err(e) => {
                    println!("  {}MB: FAILED - {}", size_mb, e);
                    break;
                }
            }
        }

        println!("  â„šī¸  Monitor memory usage during large operations\n");
    }

    #[test]
    fn test_dos_deeply_nested_json() {
        println!("🔍 [DOS] Testing deeply nested JSON parsing...");

        // Create deeply nested JSON
        let mut json = String::from("{\"a\":");
        for _ in 0..100 {
            json.push_str("{\"a\":");
        }
        json.push_str("1");
        for _ in 0..100 {
            json.push('}');
        }
        json.push('}');

        let start = Instant::now();
        let result: Result<serde_json::Value, _> = serde_json::from_str(&json);
        let elapsed = start.elapsed();

        println!(
            "  100-level nesting: {:?}, result: {:?}",
            elapsed,
            result.is_ok()
        );
        println!("  â„šī¸  Check for stack overflow on very deep nesting\n");
    }

    // ========================================================================
    // SUMMARY
    // ========================================================================

    #[test]
    fn run_deep_security_analysis() {
        println!("\n╔══════════════════════════════════════════════════════════╗");
        println!("║         DEEP SECURITY ANALYSIS                           ║");
        println!("║         Advanced Attack Vector Testing                   ║");
        println!("╚══════════════════════════════════════════════════════════╝\n");

        // Cryptographic analysis
        test_crypto_key_zeroization();
        test_crypto_timing_attack();
        test_crypto_weak_key_detection();
        test_crypto_empty_data();

        // Information leaks
        test_error_message_information_leak();
        test_memory_dump_sensitive_data();
        test_audit_log_secret_masking();

        // Logic bugs
        test_validation_bypass_null_byte();
        test_validation_unicode_normalization();
        test_validation_boundary_conditions();

        // DoS testing
        test_dos_regex_catastrophic_backtracking();
        test_dos_deeply_nested_json();

        println!("╔══════════════════════════════════════════════════════════╗");
        println!("║         DEEP SECURITY ANALYSIS COMPLETE                  ║");
        println!("╚══════════════════════════════════════════════════════════╝\n");
    }
}