elasticctl-core 0.5.2

Core types, configuration, and transport for Elastic Security rule operations.
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
//! Profiles, their on-disk form, and resolution order.
//!
//! Flags override environment variables, which override profiles and defaults.

use crate::error::{Error, ErrorKind, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

const REDACTED: &str = "***";

/// Whether overrides change the target deployment or credential.
///
/// Only these overrides change the guard banner's reported source. Timeout and
/// space overrides do not.
fn is_identity_override(ov: &Overrides) -> bool {
    ov.kibana_url.is_some() || ov.es_url.is_some() || ov.api_key.is_some()
}

/// Read an environment variable, distinguishing absence from invalid Unicode.
///
/// The error names the variable but never includes its raw bytes, so a binary
/// value cannot leak into a message or log.
fn checked_env(name: &str) -> Result<Option<String>> {
    match std::env::var_os(name) {
        None => Ok(None),
        Some(value) => value.into_string().map(Some).map_err(|_| {
            Error::new(
                ErrorKind::Error,
                format!("{name} contains invalid Unicode; set it to valid UTF-8"),
            )
        }),
    }
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Profile {
    pub kibana_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub es_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,
    #[serde(default = "default_space")]
    pub space: String,
    #[serde(default = "default_verify")]
    pub verify: bool,
    #[serde(default = "default_timeout")]
    pub timeout_secs: u64,
}

fn default_space() -> String {
    "default".to_string()
}
fn default_verify() -> bool {
    true
}
fn default_timeout() -> u64 {
    30
}

impl std::fmt::Debug for Profile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Profile")
            .field("kibana_url", &strip_userinfo(&self.kibana_url))
            .field("es_url", &self.es_url.as_deref().map(strip_userinfo))
            .field("api_key", &self.api_key.as_ref().map(|_| REDACTED))
            .field("username", &self.username)
            .field("password", &self.password.as_ref().map(|_| REDACTED))
            .field("space", &self.space)
            .field("verify", &self.verify)
            .field("timeout_secs", &self.timeout_secs)
            .finish()
    }
}

impl Profile {
    /// Return a copy safe to print.
    ///
    /// Secrets become `***`; absent values remain absent. URL userinfo is
    /// stripped too, so a credential embedded in a URL never leaks.
    pub fn redacted(&self) -> Profile {
        let mut scrubbed = self.clone();
        scrubbed.strip_userinfo();
        Profile {
            api_key: self.api_key.as_ref().map(|_| REDACTED.to_string()),
            password: self.password.as_ref().map(|_| REDACTED.to_string()),
            ..scrubbed
        }
    }

    /// Return the Kibana URL host for banners.
    ///
    /// Userinfo is stripped first, then the host is parsed. Return the scrubbed
    /// URL when no host can be parsed.
    pub fn host(&self) -> String {
        // Strip userinfo so a credential in the URL never reaches a banner.
        let url = strip_userinfo(&self.kibana_url);
        // Parse the authority host. `scheme_anchor` handles a doubled scheme;
        // the split drops the path, query, and fragment.
        if let Some(pos) = scheme_anchor(&url) {
            let after_scheme = &url[pos..];
            let host_part = after_scheme.split(['/', '?', '#']).next().unwrap_or("");
            // Use the parsed host when present.
            if !host_part.is_empty() {
                return host_part.to_string();
            }
        }
        // Preserve the scrubbed URL when parsing finds no host.
        url
    }

    /// Remove userinfo from `kibana_url` and `es_url`.
    ///
    /// Credentials use `api_key` or `username` and `password`; the transport
    /// never reads URL userinfo. Removing it prevents credentials appearing in
    /// the guard banner, `config show`, or `--debug` output.
    pub fn strip_userinfo(&mut self) {
        self.kibana_url = strip_userinfo(&self.kibana_url);
        self.es_url = self.es_url.as_deref().map(strip_userinfo);
    }
}

