fast-mcp-ssh 0.4.2

Fast MCP SSH server with persistent PTY sessions, SFTP, and AI-first tool surface
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
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    time::Duration,
};

use serde::{Deserialize, Serialize};

use crate::errors::{Result, SshError};

const DEFAULT_DENY: &[(&str, &str)] = &[
    // Matches: rm -rf /, rm -rf '/', rm -rf "/", rm -rf //, rm -rf /*,
    // rm -rf -- /, rm --recursive --force /, rm -rf /etc, rm -rf /etc/, RM -rf /.
    // Won't match relative paths (./tmp, ../foo) or deeper absolute paths
    // (rm -f /tmp/x.log): only root itself and first-level root dirs are
    // denied. The previous trailing `(\s|$|/)` alternative made ANY absolute
    // path match — every legitimate `rm /path/to/file` was blocked.
    (
        "rm-rf-root",
        r#"(?im)\brm\b(?:\s+(?:-{1,2}[a-zA-Z\-]+|--))*\s+['"]?/+\*?[a-zA-Z]*/?['"]?(\s|$)"#,
    ),
    (
        "dd-disk",
        r#"(?im)\bdd\b.*\bof\s*=\s*['"]?/dev/(sd|nvme|hd|vd)"#,
    ),
    ("mkfs", r#"(?im)\bmkfs(\.[a-z0-9]+)?\s+['"]?/dev/"#),
    ("forkbomb", r":\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:"),
    ("redirect-disk", r#">\s*['"]?/dev/(sd|nvme|hd|vd)"#),
    // chmod root: only literal `/` (filesystem root) is denied. `/etc` is allowed
    // by design — escalate via per-host guards if you want broader coverage.
    (
        "chmod-root",
        r#"(?im)\bchmod\b(?:\s+(?:-{1,2}[a-zA-Z\-]+|--))*\s+[0-7]{3,4}\s+['"]?/+['"]?(\s|$)"#,
    ),
];

const DEFAULT_CONFIRM: &[(&str, &str)] = &[
    ("shutdown", r"(?im)\b(shutdown|halt|poweroff)\b"),
    ("reboot", r"(?im)\breboot\b"),
    ("sql-drop", r"(?i)\bDROP\s+(TABLE|DATABASE|SCHEMA)\b"),
    ("sql-truncate", r"(?i)\bTRUNCATE\s+TABLE\b"),
    (
        "systemctl-stop",
        r"(?im)\bsystemctl\s+(stop|disable|mask)\b",
    ),
    (
        "docker-rm",
        r"(?im)\bdocker\s+(rm|rmi|volume\s+rm|system\s+prune)\b",
    ),
];

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Config {
    #[serde(default)]
    pub defaults: Defaults,
    #[serde(default, rename = "host")]
    pub hosts: HashMap<String, Host>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Defaults {
    /// Off by default: every non-wildcard alias in `~/.ssh/config` would
    /// otherwise become a host the model can reach without it ever appearing
    /// in `hosts.toml`. Opt in when you want that inventory.
    #[serde(default)]
    pub import_ssh_config: bool,
    #[serde(default = "default_output")]
    pub output: OutputFmt,
    #[serde(default = "default_idle")]
    pub session_idle_timeout: HumanDuration,
    #[serde(default = "default_true")]
    pub audit_log: bool,
    #[serde(default = "default_audit_path")]
    pub audit_log_path: PathBuf,
    /// Rotate the audit log once it crosses this size. `0` disables rotation
    /// and lets the file grow until the disk does.
    #[serde(default = "default_audit_max_bytes")]
    pub audit_max_bytes: u64,
    /// How many rotated `audit.log.1 … .N` generations to keep. `0` throws the
    /// old content away instead of archiving it.
    #[serde(default = "default_audit_keep_files")]
    pub audit_keep_files: usize,
    #[serde(default)]
    pub guards: Guards,
    #[serde(default = "default_keepalive")]
    pub keepalive: HumanDuration,
    #[serde(default = "default_connect_timeout")]
    pub connect_timeout: HumanDuration,
    #[serde(default = "default_truncate")]
    pub truncate_bytes: usize,
    #[serde(default = "default_max_capture")]
    pub max_capture_bytes: usize,
    #[serde(default = "default_max_channels")]
    pub max_channels_per_host: usize,
    #[serde(default)]
    pub strict_host_key_checking: StrictHostKey,
    /// How long an approved `confirm_patterns` command stays approved, keyed
    /// on the exact command string and host. A repeat of the identical
    /// command inside the window runs without a second prompt; anything else
    /// prompts again. Set `0s` to prompt every single time.
    #[serde(default = "default_confirm_ttl")]
    pub confirm_ttl: HumanDuration,
    /// Optional default host alias used when a tool call omits `host`.
    #[serde(default)]
    pub default_host: Option<String>,
}

impl Default for Defaults {
    fn default() -> Self {
        Self {
            import_ssh_config: false,
            output: OutputFmt::Toon,
            session_idle_timeout: default_idle(),
            audit_log: true,
            audit_log_path: default_audit_path(),
            audit_max_bytes: default_audit_max_bytes(),
            audit_keep_files: default_audit_keep_files(),
            guards: Guards::default(),
            keepalive: default_keepalive(),
            connect_timeout: default_connect_timeout(),
            truncate_bytes: default_truncate(),
            max_capture_bytes: default_max_capture(),
            max_channels_per_host: default_max_channels(),
            strict_host_key_checking: StrictHostKey::default(),
            confirm_ttl: default_confirm_ttl(),
            default_host: None,
        }
    }
}

#[derive(Debug, Clone, Copy, Deserialize, Serialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum StrictHostKey {
    /// Pin on first connect, reject on mismatch.
    #[default]
    Tofu,
    /// Reject any host not already pinned.
    Strict,
    /// Accept anything (legacy 0.1.0 behavior).
    Off,
}

#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum OutputFmt {
    Toon,
    Json,
    Text,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Host {
    pub addr: String,
    pub user: String,
    #[serde(default = "default_port")]
    pub port: u16,
    #[serde(default)]
    pub auth: AuthMethod,
    /// Primary private key path (back-compat with single-key configs).
    #[serde(default)]
    pub key: Option<PathBuf>,
    /// Optional list of additional candidate keys, tried in order after `key`.
    /// Useful when migrating between ed25519/rsa or when a host accepts
    /// multiple identities.
    #[serde(default)]
    pub keys: Option<Vec<PathBuf>>,
    #[serde(default)]
    pub guards: Option<Guards>,
    #[serde(default)]
    pub known_host_fingerprint: Option<String>,
    /// Alias of a host to use as a bastion / jump host. The connection to
    /// this host is opened first; a direct-tcpip channel to `addr:port` is
    /// then opened over the bastion and used as the transport for the SSH
    /// handshake with this host. Chains are followed recursively. Matches
    /// the semantics of OpenSSH `ProxyJump`.
    #[serde(default)]
    pub proxy_jump: Option<String>,
}

impl Host {
    /// Iterates over every configured key path in priority order.
    pub fn all_keys(&self) -> Vec<PathBuf> {
        let mut out = Vec::new();
        if let Some(k) = &self.key {
            out.push(k.clone());
        }
        if let Some(extra) = &self.keys {
            for k in extra {
                if !out.iter().any(|p| p == k) {
                    out.push(k.clone());
                }
            }
        }
        out
    }
}

#[derive(Debug, Clone, Copy, Deserialize, Serialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AuthMethod {
    #[default]
    Key,
    Agent,
    Password,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Guards {
    #[serde(default = "default_true")]
    pub use_default_deny: bool,
    #[serde(default = "default_true")]
    pub use_default_confirm: bool,
    #[serde(default)]
    pub deny: Vec<NamedPattern>,
    #[serde(default)]
    pub confirm: Vec<NamedPattern>,
    #[serde(default)]
    pub read_only: bool,
}

impl Default for Guards {
    fn default() -> Self {
        Self {
            use_default_deny: true,
            use_default_confirm: true,
            deny: Vec::new(),
            confirm: Vec::new(),
            read_only: false,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NamedPattern {
    pub name: String,
    pub pattern: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HumanDuration(pub Duration);

impl<'de> Deserialize<'de> for HumanDuration {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        parse_duration(&s)
            .map(HumanDuration)
            .map_err(serde::de::Error::custom)
    }
}

impl Serialize for HumanDuration {
    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
        s.serialize_str(&format!("{}s", self.0.as_secs()))
    }
}

fn parse_duration(s: &str) -> std::result::Result<Duration, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("empty duration".into());
    }
    let (num, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
    let n: u64 = num
        .parse()
        .map_err(|e| format!("bad number in duration '{s}': {e}"))?;
    let mult = match unit.trim() {
        "" | "s" | "sec" | "secs" => 1,
        "ms" => 0,
        "m" | "min" | "mins" => 60,
        "h" | "hr" | "hrs" => 3600,
        "d" | "day" | "days" => 86400,
        other => return Err(format!("unknown unit '{other}' in duration '{s}'")),
    };
    if mult == 0 {
        Ok(Duration::from_millis(n))
    } else {
        // `overflow-checks` is off in release, so an unchecked multiply would
        // wrap a nonsense value into a plausible-looking short timeout.
        let secs = n
            .checked_mul(mult)
            .ok_or_else(|| format!("duration '{s}' overflows"))?;
        Ok(Duration::from_secs(secs))
    }
}

fn default_true() -> bool {
    true
}
fn default_port() -> u16 {
    22
}
fn default_output() -> OutputFmt {
    OutputFmt::Toon
}
fn default_idle() -> HumanDuration {
    HumanDuration(Duration::from_secs(900))
}
fn default_keepalive() -> HumanDuration {
    HumanDuration(Duration::from_secs(30))
}
fn default_connect_timeout() -> HumanDuration {
    HumanDuration(Duration::from_secs(15))
}
fn default_truncate() -> usize {
    32 * 1024
}
fn default_max_capture() -> usize {
    256 * 1024
}
fn default_max_channels() -> usize {
    8
}
fn default_confirm_ttl() -> HumanDuration {
    HumanDuration(Duration::from_secs(900))
}
fn default_audit_max_bytes() -> u64 {
    16 * 1024 * 1024
}
fn default_audit_keep_files() -> usize {
    5
}
fn default_audit_path() -> PathBuf {
    config_dir().join("audit.log")
}

pub fn config_dir() -> PathBuf {
    if let Ok(env) = std::env::var("FAST_MCP_SSH_HOME") {
        return PathBuf::from(env);
    }
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".fast-mcp-ssh")
}

pub fn default_config_path() -> PathBuf {
    config_dir().join("hosts.toml")
}

impl Config {
    pub fn load(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Err(SshError::Config(format!(
                "config not found at {} — see hosts.example.toml",
                path.display()
            )));
        }
        warn_if_world_readable(path, "hosts.toml");
        let raw = std::fs::read_to_string(path)?;
        let mut cfg: Config = toml::from_str(&raw)?;
        if cfg.defaults.import_ssh_config {
            cfg.merge_ssh_config();
        }
        // Expand `~` after the ssh_config import so identity files imported
        // from `~/.ssh/config` (where `IdentityFile ~/.ssh/id_rsa` keeps the
        // literal `~`) get normalized too.
        cfg.expand_paths();
        cfg.validate()?;
        Ok(cfg)
    }

    /// Catches the common misconfigurations at startup so the first tool
    /// call doesn't have to discover them. Refuses:
    /// * `default_host` pointing at an undeclared alias
    /// * `auth = "key"` with no `key` and no `keys[]`
    /// * `auth = "password"` is fine — password is supplied per-call
    /// * `auth = "agent"` is fine — no key path needed
    /// * a configured key path that is missing or is not a regular file
    /// * a `known_host_fingerprint` that is not `SHA256:<base64>`
    ///
    /// A key readable by group or other only warns, matching OpenSSH, which
    /// refuses but has a `chmod` to offer; we do not own the file.
    pub fn validate(&self) -> Result<()> {
        if let Some(dh) = &self.defaults.default_host
            && !self.hosts.contains_key(dh)
        {
            return Err(SshError::Config(format!(
                "default_host '{dh}' is not declared in [host.*]"
            )));
        }
        for (name, h) in &self.hosts {
            if matches!(h.auth, AuthMethod::Key) && h.all_keys().is_empty() {
                return Err(SshError::Config(format!(
                    "host '{name}': auth = \"key\" but no `key` or `keys[]` set"
                )));
            }
            if h.addr.trim().is_empty() {
                return Err(SshError::Config(format!("host '{name}': addr is empty")));
            }
            if h.user.trim().is_empty() {
                return Err(SshError::Config(format!("host '{name}': user is empty")));
            }
            if matches!(h.auth, AuthMethod::Key) {
                for k in h.all_keys() {
                    check_key_file(name, &k)?;
                }
            }
            if let Some(fp) = &h.known_host_fingerprint {
                check_fingerprint(name, fp)?;
            }
            if let Some(pj) = &h.proxy_jump {
                if !self.hosts.contains_key(pj) {
                    return Err(SshError::Config(format!(
                        "host '{name}': proxy_jump = '{pj}' is not declared in [host.*]"
                    )));
                }
                if pj == name {
                    return Err(SshError::Config(format!(
                        "host '{name}': proxy_jump cannot reference self"
                    )));
                }
            }
        }
        // Detect proxy_jump cycles (A -> B -> A) — DFS from each host
        // following the chain. A repeat means a cycle.
        for name in self.hosts.keys() {
            let mut seen = std::collections::HashSet::new();
            let mut cur = name.as_str();
            seen.insert(cur);
            while let Some(next) = self.hosts.get(cur).and_then(|h| h.proxy_jump.as_deref()) {
                if !seen.insert(next) {
                    return Err(SshError::Config(format!(
                        "host '{name}': proxy_jump cycle detected through '{next}'"
                    )));
                }
                cur = next;
            }
        }
        Ok(())
    }

    pub fn host(&self, name: &str) -> Result<&Host> {
        self.hosts
            .get(name)
            .ok_or_else(|| SshError::UnknownHost(name.to_string()))
    }

    pub fn host_names(&self) -> Vec<String> {
        let mut v: Vec<_> = self.hosts.keys().cloned().collect();
        v.sort();
        v
    }

    fn expand_paths(&mut self) {
        for h in self.hosts.values_mut() {
            if let Some(k) = &h.key
                && let Some(s) = k.to_str()
                && let Ok(expanded) = shellexpand::full(s)
            {
                h.key = Some(PathBuf::from(expanded.into_owned()));
            }
            if let Some(extra) = h.keys.as_mut() {
                for k in extra.iter_mut() {
                    if let Some(s) = k.to_str()
                        && let Ok(expanded) = shellexpand::full(s)
                    {
                        *k = PathBuf::from(expanded.into_owned());
                    }
                }
            }
        }
        if let Some(s) = self.defaults.audit_log_path.to_str()
            && let Ok(expanded) = shellexpand::full(s)
        {
            self.defaults.audit_log_path = PathBuf::from(expanded.into_owned());
        }
    }

    fn merge_ssh_config(&mut self) {
        // Best-effort import of ~/.ssh/config aliases. Reads via our own
        // ssh_config parser and adds any non-wildcard host that is not already
        // declared in hosts.toml.
        let p = match dirs::home_dir() {
            Some(h) => h.join(".ssh").join("config"),
            None => return,
        };
        if !p.exists() {
            return;
        }
        let parsed = match crate::ssh_config::SshConfig::parse_file(&p) {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!(?e, "parse ~/.ssh/config failed");
                return;
            }
        };
        // First pass inserts the hosts; ProxyJump can only be honored once we
        // know which aliases actually made it into the map.
        let mut jumps: Vec<(String, String)> = Vec::new();
        for alias in parsed.list_aliases() {
            if self.hosts.contains_key(&alias) {
                continue;
            }
            let resolved = parsed.query(&alias);
            let Some(addr) = resolved.host_name.clone() else {
                continue;
            };
            let user = resolved.user.clone().unwrap_or_else(|| "root".into());
            let port = resolved.port.unwrap_or(22);
            // OpenSSH tolerates an `IdentityFile` that does not exist; it just
            // skips it. Keep only a key we can actually read so `validate`'s
            // stat check never fails the whole config over a side file we
            // imported on the user's behalf.
            let key = resolved
                .identity_files
                .iter()
                .filter_map(|f| {
                    shellexpand::full(f)
                        .ok()
                        .map(|e| PathBuf::from(e.into_owned()))
                })
                .find(|p| p.is_file());
            if let Some(pj) = resolved.proxy_jump.as_deref().and_then(jump_alias) {
                jumps.push((alias.clone(), pj));
            }
            self.hosts.insert(
                alias,
                Host {
                    addr,
                    user,
                    port,
                    auth: if key.is_some() {
                        AuthMethod::Key
                    } else {
                        AuthMethod::Agent
                    },
                    key,
                    keys: None,
                    guards: None,
                    known_host_fingerprint: None,
                    proxy_jump: None,
                },
            );
        }
        for (alias, target) in jumps {
            // Only wire a jump we can actually reach: the bastion has to be a
            // host in the map, and the chain must stay acyclic or validate()
            // would reject the whole config over an imported side file.
            if alias == target || !self.hosts.contains_key(&target) {
                continue;
            }
            if self.jump_would_cycle(&alias, &target) {
                continue;
            }
            if let Some(h) = self.hosts.get_mut(&alias) {
                h.proxy_jump = Some(target);
            }
        }
    }

    /// True if pointing `from`'s proxy_jump at `to` would close a loop.
    fn jump_would_cycle(&self, from: &str, to: &str) -> bool {
        let mut cur = to;
        for _ in 0..self.hosts.len() + 1 {
            if cur == from {
                return true;
            }
            match self.hosts.get(cur).and_then(|h| h.proxy_jump.as_deref()) {
                Some(next) => cur = next,
                None => return false,
            }
        }
        true
    }
}

