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
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

use super::model::{
    ConfigElement, Directive, HostBlock, IncludeDirective, IncludedFile, SshConfigFile,
};

const MAX_INCLUDE_DEPTH: usize = 5;

impl SshConfigFile {
    /// Parse an SSH config file from the given path.
    /// Preserves all formatting, comments, and unknown directives for round-trip fidelity.
    pub fn parse(path: &Path) -> Result<Self> {
        Self::parse_with_depth(path, 0)
    }

    fn parse_with_depth(path: &Path, depth: usize) -> Result<Self> {
        let content = if path.exists() {
            std::fs::read_to_string(path)
                .with_context(|| format!("Failed to read SSH config at {}", path.display()))?
        } else {
            String::new()
        };

        let crlf = content.contains("\r\n");
        let config_dir = path.parent().map(|p| p.to_path_buf());
        let elements = Self::parse_content_with_includes(&content, config_dir.as_deref(), depth);

        Ok(SshConfigFile {
            elements,
            path: path.to_path_buf(),
            crlf,
        })
    }

    /// Parse SSH config content from a string (without Include resolution).
    /// Used by tests to create SshConfigFile from inline strings.
    #[allow(dead_code)]
    pub fn parse_content(content: &str) -> Vec<ConfigElement> {
        Self::parse_content_with_includes(content, None, MAX_INCLUDE_DEPTH)
    }

    /// Parse SSH config content, optionally resolving Include directives.
    fn parse_content_with_includes(
        content: &str,
        config_dir: Option<&Path>,
        depth: usize,
    ) -> Vec<ConfigElement> {
        let mut elements = Vec::new();
        let mut current_block: Option<HostBlock> = None;

        for line in content.lines() {
            let trimmed = line.trim();

            // Check for Include directive.
            // An indented Include inside a Host block is preserved as a directive
            // (not a top-level Include). A non-indented Include flushes the block.
            let is_indented = line.starts_with(' ') || line.starts_with('\t');
            if !(current_block.is_some() && is_indented) {
                if let Some(pattern) = Self::parse_include_line(trimmed) {
                    if let Some(block) = current_block.take() {
                        elements.push(ConfigElement::HostBlock(block));
                    }
                    let resolved = if depth < MAX_INCLUDE_DEPTH {
                        Self::resolve_include(pattern, config_dir, depth)
                    } else {
                        Vec::new()
                    };
                    elements.push(ConfigElement::Include(IncludeDirective {
                        raw_line: line.to_string(),
                        pattern: pattern.to_string(),
                        resolved_files: resolved,
                    }));
                    continue;
                }
            }

            // Non-indented Match line = block boundary (flush current Host block).
            // Match blocks are stored as GlobalLines (inert, never edited/deleted).
            if !is_indented && Self::is_match_line(trimmed) {
                if let Some(block) = current_block.take() {
                    elements.push(ConfigElement::HostBlock(block));
                }
                elements.push(ConfigElement::GlobalLine(line.to_string()));
                continue;
            }

            // Check if this line starts a new Host block
            if let Some(pattern) = Self::parse_host_line(trimmed) {
                // Flush the previous block if any
                if let Some(block) = current_block.take() {
                    elements.push(ConfigElement::HostBlock(block));
                }
                current_block = Some(HostBlock {
                    host_pattern: pattern,
                    raw_host_line: line.to_string(),
                    directives: Vec::new(),
                });
                continue;
            }

            // If we're inside a Host block, add this line as a directive
            if let Some(ref mut block) = current_block {
                if trimmed.is_empty() || trimmed.starts_with('#') {
                    // Comment or blank line inside a host block
                    block.directives.push(Directive {
                        key: String::new(),
                        value: String::new(),
                        raw_line: line.to_string(),
                        is_non_directive: true,
                    });
                } else if let Some((key, value)) = Self::parse_directive(trimmed) {
                    block.directives.push(Directive {
                        key,
                        value,
                        raw_line: line.to_string(),
                        is_non_directive: false,
                    });
                } else {
                    // Unrecognized line format — preserve verbatim
                    block.directives.push(Directive {
                        key: String::new(),
                        value: String::new(),
                        raw_line: line.to_string(),
                        is_non_directive: true,
                    });
                }
            } else {
                // Global line (before any Host block)
                elements.push(ConfigElement::GlobalLine(line.to_string()));
            }
        }

        // Flush the last block
        if let Some(block) = current_block {
            elements.push(ConfigElement::HostBlock(block));
        }

        elements
    }

