purple-ssh 1.27.0

Manage SSH configs and launch connections from the terminal. TUI host manager with search, tags, tunnels, command snippets, password management (keychain, 1Password, Bitwarden, pass, Vault), cloud sync (AWS EC2, DigitalOcean, Vultr, Linode, Hetzner, UpCloud, Proxmox VE, Scaleway, GCP), self-update and round-trip fidelity for ~/.ssh/config.
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
use std::io;
use std::path::PathBuf;

use crate::fs_util;

/// A configured provider section from ~/.purple/providers.
#[derive(Debug, Clone)]
pub struct ProviderSection {
    pub provider: String,
    pub token: String,
    pub alias_prefix: String,
    pub user: String,
    pub identity_file: String,
    pub url: String,
    pub verify_tls: bool,
    pub auto_sync: bool,
    pub profile: String,
    pub regions: String,
    pub project: String,
}

/// Default for auto_sync: false for proxmox (N+1 API calls), true for all others.
fn default_auto_sync(provider: &str) -> bool {
    !matches!(provider, "proxmox")
}

/// Parsed provider configuration from ~/.purple/providers.
#[derive(Debug, Clone, Default)]
pub struct ProviderConfig {
    pub sections: Vec<ProviderSection>,
    /// Override path for save(). None uses the default ~/.purple/providers.
    /// Set to Some in tests to avoid writing to the real config.
    pub path_override: Option<PathBuf>,
}

fn config_path() -> Option<PathBuf> {
    dirs::home_dir().map(|h| h.join(".purple/providers"))
}

