stand 0.2.2

A CLI tool for explicit environment variable management
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Encryption management commands.

use std::fs;
use std::io::Write;
use std::path::Path;

use colored::Colorize;
use toml_edit::{DocumentMut, Item, Value};

use crate::crypto::{
    generate_key_pair, load_private_key_for_decryption, CryptoError, ENCRYPTED_PREFIX,
};

const KEYS_FILE: &str = ".stand.keys";
const CONFIG_FILE: &str = ".stand.toml";

/// Enable encryption for the project.
///
/// Generates a new key pair and adds the public key to .stand.toml.
pub fn enable_encryption(project_dir: &Path) -> Result<(), EncryptionCommandError> {
    let config_path = project_dir.join(CONFIG_FILE);
    let keys_path = project_dir.join(KEYS_FILE);

    // Check if config file exists
    if !config_path.exists() {
        return Err(EncryptionCommandError::ConfigNotFound);
    }

    // Parse config with toml_edit to preserve formatting
    let config_content = fs::read_to_string(&config_path)?;
    let mut doc: DocumentMut = config_content
        .parse()
        .map_err(|e| EncryptionCommandError::TomlParse(format!("{}", e)))?;

    // Check if encryption is already enabled
    if doc.get("encryption").is_some() {
        return Err(EncryptionCommandError::AlreadyEnabled);
    }

    // Generate key pair
    let key_pair = generate_key_pair();

    // Save private key FIRST — this is the hard-to-recover artifact.
    // If this fails, no state has changed yet (config is untouched).
    crate::crypto::keys::save_private_key(&keys_path, &key_pair.private_key)
        .map_err(EncryptionCommandError::Crypto)?;

    // Add .stand.keys to .gitignore before writing config
    add_to_gitignore(project_dir, KEYS_FILE)?;

    // Add [encryption] section to config using toml_edit
    let mut encryption_table = toml_edit::Table::new();
    encryption_table.insert("public_key", toml_edit::value(&key_pair.public_key));
    doc.insert("encryption", Item::Table(encryption_table));

    // Write config LAST. If this fails, clean up the key file.
    if let Err(e) = fs::write(&config_path, doc.to_string()) {
        // Roll back: remove the key file we just created
        if let Err(cleanup_err) = fs::remove_file(&keys_path) {
            eprintln!(
                "Warning: Failed to clean up {} after configuration write error: {}",
                KEYS_FILE, cleanup_err
            );
            eprintln!(
                "Please manually remove {} to prevent security issues.",
                keys_path.display()
            );
        }
        return Err(e.into());
    }

    println!("{} Generated key pair", "".green());
    println!(
        "{} Added [encryption] section to {}",
        "".green(),
        CONFIG_FILE
    );
    println!("{} Created {}", "".green(), KEYS_FILE);

    Ok(())
}

/// Disable encryption for the project.
///
/// Prompts for user confirmation, then decrypts all encrypted values
/// and removes encryption configuration. If the user declines, returns Ok(())
/// without making changes.
pub fn disable_encryption(project_dir: &Path) -> Result<(), EncryptionCommandError> {
    let config_path = project_dir.join(CONFIG_FILE);

    // Check if config file exists
    if !config_path.exists() {
        return Err(EncryptionCommandError::ConfigNotFound);
    }

    // Parse config with toml_edit to check encryption status
    let config_content = fs::read_to_string(&config_path)?;
    let doc: DocumentMut = config_content
        .parse()
        .map_err(|e| EncryptionCommandError::TomlParse(format!("{}", e)))?;

    // Check if encryption is enabled
    if doc.get("encryption").is_none() {
        return Err(EncryptionCommandError::NotEnabled);
    }

    // Prompt for confirmation
    println!(
        "{} This will decrypt all encrypted values and remove encryption.",
        "".yellow()
    );
    print!("Continue? [y/N]: ");
    std::io::stdout().flush()?;

    let mut input = String::new();
    std::io::stdin().read_line(&mut input)?;
    if !input.trim().eq_ignore_ascii_case("y") {
        println!("Aborted.");
        return Ok(());
    }

    // Perform the actual disable operation
    let result = disable_encryption_internal(project_dir)?;

    if result.decrypted_count > 0 {
        println!(
            "{} Decrypted {} value(s)",
            "".green(),
            result.decrypted_count
        );
    }
    println!("{} Removed [encryption] section", "".green());
    println!("{} Encryption disabled", "".green());

    Ok(())
}