    /// Parse an Include directive line. Returns the pattern if it matches.
    /// Handles both space and tab between keyword and value (SSH allows either).
    fn parse_include_line(trimmed: &str) -> Option<&str> {
        let bytes = trimmed.as_bytes();
        // "include" is 7 ASCII bytes; byte 7 must be ASCII whitespace (space or tab)
        if bytes.len() > 8
            && bytes[..7].eq_ignore_ascii_case(b"include")
            && bytes[7].is_ascii_whitespace()
        {
            // byte 8 is safe to slice at: bytes 0-7 are ASCII, so byte 8 is a char boundary
            let pattern = trimmed[8..].trim();
            if !pattern.is_empty() {
                return Some(pattern);
            }
        }
        None
    }

    /// Resolve an Include pattern to a list of included files.
    /// Supports multiple space-separated patterns on one line (SSH spec).
    fn resolve_include(
        pattern: &str,
        config_dir: Option<&Path>,
        depth: usize,
    ) -> Vec<IncludedFile> {
        let mut files = Vec::new();
        let mut seen = std::collections::HashSet::new();

        for single in pattern.split_whitespace() {
            let expanded = Self::expand_tilde(single);

            // If relative path, resolve against config dir
            let glob_pattern = if expanded.starts_with('/') {
                expanded
            } else if let Some(dir) = config_dir {
                dir.join(&expanded).to_string_lossy().to_string()
            } else {
                continue;
            };

            if let Ok(paths) = glob::glob(&glob_pattern) {
                let mut matched: Vec<PathBuf> = paths.filter_map(|p| p.ok()).collect();
                matched.sort();
                for path in matched {
                    if path.is_file() && seen.insert(path.clone()) {
                        match std::fs::read_to_string(&path) {
                            Ok(content) => {
                                let elements = Self::parse_content_with_includes(
                                    &content,
                                    path.parent(),
                                    depth + 1,
                                );
                                files.push(IncludedFile {
                                    path: path.clone(),
                                    elements,
                                });
                            }
                            Err(e) => {
                                eprintln!(
                                    "! Could not read Include file {}: {}",
                                    path.display(),
                                    e
                                );
                            }
                        }
                    }
                }
            }
        }
        files
    }

    /// Expand ~ to the home directory.
    pub(crate) fn expand_tilde(pattern: &str) -> String {
        if let Some(rest) = pattern.strip_prefix("~/") {
            if let Some(home) = dirs::home_dir() {
                return format!("{}/{}", home.display(), rest);
            }
        }
        pattern.to_string()
    }

    /// Check if a line is a "Host <pattern>" line.
    /// Returns the pattern if it is.
    /// Handles both space and tab between keyword and value (SSH allows either).
    /// Strips inline comments (`# ...` preceded by whitespace) from the pattern.
    fn parse_host_line(trimmed: &str) -> Option<String> {
        // Split on first space or tab to isolate the keyword
        let mut parts = trimmed.splitn(2, [' ', '\t']);
        let keyword = parts.next()?;
        if !keyword.eq_ignore_ascii_case("host") {
            return None;
        }
        // "hostname" splits as keyword="hostname" which fails the check above
        let raw_pattern = parts.next()?.trim();
        let pattern = strip_inline_comment(raw_pattern).to_string();
        if !pattern.is_empty() {
            return Some(pattern);
        }
        None
    }