/// Stat a configured private key so a typo surfaces as a config error at
/// startup instead of an opaque `AuthFailed` on the first call.
fn check_key_file(host: &str, path: &Path) -> Result<()> {
    let meta = std::fs::metadata(path).map_err(|e| {
        SshError::Config(format!(
            "host '{host}': key '{}' is unreadable: {e}",
            path.display()
        ))
    })?;
    if !meta.is_file() {
        return Err(SshError::Config(format!(
            "host '{host}': key '{}' is not a regular file",
            path.display()
        )));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = meta.permissions().mode() & 0o077;
        if mode != 0 {
            tracing::warn!(
                host = %host,
                path = %path.display(),
                mode = format!("{:04o}", meta.permissions().mode() & 0o7777),
                "private key is group- or world-accessible; chmod 600 it"
            );
        }
    }
    Ok(())
}

/// A pasted `ssh-keygen -l` line ("256 SHA256:abc… user@host (ED25519)") or an
/// MD5 fingerprint would never match and reads like a MITM at connect time.
/// Reject the shape here, where the message can say what was expected.
fn check_fingerprint(host: &str, fp: &str) -> Result<()> {
    const SHAPE: &str = "expected 'SHA256:<43 base64 chars>' — \
                         the bare second field of `ssh-keygen -lf <key>`, no bits, no comment";
    let Some(body) = fp.strip_prefix("SHA256:") else {
        return Err(SshError::Config(format!(
            "host '{host}': known_host_fingerprint '{fp}' has no SHA256: prefix — {SHAPE}"
        )));
    };
    let body = body.trim_end_matches('=');
    let ok = body.len() == 43
        && body
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/');
    if !ok {
        return Err(SshError::Config(format!(
            "host '{host}': known_host_fingerprint '{fp}' is not a base64 SHA-256 digest — {SHAPE}"
        )));
    }
    Ok(())
}