impl ProviderConfig {
    /// Load provider config from ~/.purple/providers.
    /// Returns empty config if file doesn't exist (normal first-use).
    /// Prints a warning to stderr on real IO errors (permissions, etc.).
    pub fn load() -> Self {
        let path = match config_path() {
            Some(p) => p,
            None => return Self::default(),
        };
        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Self::default(),
            Err(e) => {
                eprintln!("! Could not read {}: {}", path.display(), e);
                return Self::default();
            }
        };
        Self::parse(&content)
    }

    /// Parse INI-style provider config.
    fn parse(content: &str) -> Self {
        let mut sections = Vec::new();
        let mut current: Option<ProviderSection> = None;

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            if trimmed.starts_with('[') && trimmed.ends_with(']') {
                if let Some(section) = current.take() {
                    if !sections.iter().any(|s: &ProviderSection| s.provider == section.provider) {
                        sections.push(section);
                    }
                }
                let name = trimmed[1..trimmed.len() - 1].trim().to_string();
                if sections.iter().any(|s| s.provider == name) {
                    current = None;
                    continue;
                }
                let short_label = super::get_provider(&name)
                    .map(|p| p.short_label().to_string())
                    .unwrap_or_else(|| name.clone());
                let auto_sync_default = default_auto_sync(&name);
                current = Some(ProviderSection {
                    provider: name,
                    token: String::new(),
                    alias_prefix: short_label,
                    user: "root".to_string(),
                    identity_file: String::new(),
                    url: String::new(),
                    verify_tls: true,
                    auto_sync: auto_sync_default,
                    profile: String::new(),
                    regions: String::new(),
                    project: String::new(),
                });
            } else if let Some(ref mut section) = current {
                if let Some((key, value)) = trimmed.split_once('=') {
                    let key = key.trim();
                    let value = value.trim().to_string();
                    match key {
                        "token" => section.token = value,
                        "alias_prefix" => section.alias_prefix = value,
                        "user" => section.user = value,
                        "key" => section.identity_file = value,
                        "url" => section.url = value,
                        "verify_tls" => section.verify_tls = !matches!(
                            value.to_lowercase().as_str(), "false" | "0" | "no"
                        ),
                        "auto_sync" => section.auto_sync = !matches!(
                            value.to_lowercase().as_str(), "false" | "0" | "no"
                        ),
                        "profile" => section.profile = value,
                        "regions" => section.regions = value,
                        "project" => section.project = value,
                        _ => {}
                    }
                }
            }
        }
        if let Some(section) = current {
            if !sections.iter().any(|s| s.provider == section.provider) {
                sections.push(section);
            }
        }
        Self { sections, path_override: None }
    }

    /// Save provider config to ~/.purple/providers (atomic write, chmod 600).
    /// Respects path_override when set (used in tests).
    pub fn save(&self) -> io::Result<()> {
        let path = match &self.path_override {
            Some(p) => p.clone(),
            None => match config_path() {
                Some(p) => p,
                None => {
                    return Err(io::Error::new(
                        io::ErrorKind::NotFound,
                        "Could not determine home directory",
                    ))
                }
            },
        };

        let mut content = String::new();
        for (i, section) in self.sections.iter().enumerate() {
            if i > 0 {
                content.push('\n');
            }
            content.push_str(&format!("[{}]\n", section.provider));
            content.push_str(&format!("token={}\n", section.token));
            content.push_str(&format!("alias_prefix={}\n", section.alias_prefix));
            content.push_str(&format!("user={}\n", section.user));
            if !section.identity_file.is_empty() {
                content.push_str(&format!("key={}\n", section.identity_file));
            }
            if !section.url.is_empty() {
                content.push_str(&format!("url={}\n", section.url));
            }
            if !section.verify_tls {
                content.push_str("verify_tls=false\n");
            }
            if !section.profile.is_empty() {
                content.push_str(&format!("profile={}\n", section.profile));
            }
            if !section.regions.is_empty() {
                content.push_str(&format!("regions={}\n", section.regions));
            }
            if !section.project.is_empty() {
                content.push_str(&format!("project={}\n", section.project));
            }
            if section.auto_sync != default_auto_sync(&section.provider) {
                content.push_str(if section.auto_sync { "auto_sync=true\n" } else { "auto_sync=false\n" });
            }
        }

        fs_util::atomic_write(&path, content.as_bytes())
    }

    /// Get a configured provider section by name.
    pub fn section(&self, provider: &str) -> Option<&ProviderSection> {
        self.sections.iter().find(|s| s.provider == provider)
    }

    /// Add or replace a provider section.
    pub fn set_section(&mut self, section: ProviderSection) {
        if let Some(existing) = self.sections.iter_mut().find(|s| s.provider == section.provider) {
            *existing = section;
        } else {
            self.sections.push(section);
        }
    }

    /// Remove a provider section.
    pub fn remove_section(&mut self, provider: &str) {
        self.sections.retain(|s| s.provider != provider);
    }

    /// Get all configured provider sections.
    pub fn configured_providers(&self) -> &[ProviderSection] {
        &self.sections
    }
}

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

    #[test]
    fn test_parse_empty() {
        let config = ProviderConfig::parse("");
        assert!(config.sections.is_empty());
    }

    #[test]
    fn test_parse_single_section() {
        let content = "\
[digitalocean]
token=dop_v1_abc123
alias_prefix=do
user=root
key=~/.ssh/id_ed25519
";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        let s = &config.sections[0];
        assert_eq!(s.provider, "digitalocean");
        assert_eq!(s.token, "dop_v1_abc123");
        assert_eq!(s.alias_prefix, "do");
        assert_eq!(s.user, "root");
        assert_eq!(s.identity_file, "~/.ssh/id_ed25519");
    }

    #[test]
    fn test_parse_multiple_sections() {
        let content = "\
[digitalocean]
token=abc

[vultr]
token=xyz
user=deploy
";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 2);
        assert_eq!(config.sections[0].provider, "digitalocean");
        assert_eq!(config.sections[1].provider, "vultr");
        assert_eq!(config.sections[1].user, "deploy");
    }

    #[test]
    fn test_parse_comments_and_blanks() {
        let content = "\
# Provider config

[linode]
# API token
token=mytoken
";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].token, "mytoken");
    }

    #[test]
    fn test_set_section_add() {
        let mut config = ProviderConfig::default();
        config.set_section(ProviderSection {
            provider: "vultr".to_string(),
            token: "abc".to_string(),
            alias_prefix: "vultr".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: String::new(),
            verify_tls: true,
            auto_sync: true,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        });
        assert_eq!(config.sections.len(), 1);
    }

    #[test]
    fn test_set_section_replace() {
        let mut config = ProviderConfig::parse("[vultr]\ntoken=old\n");
        config.set_section(ProviderSection {
            provider: "vultr".to_string(),
            token: "new".to_string(),
            alias_prefix: "vultr".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: String::new(),
            verify_tls: true,
            auto_sync: true,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        });
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].token, "new");
    }

    #[test]
    fn test_remove_section() {
        let mut config = ProviderConfig::parse("[vultr]\ntoken=abc\n[linode]\ntoken=xyz\n");
        config.remove_section("vultr");
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].provider, "linode");
    }

    #[test]
    fn test_section_lookup() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\n");
        assert!(config.section("digitalocean").is_some());
        assert!(config.section("vultr").is_none());
    }

    #[test]
    fn test_parse_duplicate_sections_first_wins() {
        let content = "\
[digitalocean]
token=first

[digitalocean]
token=second
";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].token, "first");
    }

    #[test]
    fn test_parse_duplicate_sections_trailing() {
        let content = "\
[vultr]
token=abc

[linode]
token=xyz

[vultr]
token=dup
";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 2);
        assert_eq!(config.sections[0].provider, "vultr");
        assert_eq!(config.sections[0].token, "abc");
        assert_eq!(config.sections[1].provider, "linode");
    }

    #[test]
    fn test_defaults_applied() {
        let config = ProviderConfig::parse("[hetzner]\ntoken=abc\n");
        let s = &config.sections[0];
        assert_eq!(s.user, "root");
        assert_eq!(s.alias_prefix, "hetzner");
        assert!(s.identity_file.is_empty());
        assert!(s.url.is_empty());
        assert!(s.verify_tls);
        assert!(s.auto_sync);
    }

    #[test]
    fn test_parse_url_and_verify_tls() {
        let content = "\
[proxmox]
token=user@pam!purple=secret
url=https://pve.example.com:8006
verify_tls=false
";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        let s = &config.sections[0];
        assert_eq!(s.url, "https://pve.example.com:8006");
        assert!(!s.verify_tls);
    }

    #[test]
    fn test_url_and_verify_tls_round_trip() {
        let content = "\
[proxmox]
token=tok
alias_prefix=pve
user=root
url=https://pve.local:8006
verify_tls=false
";
        let config = ProviderConfig::parse(content);
        let s = &config.sections[0];
        assert_eq!(s.url, "https://pve.local:8006");
        assert!(!s.verify_tls);
    }

    #[test]
    fn test_verify_tls_default_true() {
        // verify_tls not present -> defaults to true
        let config = ProviderConfig::parse("[proxmox]\ntoken=abc\nurl=https://pve:8006\n");
        assert!(config.sections[0].verify_tls);
    }

    #[test]
    fn test_verify_tls_false_variants() {
        for value in &["false", "False", "FALSE", "0", "no", "No", "NO"] {
            let content = format!("[proxmox]\ntoken=abc\nurl=https://pve:8006\nverify_tls={}\n", value);
            let config = ProviderConfig::parse(&content);
            assert!(!config.sections[0].verify_tls, "verify_tls={} should be false", value);
        }
    }

    #[test]
    fn test_verify_tls_true_variants() {
        for value in &["true", "True", "1", "yes"] {
            let content = format!("[proxmox]\ntoken=abc\nurl=https://pve:8006\nverify_tls={}\n", value);
            let config = ProviderConfig::parse(&content);
            assert!(config.sections[0].verify_tls, "verify_tls={} should be true", value);
        }
    }

    #[test]
    fn test_non_proxmox_url_not_written() {
        // url and verify_tls=false must not appear for non-Proxmox providers in saved config
        let section = ProviderSection {
            provider: "digitalocean".to_string(),
            token: "tok".to_string(),
            alias_prefix: "do".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: String::new(),     // empty: not written
            verify_tls: true,       // default: not written
            auto_sync: true,        // default for non-proxmox: not written
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        };
        let mut config = ProviderConfig::default();
        config.set_section(section);
        // Parse it back: url and verify_tls should be at defaults
        let s = &config.sections[0];
        assert!(s.url.is_empty());
        assert!(s.verify_tls);
    }

    #[test]
    fn test_proxmox_url_fallback_in_section() {
        // Simulates the update path: existing section has url, new section should preserve it
        let existing = ProviderConfig::parse(
            "[proxmox]\ntoken=old\nalias_prefix=pve\nuser=root\nurl=https://pve.local:8006\n",
        );
        let existing_url = existing.section("proxmox").map(|s| s.url.clone()).unwrap_or_default();
        assert_eq!(existing_url, "https://pve.local:8006");

        let mut config = existing;
        config.set_section(ProviderSection {
            provider: "proxmox".to_string(),
            token: "new".to_string(),
            alias_prefix: "pve".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: existing_url,
            verify_tls: true,
            auto_sync: false,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        });
        assert_eq!(config.sections[0].token, "new");
        assert_eq!(config.sections[0].url, "https://pve.local:8006");
    }

    #[test]
    fn test_auto_sync_default_true_for_non_proxmox() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\n");
        assert!(config.sections[0].auto_sync);
    }

    #[test]
    fn test_auto_sync_default_false_for_proxmox() {
        let config = ProviderConfig::parse("[proxmox]\ntoken=abc\nurl=https://pve:8006\n");
        assert!(!config.sections[0].auto_sync);
    }

    #[test]
    fn test_auto_sync_explicit_true() {
        let config = ProviderConfig::parse("[proxmox]\ntoken=abc\nurl=https://pve:8006\nauto_sync=true\n");
        assert!(config.sections[0].auto_sync);
    }

    #[test]
    fn test_auto_sync_explicit_false_non_proxmox() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\nauto_sync=false\n");
        assert!(!config.sections[0].auto_sync);
    }

    #[test]
    fn test_auto_sync_not_written_when_default() {
        // non-proxmox with auto_sync=true (default) -> not written
        let mut config = ProviderConfig::default();
        config.set_section(ProviderSection {
            provider: "digitalocean".to_string(),
            token: "tok".to_string(),
            alias_prefix: "do".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: String::new(),
            verify_tls: true,
            auto_sync: true,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        });
        // Re-parse: auto_sync should still be true (default)
        assert!(config.sections[0].auto_sync);

        // proxmox with auto_sync=false (default) -> not written
        let mut config2 = ProviderConfig::default();
        config2.set_section(ProviderSection {
            provider: "proxmox".to_string(),
            token: "tok".to_string(),
            alias_prefix: "pve".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: "https://pve:8006".to_string(),
            verify_tls: true,
            auto_sync: false,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        });
        assert!(!config2.sections[0].auto_sync);
    }

    #[test]
    fn test_auto_sync_false_variants() {
        for value in &["false", "False", "FALSE", "0", "no"] {
            let content = format!("[digitalocean]\ntoken=abc\nauto_sync={}\n", value);
            let config = ProviderConfig::parse(&content);
            assert!(!config.sections[0].auto_sync, "auto_sync={} should be false", value);
        }
    }

    #[test]
    fn test_auto_sync_true_variants() {
        for value in &["true", "True", "TRUE", "1", "yes"] {
            // Start from proxmox default=false, override to true via explicit value
            let content = format!("[proxmox]\ntoken=abc\nurl=https://pve:8006\nauto_sync={}\n", value);
            let config = ProviderConfig::parse(&content);
            assert!(config.sections[0].auto_sync, "auto_sync={} should be true", value);
        }
    }

    #[test]
    fn test_auto_sync_malformed_value_treated_as_true() {
        // Unrecognised value is not "false"/"0"/"no", so treated as true (like verify_tls)
        let config = ProviderConfig::parse("[proxmox]\ntoken=abc\nurl=https://pve:8006\nauto_sync=maybe\n");
        assert!(config.sections[0].auto_sync);
    }

    #[test]
    fn test_auto_sync_written_only_when_non_default() {
        // proxmox defaults to false — setting it to true is non-default, so it IS written
        let mut config = ProviderConfig::default();
        config.set_section(ProviderSection {
            provider: "proxmox".to_string(),
            token: "tok".to_string(),
            alias_prefix: "pve".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: "https://pve:8006".to_string(),
            verify_tls: true,
            auto_sync: true, // non-default for proxmox
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        });
        // Simulate save by rebuilding content string (same logic as save())
        let content =
            "[proxmox]\ntoken=tok\nalias_prefix=pve\nuser=root\nurl=https://pve:8006\nauto_sync=true\n"
        .to_string();
        let reparsed = ProviderConfig::parse(&content);
        assert!(reparsed.sections[0].auto_sync);

        // digitalocean defaults to true — setting it to false IS written
        let content2 = "[digitalocean]\ntoken=tok\nalias_prefix=do\nuser=root\nauto_sync=false\n";
        let reparsed2 = ProviderConfig::parse(content2);
        assert!(!reparsed2.sections[0].auto_sync);
    }

    // =========================================================================
    // configured_providers accessor
    // =========================================================================

    #[test]
    fn test_configured_providers_empty() {
        let config = ProviderConfig::default();
        assert!(config.configured_providers().is_empty());
    }

    #[test]
    fn test_configured_providers_returns_all() {
        let content = "[digitalocean]\ntoken=a\n\n[vultr]\ntoken=b\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.configured_providers().len(), 2);
    }

    // =========================================================================
    // Parse edge cases
    // =========================================================================

    #[test]
    fn test_parse_unknown_keys_ignored() {
        let content = "[digitalocean]\ntoken=abc\nfoo=bar\nunknown_key=value\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].token, "abc");
    }

    #[test]
    fn test_parse_unknown_provider_still_parsed() {
        let content = "[aws]\ntoken=secret\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].provider, "aws");
    }

    #[test]
    fn test_parse_whitespace_in_section_name() {
        let content = "[ digitalocean ]\ntoken=abc\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].provider, "digitalocean");
    }

    #[test]
    fn test_parse_value_with_equals() {
        // Token might contain = signs (base64)
        let content = "[digitalocean]\ntoken=abc=def==\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].token, "abc=def==");
    }

    #[test]
    fn test_parse_whitespace_around_key_value() {
        let content = "[digitalocean]\n  token = my-token  \n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].token, "my-token");
    }

    #[test]
    fn test_parse_key_field_sets_identity_file() {
        let content = "[digitalocean]\ntoken=abc\nkey=~/.ssh/id_rsa\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].identity_file, "~/.ssh/id_rsa");
    }

    #[test]
    fn test_section_lookup_missing() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\n");
        assert!(config.section("vultr").is_none());
    }

    #[test]
    fn test_section_lookup_found() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\n");
        let section = config.section("digitalocean").unwrap();
        assert_eq!(section.token, "abc");
    }

    #[test]
    fn test_remove_nonexistent_section_noop() {
        let mut config = ProviderConfig::parse("[digitalocean]\ntoken=abc\n");
        config.remove_section("vultr");
        assert_eq!(config.sections.len(), 1);
    }

    // =========================================================================
    // Default alias_prefix from short_label
    // =========================================================================

    #[test]
    fn test_default_alias_prefix_digitalocean() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\n");
        assert_eq!(config.sections[0].alias_prefix, "do");
    }

    #[test]
    fn test_default_alias_prefix_upcloud() {
        let config = ProviderConfig::parse("[upcloud]\ntoken=abc\n");
        assert_eq!(config.sections[0].alias_prefix, "uc");
    }

    #[test]
    fn test_default_alias_prefix_proxmox() {
        let config = ProviderConfig::parse("[proxmox]\ntoken=abc\n");
        assert_eq!(config.sections[0].alias_prefix, "pve");
    }

    #[test]
    fn test_alias_prefix_override() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\nalias_prefix=ocean\n");
        assert_eq!(config.sections[0].alias_prefix, "ocean");
    }

    // =========================================================================
    // Default user is root
    // =========================================================================

    #[test]
    fn test_default_user_is_root() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\n");
        assert_eq!(config.sections[0].user, "root");
    }

    #[test]
    fn test_user_override() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\nuser=admin\n");
        assert_eq!(config.sections[0].user, "admin");
    }

    // =========================================================================
    // Proxmox URL scheme validation context
    // =========================================================================

    #[test]
    fn test_proxmox_url_parsed() {
        let config = ProviderConfig::parse("[proxmox]\ntoken=abc\nurl=https://pve.local:8006\n");
        assert_eq!(config.sections[0].url, "https://pve.local:8006");
    }

    #[test]
    fn test_non_proxmox_url_parsed_but_ignored() {
        // URL field is parsed for all providers, but only Proxmox uses it
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\nurl=https://api.do.com\n");
        assert_eq!(config.sections[0].url, "https://api.do.com");
    }

    // =========================================================================
    // Duplicate sections
    // =========================================================================

    #[test]
    fn test_duplicate_section_first_wins() {
        let content = "[digitalocean]\ntoken=first\n\n[digitalocean]\ntoken=second\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].token, "first");
    }

    // =========================================================================
    // verify_tls parsing
    // =========================================================================

    // =========================================================================
    // auto_sync default per provider
    // =========================================================================

    #[test]
    fn test_auto_sync_default_proxmox_false() {
        let config = ProviderConfig::parse("[proxmox]\ntoken=abc\n");
        assert!(!config.sections[0].auto_sync);
    }

    #[test]
    fn test_auto_sync_default_all_others_true() {
        for provider in &["digitalocean", "vultr", "linode", "hetzner", "upcloud", "aws", "scaleway", "gcp"] {
            let content = format!("[{}]\ntoken=abc\n", provider);
            let config = ProviderConfig::parse(&content);
            assert!(config.sections[0].auto_sync, "auto_sync should default to true for {}", provider);
        }
    }

    #[test]
    fn test_auto_sync_override_proxmox_to_true() {
        let config = ProviderConfig::parse("[proxmox]\ntoken=abc\nauto_sync=true\n");
        assert!(config.sections[0].auto_sync);
    }

    #[test]
    fn test_auto_sync_override_do_to_false() {
        let config = ProviderConfig::parse("[digitalocean]\ntoken=abc\nauto_sync=false\n");
        assert!(!config.sections[0].auto_sync);
    }

    // =========================================================================
    // set_section and remove_section
    // =========================================================================

    #[test]
    fn test_set_section_adds_new() {
        let mut config = ProviderConfig::default();
        let section = ProviderSection {
            provider: "vultr".to_string(),
            token: "tok".to_string(),
            alias_prefix: "vultr".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: String::new(),
            verify_tls: true,
            auto_sync: true,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        };
        config.set_section(section);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].provider, "vultr");
    }

    #[test]
    fn test_set_section_replaces_existing() {
        let mut config = ProviderConfig::parse("[vultr]\ntoken=old\n");
        assert_eq!(config.sections[0].token, "old");
        let section = ProviderSection {
            provider: "vultr".to_string(),
            token: "new".to_string(),
            alias_prefix: "vultr".to_string(),
            user: "root".to_string(),
            identity_file: String::new(),
            url: String::new(),
            verify_tls: true,
            auto_sync: true,
            profile: String::new(),
            regions: String::new(),
            project: String::new(),
        };
        config.set_section(section);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].token, "new");
    }

    #[test]
    fn test_remove_section_keeps_others() {
        let mut config = ProviderConfig::parse("[vultr]\ntoken=abc\n\n[linode]\ntoken=def\n");
        assert_eq!(config.sections.len(), 2);
        config.remove_section("vultr");
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].provider, "linode");
    }

    // =========================================================================
    // Comments and blank lines
    // =========================================================================

    #[test]
    fn test_comments_ignored() {
        let content = "# This is a comment\n[digitalocean]\n# Another comment\ntoken=abc\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].token, "abc");
    }

    #[test]
    fn test_blank_lines_ignored() {
        let content = "\n\n[digitalocean]\n\ntoken=abc\n\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 1);
        assert_eq!(config.sections[0].token, "abc");
    }

    // =========================================================================
    // Multiple providers
    // =========================================================================

    #[test]
    fn test_multiple_providers() {
        let content = "[digitalocean]\ntoken=do-tok\n\n[vultr]\ntoken=vultr-tok\n\n[proxmox]\ntoken=pve-tok\nurl=https://pve:8006\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections.len(), 3);
        assert_eq!(config.sections[0].provider, "digitalocean");
        assert_eq!(config.sections[1].provider, "vultr");
        assert_eq!(config.sections[2].provider, "proxmox");
        assert_eq!(config.sections[2].url, "https://pve:8006");
    }

    // =========================================================================
    // Token with special characters
    // =========================================================================

    #[test]
    fn test_token_with_equals_sign() {
        // API tokens can contain = signs (e.g., base64)
        let content = "[digitalocean]\ntoken=dop_v1_abc123==\n";
        let config = ProviderConfig::parse(content);
        // split_once('=') splits at first =, so "dop_v1_abc123==" is preserved
        assert_eq!(config.sections[0].token, "dop_v1_abc123==");
    }

    #[test]
    fn test_proxmox_token_with_exclamation() {
        let content = "[proxmox]\ntoken=user@pam!api-token=12345678-abcd\nurl=https://pve:8006\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].token, "user@pam!api-token=12345678-abcd");
    }

    // =========================================================================
    // Parse serialization roundtrip
    // =========================================================================

    #[test]
    fn test_serialize_roundtrip_single_provider() {
        let content = "[digitalocean]\ntoken=abc\nalias_prefix=do\nuser=root\n";
        let config = ProviderConfig::parse(content);
        let mut serialized = String::new();
        for section in &config.sections {
            serialized.push_str(&format!("[{}]\n", section.provider));
            serialized.push_str(&format!("token={}\n", section.token));
            serialized.push_str(&format!("alias_prefix={}\n", section.alias_prefix));
            serialized.push_str(&format!("user={}\n", section.user));
        }
        let reparsed = ProviderConfig::parse(&serialized);
        assert_eq!(reparsed.sections.len(), 1);
        assert_eq!(reparsed.sections[0].token, "abc");
        assert_eq!(reparsed.sections[0].alias_prefix, "do");
        assert_eq!(reparsed.sections[0].user, "root");
    }

    // =========================================================================
    // verify_tls parsing variants
    // =========================================================================

    #[test]
    fn test_verify_tls_values() {
        for (val, expected) in [
            ("false", false), ("False", false), ("FALSE", false),
            ("0", false), ("no", false), ("No", false), ("NO", false),
            ("true", true), ("True", true), ("1", true), ("yes", true),
            ("anything", true), // any unrecognized value defaults to true
        ] {
            let content = format!("[digitalocean]\ntoken=t\nverify_tls={}\n", val);
            let config = ProviderConfig::parse(&content);
            assert_eq!(
                config.sections[0].verify_tls, expected,
                "verify_tls={} should be {}",
                val, expected
            );
        }
    }

    // =========================================================================
    // auto_sync parsing variants
    // =========================================================================

    #[test]
    fn test_auto_sync_values() {
        for (val, expected) in [
            ("false", false), ("False", false), ("FALSE", false),
            ("0", false), ("no", false), ("No", false),
            ("true", true), ("1", true), ("yes", true),
        ] {
            let content = format!("[digitalocean]\ntoken=t\nauto_sync={}\n", val);
            let config = ProviderConfig::parse(&content);
            assert_eq!(
                config.sections[0].auto_sync, expected,
                "auto_sync={} should be {}",
                val, expected
            );
        }
    }

    // =========================================================================
    // Default values
    // =========================================================================

    #[test]
    fn test_default_user_root_when_not_specified() {
        let content = "[digitalocean]\ntoken=abc\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].user, "root");
    }

    #[test]
    fn test_default_alias_prefix_from_short_label() {
        // DigitalOcean short_label is "do"
        let content = "[digitalocean]\ntoken=abc\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].alias_prefix, "do");
    }

    #[test]
    fn test_default_alias_prefix_unknown_provider() {
        // Unknown provider uses the section name as default prefix
        let content = "[unknown_cloud]\ntoken=abc\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].alias_prefix, "unknown_cloud");
    }

    #[test]
    fn test_default_identity_file_empty() {
        let content = "[digitalocean]\ntoken=abc\n";
        let config = ProviderConfig::parse(content);
        assert!(config.sections[0].identity_file.is_empty());
    }

    #[test]
    fn test_default_url_empty() {
        let content = "[digitalocean]\ntoken=abc\n";
        let config = ProviderConfig::parse(content);
        assert!(config.sections[0].url.is_empty());
    }

    // =========================================================================
    // GCP project field
    // =========================================================================

    #[test]
    fn test_gcp_project_parsed() {
        let config = ProviderConfig::parse("[gcp]\ntoken=abc\nproject=my-gcp-project\n");
        assert_eq!(config.sections[0].project, "my-gcp-project");
    }

    #[test]
    fn test_gcp_project_default_empty() {
        let config = ProviderConfig::parse("[gcp]\ntoken=abc\n");
        assert!(config.sections[0].project.is_empty());
    }

    #[test]
    fn test_gcp_project_roundtrip() {
        let content = "[gcp]\ntoken=sa.json\nproject=my-project\nregions=us-central1-a\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].project, "my-project");
        assert_eq!(config.sections[0].regions, "us-central1-a");
        // Re-serialize and parse
        let serialized = format!(
            "[gcp]\ntoken={}\nproject={}\nregions={}\n",
            config.sections[0].token,
            config.sections[0].project,
            config.sections[0].regions,
        );
        let reparsed = ProviderConfig::parse(&serialized);
        assert_eq!(reparsed.sections[0].project, "my-project");
        assert_eq!(reparsed.sections[0].regions, "us-central1-a");
    }

    #[test]
    fn test_default_alias_prefix_gcp() {
        let config = ProviderConfig::parse("[gcp]\ntoken=abc\n");
        assert_eq!(config.sections[0].alias_prefix, "gcp");
    }

    // =========================================================================
    // configured_providers and section methods
    // =========================================================================

    #[test]
    fn test_configured_providers_returns_all_sections() {
        let content = "[digitalocean]\ntoken=a\n\n[vultr]\ntoken=b\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.configured_providers().len(), 2);
    }

    #[test]
    fn test_section_by_name() {
        let content = "[digitalocean]\ntoken=do-tok\n\n[vultr]\ntoken=vultr-tok\n";
        let config = ProviderConfig::parse(content);
        let do_section = config.section("digitalocean").unwrap();
        assert_eq!(do_section.token, "do-tok");
        let vultr_section = config.section("vultr").unwrap();
        assert_eq!(vultr_section.token, "vultr-tok");
    }

    #[test]
    fn test_section_not_found() {
        let config = ProviderConfig::parse("");
        assert!(config.section("nonexistent").is_none());
    }

    // =========================================================================
    // Key without value
    // =========================================================================

    #[test]
    fn test_line_without_equals_ignored() {
        let content = "[digitalocean]\ntoken=abc\ngarbage_line\nuser=admin\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].token, "abc");
        assert_eq!(config.sections[0].user, "admin");
    }

    #[test]
    fn test_unknown_key_ignored() {
        let content = "[digitalocean]\ntoken=abc\nfoo=bar\nbaz=qux\nuser=admin\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].token, "abc");
        assert_eq!(config.sections[0].user, "admin");
    }

    // =========================================================================
    // Whitespace handling
    // =========================================================================

    #[test]
    fn test_whitespace_around_section_name() {
        let content = "[  digitalocean  ]\ntoken=abc\n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].provider, "digitalocean");
    }

    #[test]
    fn test_whitespace_around_key_value() {
        let content = "[digitalocean]\n  token  =  abc  \n  user  =  admin  \n";
        let config = ProviderConfig::parse(content);
        assert_eq!(config.sections[0].token, "abc");
        assert_eq!(config.sections[0].user, "admin");
    }

    // =========================================================================
    // set_section edge cases
    // =========================================================================

    #[test]
    fn test_set_section_multiple_adds() {
        let mut config = ProviderConfig::default();
        for name in ["digitalocean", "vultr", "hetzner"] {
            config.set_section(ProviderSection {
                provider: name.to_string(),
                token: format!("{}-tok", name),
                alias_prefix: name.to_string(),
                user: "root".to_string(),
                identity_file: String::new(),
                url: String::new(),
                verify_tls: true,
                auto_sync: true,
                profile: String::new(),
                regions: String::new(),
                project: String::new(),
            });
        }
        assert_eq!(config.sections.len(), 3);
    }

    #[test]
    fn test_remove_section_all() {
        let content = "[digitalocean]\ntoken=a\n\n[vultr]\ntoken=b\n";
        let mut config = ProviderConfig::parse(content);
        config.remove_section("digitalocean");
        config.remove_section("vultr");
        assert!(config.sections.is_empty());
    }
}