/// Result of the disable_encryption_internal operation.
#[derive(Debug, Default)]
pub struct DisableEncryptionResult {
    /// Number of values successfully decrypted.
    pub decrypted_count: usize,
}

/// Internal function to disable encryption without user confirmation.
///
/// This function is separated to allow testing without interactive prompts.
/// If no encrypted values exist, the private key is not required.
pub fn disable_encryption_internal(
    project_dir: &Path,
) -> Result<DisableEncryptionResult, EncryptionCommandError> {
    let config_path = project_dir.join(CONFIG_FILE);
    let keys_path = project_dir.join(KEYS_FILE);

    // Parse config with toml_edit
    let config_content = fs::read_to_string(&config_path)?;
    let mut doc: DocumentMut = config_content
        .parse()
        .map_err(|e| EncryptionCommandError::TomlParse(format!("{}", e)))?;

    // Check if encryption is enabled
    if doc.get("encryption").is_none() {
        return Err(EncryptionCommandError::NotEnabled);
    }

    // First, check if there are any encrypted values (read-only scan)
    let has_encrypted_values = has_encrypted_values_in_doc(&doc);

    let mut result = DisableEncryptionResult::default();

    // Only load private key if there are encrypted values to decrypt
    if has_encrypted_values {
        let private_key = load_private_key_for_decryption(project_dir)?;
        let identity = crate::crypto::keys::parse_private_key(&private_key)
            .map_err(EncryptionCommandError::Crypto)?;

        // Decrypt all encrypted values in environments section
        if let Some(environments) = doc.get_mut("environments") {
            if let Some(env_table) = environments.as_table_mut() {
                for (_env_name, env_config) in env_table.iter_mut() {
                    if let Some(env_tbl) = env_config.as_table_mut() {
                        for (key, value) in env_tbl.iter_mut() {
                            if let Some(val_str) = value.as_str() {
                                if val_str.starts_with(ENCRYPTED_PREFIX) {
                                    let decrypted = crate::crypto::decrypt_value(
                                        val_str, &identity,
                                    )
                                    .map_err(|e| EncryptionCommandError::DecryptionFailed {
                                        variable: key.to_string(),
                                        reason: e.to_string(),
                                    })?;
                                    *value = Item::Value(Value::from(decrypted));
                                    result.decrypted_count += 1;
                                }
                            }
                        }
                    }
                }
            }
        }

        // Also decrypt [common] section
        if let Some(common) = doc.get_mut("common") {
            if let Some(common_table) = common.as_table_mut() {
                for (key, value) in common_table.iter_mut() {
                    if let Some(val_str) = value.as_str() {
                        if val_str.starts_with(ENCRYPTED_PREFIX) {
                            let decrypted = crate::crypto::decrypt_value(val_str, &identity)
                                .map_err(|e| EncryptionCommandError::DecryptionFailed {
                                    variable: key.to_string(),
                                    reason: e.to_string(),
                                })?;
                            *value = Item::Value(Value::from(decrypted));
                            result.decrypted_count += 1;
                        }
                    }
                }
            }
        }
    }

    // Remove [encryption] section using toml_edit
    doc.remove("encryption");

    // Write back preserving formatting
    fs::write(&config_path, doc.to_string())?;

    // Remove .stand.keys file if it exists
    if keys_path.exists() {
        fs::remove_file(&keys_path)?;
    }

    Ok(result)
}