/// `hosts.toml` carries the host inventory and private key paths. The `0700`
/// on the config dir only happens when the audit log is enabled, so check the
/// file itself. Warn rather than refuse: the user may have deliberate ACLs.
fn warn_if_world_readable(path: &Path, label: &str) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = std::fs::metadata(path) {
            let mode = meta.permissions().mode();
            if mode & 0o077 != 0 {
                tracing::warn!(
                    path = %path.display(),
                    mode = format!("{:04o}", mode & 0o7777),
                    "{label} is group- or world-readable; chmod 600 it"
                );
            }
        }
    }
    #[cfg(not(unix))]
    {
        let _ = (path, label);
    }
}

/// Reduces an OpenSSH `ProxyJump` value to a bare alias we can look up:
/// takes the first hop of a comma-separated chain and drops any `user@` and
/// `:port` decoration. `none` disables the jump.
fn jump_alias(value: &str) -> Option<String> {
    let first = value.split(',').next()?.trim();
    if first.is_empty() || first.eq_ignore_ascii_case("none") {
        return None;
    }
    let host = first.rsplit('@').next()?;
    let host = match host.rsplit_once(':') {
        // Only strip a numeric port; keeps IPv6-ish values intact.
        Some((h, port)) if !h.is_empty() && port.chars().all(|c| c.is_ascii_digit()) => h,
        _ => host,
    };
    if host.is_empty() {
        None
    } else {
        Some(host.to_string())
    }
}