/// Return the byte index just past the scheme's `://`.
///
/// Shared with flavor detection's `host_of`.
///
/// The scheme is normally the first `://`. A doubled scheme
/// (`https://https://host`) puts a second `://` inside the authority, so the
/// first `/` after the first `://` is itself part of that `://`; anchor on that
/// second `://` then so the authority after it parses correctly. A `://` in the
/// path, query, or fragment never becomes the anchor.
pub(crate) fn scheme_anchor(url: &str) -> Option<usize> {
    let first = url.find("://")?;
    let after = &url[first + 3..];
    let Some(delim) = after.find(['/', '?', '#']) else {
        return Some(first + 3);
    };
    // A doubled scheme is the only case where the first delimiter is itself the
    // `/` of a second `://`. An empty port (`https://host:/path`) also ends the
    // authority in `:`, but the bytes after it are not `//`, so it is not
    // doubled and must anchor on the first scheme.
    if delim >= 1
        && after.as_bytes()[delim - 1] == b':'
        && after.get(delim..delim + 2) == Some("//")
    {
        // Anchor just past the second `://`, never on a later `://` in the
        // path, query, or fragment.
        Some(first + 3 + delim + 2)
    } else {
        Some(first + 3)
    }
}

/// Remove userinfo from a URL authority without changing other bytes.
///
/// Userinfo is the `user:password@` in the authority, delimited by the scheme's
/// `://` and the first `/`, `?`, or `#` after it. Paths and queries may
/// legitimately contain `@`; only an `@` inside the authority is userinfo. A
/// `://` in the path, query, or fragment is not the scheme and must not defeat
/// the strip, while a doubled scheme still strips its userinfo.
fn strip_userinfo(url: &str) -> String {
    let Some(scheme_end) = scheme_anchor(url) else {
        return url.to_string();
    };
    let (scheme, rest) = url.split_at(scheme_end);
    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, tail) = rest.split_at(authority_end);
    match authority.rfind('@') {
        Some(i) => format!("{scheme}{}{tail}", &authority[i + 1..]),
        None => url.to_string(),
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
    #[serde(default)]
    pub current: String,
    #[serde(default)]
    pub profiles: BTreeMap<String, Profile>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
    Profile,
    Env,
    Flags,
}

#[derive(Debug, Clone)]
pub struct Resolved {
    pub profile: Profile,
    pub name: String,
    pub source: Source,
}

impl Resolved {
    pub fn banner(&self) -> String {
        format!(
            "profile: {} @ {}, space: {}",
            self.name,
            self.profile.host(),
            self.profile.space
        )
    }
}

#[derive(Debug, Clone, Default)]
pub struct Overrides {
    pub kibana_url: Option<String>,
    pub es_url: Option<String>,
    pub api_key: Option<String>,
    pub space: Option<String>,
    pub timeout_secs: Option<u64>,
}

impl Overrides {
    /// Read `ELASTICCTL_*` environment variables as overrides.
    ///
    /// `es_url` and `kibana_url` are identity overrides. Cloud deployments use
    /// distinct endpoints; inheriting one from a saved profile could target two
    /// deployments and send the overridden credential to the wrong host.
    pub fn from_env() -> Overrides {
        Overrides {
            kibana_url: std::env::var("ELASTICCTL_KIBANA_URL").ok(),
            es_url: std::env::var("ELASTICCTL_ES_URL").ok(),
            api_key: std::env::var("ELASTICCTL_API_KEY").ok(),
            space: std::env::var("ELASTICCTL_SPACE").ok(),
            timeout_secs: std::env::var("ELASTICCTL_TIMEOUT")
                .ok()
                .and_then(|v| v.parse().ok()),
        }
    }

    /// Read `ELASTICCTL_*` environment variables as overrides, failing on
    /// invalid input.
    ///
    /// Unlike `from_env`, this distinguishes an absent variable from invalid
    /// Unicode and rejects a non-integer timeout instead of silently dropping
    /// it.
    pub fn try_from_env() -> Result<Overrides> {
        Self::try_from_env_with_flags(&Overrides::default())
    }