/// Check if the document contains any encrypted values.
fn has_encrypted_values_in_doc(doc: &DocumentMut) -> bool {
    // Check environments section
    if let Some(environments) = doc.get("environments") {
        if let Some(env_table) = environments.as_table() {
            for (_env_name, env_config) in env_table.iter() {
                if let Some(env_tbl) = env_config.as_table() {
                    for (_key, value) in env_tbl.iter() {
                        if let Some(val_str) = value.as_str() {
                            if val_str.starts_with(ENCRYPTED_PREFIX) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
    }

    // Check common section
    if let Some(common) = doc.get("common") {
        if let Some(common_table) = common.as_table() {
            for (_key, value) in common_table.iter() {
                if let Some(val_str) = value.as_str() {
                    if val_str.starts_with(ENCRYPTED_PREFIX) {
                        return true;
                    }
                }
            }
        }
    }

    false
}

/// Adds a file to .gitignore if not already present.
fn add_to_gitignore(project_dir: &Path, filename: &str) -> Result<(), std::io::Error> {
    let gitignore_path = project_dir.join(".gitignore");

    if gitignore_path.exists() {
        let content = fs::read_to_string(&gitignore_path)?;
        if content.lines().any(|line| line.trim() == filename) {
            return Ok(()); // Already in .gitignore
        }
        // Append to existing .gitignore
        let mut file = fs::OpenOptions::new().append(true).open(&gitignore_path)?;
        std::io::Write::write_all(&mut file, format!("\n{}\n", filename).as_bytes())?;
    } else {
        // Create new .gitignore
        fs::write(&gitignore_path, format!("{}\n", filename))?;
    }

    println!("{} Added {} to .gitignore", "".green(), filename);
    Ok(())
}

/// Error type for encryption commands.
#[derive(Debug, thiserror::Error)]
pub enum EncryptionCommandError {
    #[error("Configuration file not found. Run 'stand init' first.")]
    ConfigNotFound,

    #[error("Encryption is already enabled for this project")]
    AlreadyEnabled,

    #[error("Encryption is not enabled for this project")]
    NotEnabled,

    #[error("Cryptographic error: {0}")]
    Crypto(#[from] CryptoError),

    #[error("TOML parsing error: {0}")]
    TomlParse(String),

    #[error("Failed to decrypt variable '{variable}': {reason}. All values must be decryptable to disable encryption.")]
    DecryptionFailed { variable: String, reason: String },

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

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

    #[test]
    fn test_enable_encryption_no_config() {
        let dir = tempdir().unwrap();
        let result = enable_encryption(dir.path());
        assert!(matches!(
            result,
            Err(EncryptionCommandError::ConfigNotFound)
        ));
    }

    #[test]
    fn test_enable_encryption_success() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join(".stand.toml");

        // Create minimal config
        fs::write(
            &config_path,
            r#"version = "1.0"

[environments.dev]
description = "Development"
"#,
        )
        .unwrap();

        let result = enable_encryption(dir.path());
        assert!(result.is_ok());

        // Check that [encryption] section was added
        let updated_config = fs::read_to_string(&config_path).unwrap();
        assert!(updated_config.contains("[encryption]"));
        assert!(updated_config.contains("public_key = \"age1"));

        // Check that .stand.keys was created
        let keys_path = dir.path().join(".stand.keys");
        assert!(keys_path.exists());
    }

    #[test]
    fn test_enable_encryption_already_enabled() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join(".stand.toml");

        // Create config with encryption already enabled
        fs::write(
            &config_path,
            r#"version = "1.0"

[encryption]
public_key = "age1test"

[environments.dev]
description = "Development"
"#,
        )
        .unwrap();

        let result = enable_encryption(dir.path());
        assert!(matches!(
            result,
            Err(EncryptionCommandError::AlreadyEnabled)
        ));
    }

    // === Issue 2: Tests for disable_encryption_internal ===

    #[test]
    fn test_disable_encryption_internal_decrypts_all_values() {
        let dir = tempdir().unwrap();

        // Generate keys
        let key_pair = crate::crypto::keys::generate_key_pair();
        let keys_path = dir.path().join(".stand.keys");
        crate::crypto::keys::save_private_key(&keys_path, &key_pair.private_key).unwrap();

        // Encrypt test values
        let recipient = key_pair.to_recipient().unwrap();
        let encrypted1 = crate::crypto::encrypt_value("secret1", &recipient).unwrap();
        let encrypted2 = crate::crypto::encrypt_value("secret2", &recipient).unwrap();

        // Create config with encrypted values
        let config_path = dir.path().join(".stand.toml");
        fs::write(
            &config_path,
            format!(
                r#"version = "1.0"

[encryption]
public_key = "{}"

[environments.dev]
description = "Development"
API_KEY = "{}"
DB_PASSWORD = "{}"
"#,
                key_pair.public_key, encrypted1, encrypted2
            ),
        )
        .unwrap();

        // Disable encryption
        let result = disable_encryption_internal(dir.path());
        assert!(result.is_ok());

        let result = result.unwrap();
        assert_eq!(result.decrypted_count, 2);

        // Verify the config was updated
        let updated_config = fs::read_to_string(&config_path).unwrap();
        assert!(!updated_config.contains("[encryption]"));
        assert!(!updated_config.contains("encrypted:"));
        assert!(updated_config.contains("API_KEY = \"secret1\""));
        assert!(updated_config.contains("DB_PASSWORD = \"secret2\""));

        // Verify .stand.keys was removed
        assert!(!keys_path.exists());
    }

    #[test]
    fn test_disable_encryption_internal_removes_encryption_section() {
        let dir = tempdir().unwrap();

        // Generate keys (no encrypted values, just testing section removal)
        let key_pair = crate::crypto::keys::generate_key_pair();
        let keys_path = dir.path().join(".stand.keys");
        crate::crypto::keys::save_private_key(&keys_path, &key_pair.private_key).unwrap();

        // Create config with encryption section but no encrypted values
        let config_path = dir.path().join(".stand.toml");
        fs::write(
            &config_path,
            format!(
                r#"version = "1.0"

[encryption]
public_key = "{}"

[environments.dev]
description = "Development"
PLAIN_VALUE = "not encrypted"
"#,
                key_pair.public_key
            ),
        )
        .unwrap();

        let result = disable_encryption_internal(dir.path());
        assert!(result.is_ok());

        let result = result.unwrap();
        assert_eq!(result.decrypted_count, 0);

        // Verify [encryption] section was removed
        let updated_config = fs::read_to_string(&config_path).unwrap();
        assert!(!updated_config.contains("[encryption]"));
        assert!(!updated_config.contains("public_key"));

        // Verify other content is preserved
        assert!(updated_config.contains("PLAIN_VALUE = \"not encrypted\""));
    }

    #[test]
    fn test_disable_encryption_internal_removes_keys_file() {
        let dir = tempdir().unwrap();

        // Generate keys
        let key_pair = crate::crypto::keys::generate_key_pair();
        let keys_path = dir.path().join(".stand.keys");
        crate::crypto::keys::save_private_key(&keys_path, &key_pair.private_key).unwrap();
        assert!(keys_path.exists());

        // Create config
        let config_path = dir.path().join(".stand.toml");
        fs::write(
            &config_path,
            format!(
                r#"version = "1.0"

[encryption]
public_key = "{}"

[environments.dev]
description = "Development"
"#,
                key_pair.public_key
            ),
        )
        .unwrap();

        let result = disable_encryption_internal(dir.path());
        assert!(result.is_ok());

        // Verify .stand.keys was deleted
        assert!(!keys_path.exists());
    }

    #[test]
    fn test_disable_encryption_internal_not_enabled() {
        let dir = tempdir().unwrap();

        // Create config WITHOUT encryption section
        let config_path = dir.path().join(".stand.toml");
        fs::write(
            &config_path,
            r#"version = "1.0"

[environments.dev]
description = "Development"
"#,
        )
        .unwrap();

        let result = disable_encryption_internal(dir.path());
        assert!(matches!(result, Err(EncryptionCommandError::NotEnabled)));
    }

    #[test]
    fn test_disable_encryption_internal_no_private_key() {
        let dir = tempdir().unwrap();

        // Create config with encryption enabled but NO .stand.keys file
        let config_path = dir.path().join(".stand.toml");
        fs::write(
            &config_path,
            r#"version = "1.0"

[encryption]
public_key = "age1test"

[environments.dev]
description = "Development"
SECRET = "encrypted:somedata"
"#,
        )
        .unwrap();

        // Note: No .stand.keys file created

        let result = disable_encryption_internal(dir.path());
        assert!(matches!(result, Err(EncryptionCommandError::Crypto(_))));
    }

    #[test]
    fn test_disable_encryption_internal_handles_common_section() {
        let dir = tempdir().unwrap();

        // Generate keys
        let key_pair = crate::crypto::keys::generate_key_pair();
        let keys_path = dir.path().join(".stand.keys");
        crate::crypto::keys::save_private_key(&keys_path, &key_pair.private_key).unwrap();

        // Encrypt test value
        let recipient = key_pair.to_recipient().unwrap();
        let encrypted = crate::crypto::encrypt_value("common-secret", &recipient).unwrap();

        // Create config with encrypted value in [common] section
        let config_path = dir.path().join(".stand.toml");
        fs::write(
            &config_path,
            format!(
                r#"version = "1.0"

[encryption]
public_key = "{}"

[common]
SHARED_SECRET = "{}"

[environments.dev]
description = "Development"
"#,
                key_pair.public_key, encrypted
            ),
        )
        .unwrap();

        let result = disable_encryption_internal(dir.path());
        assert!(result.is_ok());

        let result = result.unwrap();
        assert_eq!(result.decrypted_count, 1);

        // Verify the common section was updated
        let updated_config = fs::read_to_string(&config_path).unwrap();
        assert!(updated_config.contains("SHARED_SECRET = \"common-secret\""));
    }

    #[test]
    fn test_disable_encryption_internal_fails_on_malformed_value() {
        let dir = tempdir().unwrap();

        // Generate keys
        let key_pair = crate::crypto::keys::generate_key_pair();
        let keys_path = dir.path().join(".stand.keys");
        crate::crypto::keys::save_private_key(&keys_path, &key_pair.private_key).unwrap();

        // Create config with a malformed encrypted value (not valid ciphertext)
        let config_path = dir.path().join(".stand.toml");
        let original_content = format!(
            r#"version = "1.0"

[encryption]
public_key = "{}"

[environments.dev]
description = "Development"
MALFORMED_SECRET = "encrypted:this-is-not-valid-ciphertext"
"#,
            key_pair.public_key
        );
        fs::write(&config_path, &original_content).unwrap();

        // Attempt to disable encryption - should fail
        let result = disable_encryption_internal(dir.path());
        assert!(matches!(
            result,
            Err(EncryptionCommandError::DecryptionFailed { .. })
        ));

        // Verify the config file was NOT modified (still contains encryption section)
        let config_after = fs::read_to_string(&config_path).unwrap();
        assert_eq!(config_after, original_content);

        // Verify .stand.keys was NOT deleted
        assert!(keys_path.exists());
    }

    #[test]
    fn test_disable_encryption_internal_succeeds_without_key_when_no_encrypted_values() {
        let dir = tempdir().unwrap();

        // Create config with encryption enabled but NO encrypted values and NO .stand.keys
        let config_path = dir.path().join(".stand.toml");
        fs::write(
            &config_path,
            r#"version = "1.0"

[encryption]
public_key = "age1somekey"

[environments.dev]
description = "Development"
PLAIN_VALUE = "not-encrypted"
"#,
        )
        .unwrap();

        // Note: No .stand.keys file exists, but there are no encrypted values either

        let result = disable_encryption_internal(dir.path());
        assert!(result.is_ok());

        let result = result.unwrap();
        assert_eq!(result.decrypted_count, 0);

        // Verify [encryption] section was removed
        let updated_config = fs::read_to_string(&config_path).unwrap();
        assert!(!updated_config.contains("[encryption]"));
        assert!(updated_config.contains("PLAIN_VALUE = \"not-encrypted\""));
    }
}