    /// Check if a line is a "Match ..." line (block boundary).
    fn is_match_line(trimmed: &str) -> bool {
        let mut parts = trimmed.splitn(2, [' ', '\t']);
        let keyword = parts.next().unwrap_or("");
        keyword.eq_ignore_ascii_case("match")
    }

    /// Parse a "Key Value" directive line.
    /// Matches OpenSSH behavior: keyword ends at first whitespace or `=`.
    /// An `=` in the value portion (e.g. `IdentityFile ~/.ssh/id=prod`) is
    /// NOT treated as a separator.
    fn parse_directive(trimmed: &str) -> Option<(String, String)> {
        // Find end of keyword: first whitespace or '='
        let key_end = trimmed.find(|c: char| c.is_whitespace() || c == '=')?;
        let key = &trimmed[..key_end];
        if key.is_empty() {
            return None;
        }

        // Skip whitespace, optional '=', and more whitespace after the keyword
        let rest = trimmed[key_end..].trim_start();
        let rest = rest.strip_prefix('=').unwrap_or(rest);
        let value = rest.trim_start();

        // Strip inline comments (# preceded by whitespace) from parsed value,
        // but only outside quoted strings. Raw_line is untouched for round-trip fidelity.
        let value = strip_inline_comment(value);

        Some((key.to_string(), value.to_string()))
    }
}