    /// Read `ELASTICCTL_*` as overrides, failing on invalid input for every
    /// field the given flags do not already override.
    ///
    /// A flag overrides its environment variable, so a stale invalid value in
    /// an overridden field must not fail the command. `Context::build` passes
    /// the CLI flags here; `config init --from-env` uses the strict
    /// `try_from_env` because the environment is its source of truth.
    pub fn try_from_env_with_flags(flags: &Overrides) -> Result<Overrides> {
        let timeout = if flags.timeout_secs.is_some() {
            std::env::var("ELASTICCTL_TIMEOUT")
                .ok()
                .and_then(|v| v.parse().ok())
        } else {
            match checked_env("ELASTICCTL_TIMEOUT")? {
                None => None,
                Some(value) => Some(value.parse::<u64>().map_err(|error| {
                    Error::new(
                        ErrorKind::Error,
                        format!("ELASTICCTL_TIMEOUT must be an unsigned integer: {error}"),
                    )
                })?),
            }
        };
        let space = if flags.space.is_some() {
            std::env::var("ELASTICCTL_SPACE").ok()
        } else {
            checked_env("ELASTICCTL_SPACE")?
        };
        Ok(Overrides {
            kibana_url: checked_env("ELASTICCTL_KIBANA_URL")?,
            es_url: checked_env("ELASTICCTL_ES_URL")?,
            api_key: checked_env("ELASTICCTL_API_KEY")?,
            space,
            timeout_secs: timeout,
        })
    }

    /// Merge overrides, preferring `self` over `lower`.
    pub fn merge_over(self, lower: Overrides) -> Overrides {
        Overrides {
            kibana_url: self.kibana_url.or(lower.kibana_url),
            es_url: self.es_url.or(lower.es_url),
            api_key: self.api_key.or(lower.api_key),
            space: self.space.or(lower.space),
            timeout_secs: self.timeout_secs.or(lower.timeout_secs),
        }
    }
}