pub fn default_deny_patterns() -> Vec<NamedPattern> {
    DEFAULT_DENY
        .iter()
        .map(|(n, p)| NamedPattern {
            name: (*n).into(),
            pattern: (*p).into(),
        })
        .collect()
}

pub fn default_confirm_patterns() -> Vec<NamedPattern> {
    DEFAULT_CONFIRM
        .iter()
        .map(|(n, p)| NamedPattern {
            name: (*n).into(),
            pattern: (*p).into(),
        })
        .collect()
}

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

    #[test]
    fn parse_duration_units() {
        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
        assert_eq!(parse_duration("15m").unwrap(), Duration::from_secs(900));
        assert_eq!(parse_duration("2h").unwrap(), Duration::from_secs(7200));
        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
        assert!(parse_duration("xyz").is_err());
    }

    #[test]
    fn parse_minimal_toml() {
        let raw = r#"
            [host.test]
            addr = "1.2.3.4"
            user = "root"
        "#;
        let c: Config = toml::from_str(raw).unwrap();
        assert_eq!(c.hosts.len(), 1);
        let h = &c.hosts["test"];
        assert_eq!(h.port, 22);
        assert_eq!(h.user, "root");
        assert!(matches!(h.auth, AuthMethod::Key));
    }

    #[test]
    fn validate_rejects_unknown_default_host() {
        let raw = r#"
            [defaults]
            default_host = "nope"

            [host.real]
            addr = "1.2.3.4"
            user = "root"
        "#;
        let c: Config = toml::from_str(raw).unwrap();
        let err = c.validate().unwrap_err();
        assert!(err.to_string().contains("default_host"), "got: {err}");
    }

    #[test]
    fn validate_rejects_auth_key_without_key() {
        let raw = r#"
            [host.k]
            addr = "1.2.3.4"
            user = "root"
            auth = "key"
        "#;
        let c: Config = toml::from_str(raw).unwrap();
        let err = c.validate().unwrap_err();
        assert!(err.to_string().contains("auth"), "got: {err}");
    }

    /// Writes two throwaway key files and returns a config referencing them.
    fn cfg_with_keys(dir: &tempfile::TempDir) -> Config {
        let a = dir.path().join("a");
        let b = dir.path().join("b");
        std::fs::write(&a, "k").unwrap();
        std::fs::write(&b, "k").unwrap();
        let raw = format!(
            r#"
            [host.k]
            addr = "1.2.3.4"
            user = "root"
            auth = "key"
            keys = [{:?}, {:?}]
        "#,
            a.to_string_lossy(),
            b.to_string_lossy()
        );
        toml::from_str(&raw).unwrap()
    }

    #[test]
    fn validate_accepts_multi_keys() {
        let dir = tempfile::tempdir().unwrap();
        let c = cfg_with_keys(&dir);
        c.validate().expect("ok");
        let h = &c.hosts["k"];
        assert_eq!(h.all_keys().len(), 2);
    }

    #[test]
    fn validate_rejects_missing_key_file() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("nope");
        let raw = format!(
            r#"
            [host.k]
            addr = "1.2.3.4"
            user = "root"
            auth = "key"
            key = {:?}
        "#,
            missing.to_string_lossy()
        );
        let c: Config = toml::from_str(&raw).unwrap();
        let err = c.validate().unwrap_err();
        assert!(err.to_string().contains("unreadable"), "got: {err}");
    }

    #[test]
    fn validate_rejects_key_that_is_a_directory() {
        let dir = tempfile::tempdir().unwrap();
        let raw = format!(
            r#"
            [host.k]
            addr = "1.2.3.4"
            user = "root"
            auth = "key"
            key = {:?}
        "#,
            dir.path().to_string_lossy()
        );
        let c: Config = toml::from_str(&raw).unwrap();
        let err = c.validate().unwrap_err();
        assert!(err.to_string().contains("regular file"), "got: {err}");
    }

    #[test]
    fn validate_ignores_key_path_for_agent_auth() {
        let raw = r#"
            [host.k]
            addr = "1.2.3.4"
            user = "root"
            auth = "agent"
            key = "/definitely/not/here"
        "#;
        let c: Config = toml::from_str(raw).unwrap();
        c.validate().expect("agent auth never reads the key path");
    }

    fn cfg_with_fingerprint(fp: &str) -> Config {
        let raw = format!(
            r#"
            [host.k]
            addr = "1.2.3.4"
            user = "root"
            auth = "agent"
            known_host_fingerprint = "{fp}"
        "#
        );
        toml::from_str(&raw).unwrap()
    }

    #[test]
    fn validate_accepts_well_formed_fingerprint() {
        let fp = format!("SHA256:{}", "A".repeat(43));
        cfg_with_fingerprint(&fp).validate().expect("ok");
    }

    #[test]
    fn validate_rejects_md5_fingerprint() {
        let c = cfg_with_fingerprint("MD5:aa:bb:cc:dd");
        let err = c.validate().unwrap_err();
        assert!(err.to_string().contains("SHA256:"), "got: {err}");
    }

    #[test]
    fn validate_rejects_fingerprint_with_comment() {
        let fp = format!("SHA256:{} user@host (ED25519)", "A".repeat(43));
        let c = cfg_with_fingerprint(&fp);
        let err = c.validate().unwrap_err();
        assert!(err.to_string().contains("base64"), "got: {err}");
    }

    #[test]
    fn parse_duration_rejects_overflow() {
        assert!(parse_duration("999999999999999999d").is_err());
        assert!(parse_duration("18446744073709551615h").is_err());
        assert_eq!(parse_duration("1d").unwrap(), Duration::from_secs(86400));
    }

    #[test]
    fn import_ssh_config_is_opt_in() {
        let c: Config = toml::from_str("").unwrap();
        assert!(!c.defaults.import_ssh_config);
        assert!(!Defaults::default().import_ssh_config);
    }

    #[test]
    fn audit_rotation_defaults() {
        let c: Config = toml::from_str("").unwrap();
        assert_eq!(c.defaults.audit_max_bytes, 16 * 1024 * 1024);
        assert_eq!(c.defaults.audit_keep_files, 5);
    }

    #[test]
    fn parse_full_toml() {
        let raw = r#"
            [defaults]
            output = "json"
            session_idle_timeout = "5m"

            [host.box1]
            addr = "10.0.0.1"
            user = "ops"
            port = 2222
            auth = "agent"
        "#;
        let c: Config = toml::from_str(raw).unwrap();
        assert_eq!(c.defaults.output, OutputFmt::Json);
        assert_eq!(c.defaults.session_idle_timeout.0, Duration::from_secs(300));
        assert_eq!(c.hosts["box1"].port, 2222);
        assert!(matches!(c.hosts["box1"].auth, AuthMethod::Agent));
    }
}