/// Strip an inline comment (`# ...` preceded by whitespace) from a parsed value,
/// respecting double-quoted strings.
fn strip_inline_comment(value: &str) -> &str {
    let bytes = value.as_bytes();
    let mut in_quote = false;
    for i in 0..bytes.len() {
        if bytes[i] == b'"' {
            in_quote = !in_quote;
        } else if !in_quote
            && bytes[i] == b'#'
            && i > 0
            && (bytes[i - 1] == b' ' || bytes[i - 1] == b'\t')
        {
            return value[..i].trim_end();
        }
    }
    value
}

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

    fn parse_str(content: &str) -> SshConfigFile {
        SshConfigFile {
            elements: SshConfigFile::parse_content(content),
            path: PathBuf::from("/tmp/test_config"),
            crlf: content.contains("\r\n"),
        }
    }

    #[test]
    fn test_empty_config() {
        let config = parse_str("");
        assert!(config.host_entries().is_empty());
    }

    #[test]
    fn test_basic_host() {
        let config = parse_str(
            "Host myserver\n  HostName 192.168.1.10\n  User admin\n  Port 2222\n",
        );
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].alias, "myserver");
        assert_eq!(entries[0].hostname, "192.168.1.10");
        assert_eq!(entries[0].user, "admin");
        assert_eq!(entries[0].port, 2222);
    }

    #[test]
    fn test_multiple_hosts() {
        let content = "\
Host alpha
  HostName alpha.example.com
  User deploy

Host beta
  HostName beta.example.com
  User root
  Port 22022
";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].alias, "alpha");
        assert_eq!(entries[1].alias, "beta");
        assert_eq!(entries[1].port, 22022);
    }

    #[test]
    fn test_wildcard_host_filtered() {
        let content = "\
Host *
  ServerAliveInterval 60

Host myserver
  HostName 10.0.0.1
";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].alias, "myserver");
    }

    #[test]
    fn test_comments_preserved() {
        let content = "\
# Global comment
Host myserver
  # This is a comment
  HostName 10.0.0.1
  User admin
";
        let config = parse_str(content);
        // Check that the global comment is preserved
        assert!(matches!(&config.elements[0], ConfigElement::GlobalLine(s) if s == "# Global comment"));
        // Check that the host block has the comment directive
        if let ConfigElement::HostBlock(block) = &config.elements[1] {
            assert!(block.directives[0].is_non_directive);
            assert_eq!(block.directives[0].raw_line, "  # This is a comment");
        } else {
            panic!("Expected HostBlock");
        }
    }

    #[test]
    fn test_identity_file_and_proxy_jump() {
        let content = "\
Host bastion
  HostName bastion.example.com
  User admin
  IdentityFile ~/.ssh/id_ed25519
  ProxyJump gateway
";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries[0].identity_file, "~/.ssh/id_ed25519");
        assert_eq!(entries[0].proxy_jump, "gateway");
    }

    #[test]
    fn test_unknown_directives_preserved() {
        let content = "\
Host myserver
  HostName 10.0.0.1
  ForwardAgent yes
  LocalForward 8080 localhost:80
";
        let config = parse_str(content);
        if let ConfigElement::HostBlock(block) = &config.elements[0] {
            assert_eq!(block.directives.len(), 3);
            assert_eq!(block.directives[1].key, "ForwardAgent");
            assert_eq!(block.directives[1].value, "yes");
            assert_eq!(block.directives[2].key, "LocalForward");
        } else {
            panic!("Expected HostBlock");
        }
    }

    #[test]
    fn test_include_directive_parsed() {
        let content = "\
Include config.d/*

Host myserver
  HostName 10.0.0.1
";
        let config = parse_str(content);
        // parse_content uses no config_dir, so Include resolves to no files
        assert!(matches!(&config.elements[0], ConfigElement::Include(inc) if inc.raw_line == "Include config.d/*"));
        // Blank line becomes a GlobalLine between Include and HostBlock
        assert!(matches!(&config.elements[1], ConfigElement::GlobalLine(s) if s.is_empty()));
        assert!(matches!(&config.elements[2], ConfigElement::HostBlock(_)));
    }

    #[test]
    fn test_include_round_trip() {
        let content = "\
Include ~/.ssh/config.d/*

Host myserver
  HostName 10.0.0.1
";
        let config = parse_str(content);
        assert_eq!(config.serialize(), content);
    }

    #[test]
    fn test_ssh_command() {
        use crate::ssh_config::model::HostEntry;
        let entry = HostEntry {
            alias: "myserver".to_string(),
            hostname: "10.0.0.1".to_string(),
            ..Default::default()
        };
        assert_eq!(entry.ssh_command(), "ssh -- 'myserver'");
    }

    #[test]
    fn test_unicode_comment_no_panic() {
        // "# abcdeé" has byte 8 mid-character (é starts at byte 7, is 2 bytes)
        // This must not panic in parse_include_line
        let content = "# abcde\u{00e9} test\n\nHost myserver\n  HostName 10.0.0.1\n";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].alias, "myserver");
    }

    #[test]
    fn test_unicode_multibyte_line_no_panic() {
        // Three 3-byte CJK characters: byte 8 falls mid-character
        let content = "# \u{3042}\u{3042}\u{3042}xyz\n\nHost myserver\n  HostName 10.0.0.1\n";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn test_host_with_tab_separator() {
        let content = "Host\tmyserver\n  HostName 10.0.0.1\n";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].alias, "myserver");
    }

    #[test]
    fn test_include_with_tab_separator() {
        let content = "Include\tconfig.d/*\n\nHost myserver\n  HostName 10.0.0.1\n";
        let config = parse_str(content);
        assert!(matches!(&config.elements[0], ConfigElement::Include(inc) if inc.pattern == "config.d/*"));
    }

    #[test]
    fn test_hostname_not_confused_with_host() {
        // "HostName" should not be parsed as a Host line
        let content = "Host myserver\n  HostName example.com\n";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].hostname, "example.com");
    }

    #[test]
    fn test_equals_in_value_not_treated_as_separator() {
        let content = "Host myserver\n  IdentityFile ~/.ssh/id=prod\n";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].identity_file, "~/.ssh/id=prod");
    }

    #[test]
    fn test_equals_syntax_key_value() {
        let content = "Host myserver\n  HostName=10.0.0.1\n  User = admin\n";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].hostname, "10.0.0.1");
        assert_eq!(entries[0].user, "admin");
    }

    #[test]
    fn test_inline_comment_inside_quotes_preserved() {
        let content = "Host myserver\n  ProxyCommand ssh -W \"%h #test\" gateway\n";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        // The value should preserve the # inside quotes
        if let ConfigElement::HostBlock(block) = &config.elements[0] {
            let proxy_cmd = block.directives.iter().find(|d| d.key == "ProxyCommand").unwrap();
            assert_eq!(proxy_cmd.value, "ssh -W \"%h #test\" gateway");
        } else {
            panic!("Expected HostBlock");
        }
    }

    #[test]
    fn test_inline_comment_outside_quotes_stripped() {
        let content = "Host myserver\n  HostName 10.0.0.1 # production\n";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries[0].hostname, "10.0.0.1");
    }

    #[test]
    fn test_host_inline_comment_stripped() {
        let content = "Host alpha # this is a comment\n  HostName 10.0.0.1\n";
        let config = parse_str(content);
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].alias, "alpha");
        // Raw line is preserved for round-trip fidelity
        if let ConfigElement::HostBlock(block) = &config.elements[0] {
            assert_eq!(block.raw_host_line, "Host alpha # this is a comment");
            assert_eq!(block.host_pattern, "alpha");
        } else {
            panic!("Expected HostBlock");
        }
    }

    #[test]
    fn test_match_block_is_global_line() {
        let content = "\
Host myserver
  HostName 10.0.0.1

Match host *.example.com
  ForwardAgent yes
";
        let config = parse_str(content);
        // Match line should flush the Host block and become a GlobalLine
        let host_count = config.elements.iter().filter(|e| matches!(e, ConfigElement::HostBlock(_))).count();
        assert_eq!(host_count, 1);
        // Match line itself
        assert!(config.elements.iter().any(|e| matches!(e, ConfigElement::GlobalLine(s) if s == "Match host *.example.com")));
        // Indented lines after Match (no current_block) become GlobalLines
        assert!(config.elements.iter().any(|e| matches!(e, ConfigElement::GlobalLine(s) if s.contains("ForwardAgent"))));
    }

    #[test]
    fn test_match_block_survives_host_deletion() {
        let content = "\
Host myserver
  HostName 10.0.0.1

Match host *.example.com
  ForwardAgent yes

Host other
  HostName 10.0.0.2
";
        let mut config = parse_str(content);
        config.delete_host("myserver");
        let output = config.serialize();
        assert!(output.contains("Match host *.example.com"));
        assert!(output.contains("ForwardAgent yes"));
        assert!(output.contains("Host other"));
        assert!(!output.contains("Host myserver"));
    }

    #[test]
    fn test_match_block_round_trip() {
        let content = "\
Host myserver
  HostName 10.0.0.1

Match host *.example.com
  ForwardAgent yes
";
        let config = parse_str(content);
        assert_eq!(config.serialize(), content);
    }

    #[test]
    fn test_match_at_start_of_file() {
        let content = "\
Match all
  ServerAliveInterval 60

Host myserver
  HostName 10.0.0.1
";
        let config = parse_str(content);
        assert!(matches!(&config.elements[0], ConfigElement::GlobalLine(s) if s == "Match all"));
        assert!(matches!(&config.elements[1], ConfigElement::GlobalLine(s) if s.contains("ServerAliveInterval")));
        let entries = config.host_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].alias, "myserver");
    }

    #[test]
    fn test_host_multi_pattern_with_inline_comment() {
        // Multi-pattern host with inline comment: "prod staging # servers"
        // The comment should be stripped, but "prod staging" is still multi-pattern
        // and gets filtered by host_entries()
        let content = "Host prod staging # servers\n  HostName 10.0.0.1\n";
        let config = parse_str(content);
        if let ConfigElement::HostBlock(block) = &config.elements[0] {
            assert_eq!(block.host_pattern, "prod staging");
        } else {
            panic!("Expected HostBlock");
        }
        // Multi-pattern hosts are filtered out of host_entries
        assert_eq!(config.host_entries().len(), 0);
    }
}