impl Config {
    pub fn default_path() -> PathBuf {
        directories::UserDirs::new()
            .map(|d| d.home_dir().to_path_buf())
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".elasticctl")
            .join("config.toml")
    }

    /// Treat a missing file as an empty config so `config init` works on a new
    /// machine.
    pub fn load(path: &Path) -> Result<Config> {
        if !path.exists() {
            return Ok(Config::default());
        }
        let body = fs::read_to_string(path).map_err(|e| {
            Error::new(ErrorKind::Error, format!("reading {}: {e}", path.display()))
        })?;
        toml::from_str(&body)
            .map_err(|e| Error::new(ErrorKind::Error, format!("parsing {}: {e}", path.display())))
    }

    /// Describe insecure file permissions, or return `None` for absent or
    /// owner-only files.
    ///
    /// The caller decides whether and how to display this warning, including
    /// for CLI `--json` output.
    #[cfg(unix)]
    pub fn permission_warning(path: &Path) -> Option<String> {
        use std::os::unix::fs::PermissionsExt;
        let metadata = fs::metadata(path).ok()?;
        let mode = metadata.permissions().mode();
        // Group or other permission bits are set.
        if mode & 0o077 != 0 {
            Some(format!(
                "config file {} is readable by group or other (mode {:o}); should be 0600",
                path.display(),
                mode & 0o777
            ))
        } else {
            None
        }
    }

    #[cfg(not(unix))]
    pub fn permission_warning(_path: &Path) -> Option<String> {
        None
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        let parent = path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."));
        fs::create_dir_all(parent).map_err(|e| {
            Error::new(
                ErrorKind::Error,
                format!("creating {}: {e}", parent.display()),
            )
        })?;
        // Strip userinfo from every profile before serializing, so a credential
        // embedded in a URL is never written to disk by a direct library caller.
        let mut scrubbed = self.clone();
        for profile in scrubbed.profiles.values_mut() {
            profile.strip_userinfo();
        }
        let body = toml::to_string_pretty(&scrubbed)
            .map_err(|e| Error::new(ErrorKind::Error, format!("serializing config: {e}")))?;

        // Write to a same-directory temporary file, then rename it over the
        // destination. This replaces the file atomically instead of truncating
        // it in place, so an existing loose-permission file or a symlink is
        // never written through.
        let mut pending = tempfile::Builder::new()
            .prefix(".elasticctl-config-")
            .tempfile_in(parent)
            .map_err(|e| {
                Error::new(ErrorKind::Error, format!("writing {}: {e}", path.display()))
            })?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            pending
                .as_file()
                .set_permissions(fs::Permissions::from_mode(0o600))
                .map_err(|e| {
                    Error::new(ErrorKind::Error, format!("writing {}: {e}", path.display()))
                })?;
        }
        use std::io::Write;
        pending.write_all(body.as_bytes()).map_err(|e| {
            Error::new(ErrorKind::Error, format!("writing {}: {e}", path.display()))
        })?;
        pending.as_file().sync_all().map_err(|e| {
            Error::new(ErrorKind::Error, format!("writing {}: {e}", path.display()))
        })?;
        pending.persist(path).map_err(|e| {
            Error::new(ErrorKind::Error, format!("writing {}: {e}", path.display()))
        })?;
        // Sync the directory so the rename is durable. Only Linux supports
        // directory fsync; macOS and BSD return EINVAL on a directory fd.
        #[cfg(target_os = "linux")]
        fs::File::open(parent)
            .and_then(|f| f.sync_all())
            .map_err(|e| {
                Error::new(ErrorKind::Error, format!("writing {}: {e}", path.display()))
            })?;
        Ok(())
    }

    /// Resolve the effective profile and its source.
    pub fn resolve(&self, name: Option<&str>, ov: &Overrides) -> Result<Resolved> {
        let wanted = name.unwrap_or(if self.current.is_empty() {
            "default"
        } else {
            &self.current
        });
        let mut profile = self.profiles.get(wanted).cloned().ok_or_else(|| {
            Error::new(ErrorKind::NotFound, format!("Profile '{wanted}' not found"))
        })?;

        if let Some(v) = &ov.kibana_url {
            profile.kibana_url = v.clone();
        }
        // Do not combine an overridden Kibana URL with a profile Elasticsearch
        // URL: they can target separate deployments. Without an `es_url`
        // override, fall back to the Kibana host instead of sending credentials
        // to the profile's Elasticsearch host.
        if let Some(v) = &ov.es_url {
            profile.es_url = Some(v.clone());
        } else if ov.kibana_url.is_some() {
            profile.es_url = None;
        }
        if let Some(v) = &ov.api_key {
            profile.api_key = Some(v.clone());
        }
        if let Some(v) = &ov.space {
            profile.space = v.clone();
        }
        if let Some(v) = ov.timeout_secs {
            profile.timeout_secs = v;
        }

        let source = if is_identity_override(ov) {
            Source::Flags
        } else {
            Source::Profile
        };

        // Strip userinfo after applying file, environment, and flag values.
        profile.strip_userinfo();

        Ok(Resolved {
            profile,
            name: wanted.to_string(),
            source,
        })
    }
}

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

    fn sample() -> Config {
        let mut profiles = BTreeMap::new();
        profiles.insert(
            "default".to_string(),
            Profile {
                kibana_url: "https://kb.example.com".into(),
                es_url: Some("https://es.example.com".into()),
                api_key: Some("essu_SECRET".into()),
                username: Some("user".into()),
                password: Some("pass_SECRET".into()),
                space: "default".into(),
                verify: true,
                timeout_secs: 30,
            },
        );
        profiles.insert(
            "prod".to_string(),
            Profile {
                kibana_url: "https://prod.example.com".into(),
                ..profiles["default"].clone()
            },
        );
        Config {
            current: "default".into(),
            profiles,
        }
    }

    #[test]
    fn round_trips_through_toml() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        sample().save(&path).unwrap();
        let loaded = Config::load(&path).unwrap();
        assert_eq!(loaded.current, "default");
        assert_eq!(loaded.profiles.len(), 2);
        assert_eq!(
            loaded.profiles["prod"].kibana_url,
            "https://prod.example.com"
        );
    }

    #[test]
    fn save_enforces_owner_only_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        sample().save(&path).unwrap();
        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "config must not be readable by group or other");
    }

    #[cfg(unix)]
    #[test]
    fn save_atomically_replaces_a_permissive_existing_file() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        fs::write(&path, "old\n").unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
        let old_inode = fs::metadata(&path).unwrap().ino();

        sample().save(&path).unwrap();

        let metadata = fs::metadata(&path).unwrap();
        assert_ne!(metadata.ino(), old_inode, "save must replace, not truncate");
        assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
        assert_eq!(Config::load(&path).unwrap().current, "default");
    }

    #[cfg(unix)]
    #[test]
    fn save_replaces_a_symlink_without_writing_its_target() {
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("target.toml");
        let path = dir.path().join("config.toml");
        fs::write(&target, "do not replace\n").unwrap();
        symlink(&target, &path).unwrap();

        sample().save(&path).unwrap();

        assert_eq!(fs::read_to_string(&target).unwrap(), "do not replace\n");
        assert!(
            !fs::symlink_metadata(&path)
                .unwrap()
                .file_type()
                .is_symlink()
        );
    }

    #[test]
    fn save_never_writes_userinfo_to_disk() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        let cfg = with_urls(
            "https://user:pass@kb.example.com",
            Some("https://user:pass@es.example.com"),
        );
        cfg.save(&path).unwrap();
        let body = fs::read_to_string(&path).unwrap();
        assert!(!body.contains("user:pass"), "{body}");
        assert!(!body.contains("user:"), "{body}");
        assert!(body.contains("https://kb.example.com"), "{body}");
        assert!(body.contains("https://es.example.com"), "{body}");
    }

    #[test]
    fn load_of_a_missing_file_is_an_empty_config_not_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let cfg = Config::load(&dir.path().join("absent.toml")).unwrap();
        assert!(cfg.profiles.is_empty());
    }

    #[test]
    fn resolving_an_unknown_profile_is_a_not_found_error() {
        let err = sample()
            .resolve(Some("nope"), &Overrides::default())
            .unwrap_err();
        assert_eq!(err.kind, ErrorKind::NotFound);
        assert!(err.message.contains("nope"));
    }

    /// Verify that `ELASTICCTL_ES_URL` overrides the profile. This prevents a
    /// Kibana override and inherited `es_url` from targeting two deployments.
    #[test]
    fn an_es_url_override_is_applied() {
        let r = sample()
            .resolve(
                None,
                &Overrides {
                    es_url: Some("https://other-es.example.com".into()),
                    ..Default::default()
                },
            )
            .unwrap();
        assert_eq!(
            r.profile.es_url.as_deref(),
            Some("https://other-es.example.com")
        );
    }

    /// A Kibana-only override must clear the profile's Elasticsearch host.
    /// Otherwise credentials could be sent to an unselected deployment.
    #[test]
    fn overriding_only_the_kibana_url_clears_the_profiles_es_url() {
        let r = sample()
            .resolve(
                None,
                &Overrides {
                    kibana_url: Some("https://other-kb.example.com".into()),
                    ..Default::default()
                },
            )
            .unwrap();
        assert_eq!(
            r.profile.es_url, None,
            "an inherited es_url would point at the profile's stack, not the overridden one"
        );
    }

    #[test]
    fn an_es_url_override_counts_as_an_identity_override() {
        let r = sample()
            .resolve(
                None,
                &Overrides {
                    es_url: Some("https://other-es.example.com".into()),
                    ..Default::default()
                },
            )
            .unwrap();
        assert_eq!(
            r.source,
            Source::Flags,
            "changing which stack is addressed is an identity change"
        );
    }

    #[test]
    fn resolve_defaults_to_the_current_profile() {
        let r = sample().resolve(None, &Overrides::default()).unwrap();
        assert_eq!(r.name, "default");
        assert_eq!(r.source, Source::Profile);
        assert_eq!(r.profile.kibana_url, "https://kb.example.com");
    }

    #[test]
    fn flags_override_the_profile_and_change_the_reported_source() {
        let ov = Overrides {
            kibana_url: Some("https://override.example.com".into()),
            ..Default::default()
        };
        let r = sample().resolve(None, &ov).unwrap();
        assert_eq!(r.profile.kibana_url, "https://override.example.com");
        assert_eq!(
            r.source,
            Source::Flags,
            "an identity override changes provenance"
        );
    }

    #[test]
    fn a_non_identity_override_does_not_change_the_source() {
        let ov = Overrides {
            timeout_secs: Some(90),
            ..Default::default()
        };
        let r = sample().resolve(None, &ov).unwrap();
        assert_eq!(r.profile.timeout_secs, 90);
        assert_eq!(
            r.source,
            Source::Profile,
            "timeout is not an identity field"
        );
    }

    #[test]
    fn redacted_hides_every_secret_field() {
        let p = sample().profiles["default"].redacted();
        assert_eq!(
            p.api_key.as_deref(),
            Some("***"),
            "api_key must be redacted"
        );
        assert_eq!(
            p.password.as_deref(),
            Some("***"),
            "password must be redacted"
        );
        assert_eq!(
            p.kibana_url, "https://kb.example.com",
            "non-secrets stay visible"
        );
    }

    #[test]
    fn redacted_leaves_absent_secrets_absent() {
        let mut p = sample().profiles["default"].clone();
        p.api_key = None;
        p.password = None;
        let redacted = p.redacted();
        assert_eq!(redacted.api_key, None, "absent api_key stays absent");
        assert_eq!(redacted.password, None, "absent password stays absent");
    }

    #[test]
    fn redacted_strips_userinfo_from_both_urls() {
        let mut p = sample().profiles["default"].clone();
        p.kibana_url = "https://user:pass@kb.example.com".into();
        p.es_url = Some("https://user:pass@es.example.com".into());
        let r = p.redacted();
        assert_eq!(r.kibana_url, "https://kb.example.com");
        assert_eq!(r.es_url.as_deref(), Some("https://es.example.com"));
        assert_eq!(r.api_key.as_deref(), Some("***"), "secrets still redact");
    }

    #[test]
    fn debug_never_prints_a_secret_or_userinfo() {
        let profile = with_urls(
            "https://user:pass@kb.example.com",
            Some("https://user:pass@es.example.com"),
        )
        .profiles["default"]
            .clone();
        let out = format!("{profile:?}");
        assert!(!out.contains("essu_SECRET"), "api key leaked: {out}");
        // `user:pass` and `pass@` name the userinfo; the field name `password`
        // itself legitimately contains `pass`, so a bare `pass` would false-fail.
        assert!(!out.contains("user:pass"), "userinfo leaked: {out}");
        assert!(!out.contains("pass@"), "userinfo leaked: {out}");
        assert!(out.contains("kb.example.com"), "host missing: {out}");
        assert!(out.contains("es.example.com"), "host missing: {out}");
    }

    #[test]
    fn debug_marks_the_api_key_present_but_redacted() {
        let profile = with_urls("https://kb.example.com", None).profiles["default"].clone();
        let out = format!("{profile:?}");
        assert!(
            out.contains("Some(\"***\")"),
            "api key must show present-but-redacted: {out}"
        );
        assert!(!out.contains("essu_SECRET"), "api key leaked: {out}");
    }

    #[test]
    fn banner_names_profile_host_and_space() {
        let r = sample()
            .resolve(Some("prod"), &Overrides::default())
            .unwrap();
        let b = r.banner();
        assert!(b.contains("prod"), "banner must name the profile: {b}");
        assert!(
            b.contains("prod.example.com"),
            "banner must name the host: {b}"
        );
        assert!(b.contains("default"), "banner must name the space: {b}");
    }

    #[test]
    fn a_saved_config_never_contains_a_plaintext_key_in_a_world_readable_file() {
        // Check key storage and file permissions together.
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        sample().save(&path).unwrap();
        let body = fs::read_to_string(&path).unwrap();
        assert!(
            body.contains("essu_SECRET"),
            "the real key is stored, not redacted on disk"
        );
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
    }

    #[test]
    fn newly_created_file_is_mode_0600_not_umask_default() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("new_config.toml");
        // Verify the file is newly created.
        assert!(!path.exists());
        sample().save(&path).unwrap();
        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(
            mode, 0o600,
            "newly created config must be 0600 immediately, not umask default"
        );
    }

    #[test]
    fn host_parses_normal_https_url() {
        let p = Profile {
            kibana_url: "https://kb.example.com".into(),
            ..Profile {
                kibana_url: "".into(),
                es_url: None,
                api_key: None,
                username: None,
                password: None,
                space: "default".into(),
                verify: true,
                timeout_secs: 30,
            }
        };
        assert_eq!(p.host(), "kb.example.com");
    }

    #[test]
    fn host_strips_path_from_url() {
        let p = Profile {
            kibana_url: "https://kb.example.com/api/spaces".into(),
            ..Profile {
                kibana_url: "".into(),
                es_url: None,
                api_key: None,
                username: None,
                password: None,
                space: "default".into(),
                verify: true,
                timeout_secs: 30,
            }
        };
        assert_eq!(p.host(), "kb.example.com");
    }

    #[test]
    fn host_handles_doubled_scheme() {
        let p = Profile {
            kibana_url: "https://https://kb.example.com".into(),
            ..Profile {
                kibana_url: "".into(),
                es_url: None,
                api_key: None,
                username: None,
                password: None,
                space: "default".into(),
                verify: true,
                timeout_secs: 30,
            }
        };
        // A doubled scheme anchors on the second `://`, so the host is the
        // authority after it.
        assert_eq!(p.host(), "kb.example.com");
    }

    #[test]
    fn host_handles_bare_hostname() {
        let p = Profile {
            kibana_url: "kb.example.com".into(),
            ..Profile {
                kibana_url: "".into(),
                es_url: None,
                api_key: None,
                username: None,
                password: None,
                space: "default".into(),
                verify: true,
                timeout_secs: 30,
            }
        };
        assert_eq!(p.host(), "kb.example.com", "must fall back to original");
    }

    #[test]
    fn host_handles_empty_string() {
        let p = Profile {
            kibana_url: "".into(),
            es_url: None,
            api_key: None,
            username: None,
            password: None,
            space: "default".into(),
            verify: true,
            timeout_secs: 30,
        };
        assert_eq!(p.host(), "", "empty falls back to original");
    }

    #[test]
    fn host_never_shows_userinfo() {
        let p = with_urls("https://user:pass@kb.example.com", None).profiles["default"].clone();
        assert_eq!(p.host(), "kb.example.com");
    }

    #[test]
    fn load_succeeds_on_a_permissive_file_and_prints_nothing() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        sample().save(&path).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
        // `load` does not print; callers use `permission_warning` instead.
        let cfg = Config::load(&path).unwrap();
        assert!(
            !cfg.profiles.is_empty(),
            "load must succeed regardless of file permissions"
        );
    }

    #[test]
    fn permission_warning_flags_a_group_or_other_readable_file() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        sample().save(&path).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
        let warning = Config::permission_warning(&path).expect("0644 must warn");
        assert!(warning.contains("644"), "{warning}");
    }

    #[test]
    fn permission_warning_is_none_for_an_owner_only_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        sample().save(&path).unwrap(); // `Config::save` already enforces 0600.
        assert!(Config::permission_warning(&path).is_none());
    }

    #[test]
    fn permission_warning_is_none_for_a_missing_file() {
        let dir = tempfile::tempdir().unwrap();
        assert!(Config::permission_warning(&dir.path().join("absent.toml")).is_none());
    }

    fn with_urls(kibana: &str, es: Option<&str>) -> Config {
        let mut profiles = BTreeMap::new();
        profiles.insert(
            "default".to_string(),
            Profile {
                kibana_url: kibana.into(),
                es_url: es.map(String::from),
                api_key: Some("essu_SECRET".into()),
                username: None,
                password: None,
                space: "default".into(),
                verify: true,
                timeout_secs: 30,
            },
        );
        Config {
            current: "default".into(),
            profiles,
        }
    }

    #[test]
    fn resolve_strips_userinfo_from_both_urls() {
        let r = with_urls(
            "https://user:pass@kb.example.com",
            Some("https://user:pass@es.example.com:9243/"),
        )
        .resolve(None, &Overrides::default())
        .unwrap();
        assert_eq!(r.profile.kibana_url, "https://kb.example.com");
        assert_eq!(
            r.profile.es_url.as_deref(),
            Some("https://es.example.com:9243/")
        );
    }

    #[test]
    fn resolve_strips_userinfo_supplied_by_an_override() {
        // Strip userinfo after flags and environment overrides are applied.
        let ov = Overrides {
            kibana_url: Some("https://user:pass@override.example.com".into()),
            ..Default::default()
        };
        let r = with_urls("https://kb.example.com", None)
            .resolve(None, &ov)
            .unwrap();
        assert_eq!(r.profile.kibana_url, "https://override.example.com");
    }

    #[test]
    fn the_banner_never_shows_userinfo() {
        // The approval banner must not expose a password.
        let r = with_urls("https://user:hunter2@prod.example.com", None)
            .resolve(None, &Overrides::default())
            .unwrap();
        let b = r.banner();
        assert!(!b.contains("hunter2"), "{b}");
        // The banner uses one `@` between profile name and host.
        assert_eq!(b.matches('@').count(), 1, "{b}");
        assert!(b.contains("prod.example.com"), "{b}");
    }

    #[test]
    fn a_url_without_userinfo_is_left_exactly_as_written() {
        for url in [
            "https://kb.example.com",
            "https://kb.example.com:5601/base/path?q=1",
            "http://localhost:5601",
            "kb.example.com",
            "",
        ] {
            let mut p = with_urls(url, None).profiles["default"].clone();
            p.strip_userinfo();
            assert_eq!(
                p.kibana_url, url,
                "unchanged input must stay byte-identical"
            );
        }
    }

    #[test]
    fn an_at_sign_outside_the_authority_is_not_treated_as_userinfo() {
        // Only the authority carries userinfo; paths and queries may contain `@`.
        let mut p =
            with_urls("https://kb.example.com/a@b?user=x@y", None).profiles["default"].clone();
        p.strip_userinfo();
        assert_eq!(p.kibana_url, "https://kb.example.com/a@b?user=x@y");
    }

    #[test]
    fn a_query_string_scheme_without_userinfo_is_left_exactly_as_written() {
        // A later `://` in the query is not the scheme, so it must not disturb
        // a URL that carries no userinfo at all.
        let mut p =
            with_urls("https://kb.example.com/?next=https://idp", None).profiles["default"].clone();
        p.strip_userinfo();
        assert_eq!(p.kibana_url, "https://kb.example.com/?next=https://idp");
    }

    #[test]
    fn userinfo_is_stripped_when_a_query_contains_a_scheme() {
        // The first `://` delimits the scheme; the `://` inside the query must
        // not defeat the strip of the authority's userinfo.
        let mut p = with_urls("https://user:pass@kb.example.com/?next=https://idp", None).profiles
            ["default"]
            .clone();
        p.strip_userinfo();
        assert_eq!(p.kibana_url, "https://kb.example.com/?next=https://idp");
    }

    #[test]
    fn host_uses_the_authority_when_a_query_contains_a_scheme() {
        let p = with_urls("https://user:pass@kb.example.com/?next=https://idp", None)
            .profiles["default"]
            .clone();
        assert_eq!(p.host(), "kb.example.com");
    }

    #[test]
    fn a_doubled_scheme_with_userinfo_is_stripped() {
        // A doubled scheme anchors on the second `://`, so the `user:pass@` in
        // the authority after it is still stripped.
        let mut p =
            with_urls("https://https://user:pass@kb.example.com", None).profiles["default"].clone();
        p.strip_userinfo();
        assert_eq!(p.kibana_url, "https://https://kb.example.com");
        assert_eq!(p.host(), "kb.example.com");
    }

    #[test]
    fn a_doubled_scheme_with_userinfo_and_a_query_scheme_strips_the_userinfo() {
        // A doubled scheme plus a later `://` in the query must anchor on the
        // second scheme, not the query's `://`, or `user:pass@` leaks.
        let mut p = with_urls(
            "https://https://user:pass@kb.example.com/?next=https://idp",
            None,
        )
        .profiles["default"]
            .clone();
        p.strip_userinfo();
        assert_eq!(
            p.kibana_url,
            "https://https://kb.example.com/?next=https://idp"
        );
    }

    #[test]
    fn an_empty_port_does_not_defeat_userinfo_stripping() {
        // `host:` is an empty port, not a doubled scheme; the userinfo before it
        // must still be stripped even when the query carries a later `://`.
        let mut p =
            with_urls("https://user:pass@host:/path?next=https://idp", None).profiles["default"]
                .clone();
        p.strip_userinfo();
        assert_eq!(p.kibana_url, "https://host:/path?next=https://idp");
    }

    #[test]
    fn percent_encoded_userinfo_scrubs_to_the_host() {
        // The raw `@` is the delimiter; `%40` (a percent-encoded `@`) is not
        // userinfo and must not be mistaken for one.
        assert_eq!(
            strip_userinfo("https://user%40x:pass@kb.example.com"),
            "https://kb.example.com"
        );
    }

    #[test]
    fn percent_encoded_path_and_query_without_userinfo_are_left_byte_identical() {
        // `%2F` and `%3F` are percent-encoded `/` and `?`, not delimiters, so a
        // URL with no userinfo must be returned exactly as written.
        let url = "https://kb.example.com/%2Fpath?next=%3F";
        assert_eq!(strip_userinfo(url), url);
    }

    // `try_from_env_with_flags` and `try_from_env` read the process
    // environment, which cannot be mutated here because this crate forbids
    // `unsafe` blocks. Their flag-override behavior is exercised end-to-end by
    // the `config_cmd` integration test
    // `a_timeout_flag_supersedes_an_invalid_environment_timeout`.
}