purple-ssh 1.24.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), 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
use std::io::BufRead;
use std::path::Path;

use crate::quick_add;
use crate::ssh_config::model::{HostEntry, SshConfigFile};

/// Import hosts from a file with one `[user@]host[:port]` per line.
/// Returns (imported, skipped, parse_failures, read_errors).
pub fn import_from_file(
    config: &mut SshConfigFile,
    path: &Path,
    group: Option<&str>,
) -> Result<(usize, usize, usize, usize), String> {
    let file =
        std::fs::File::open(path).map_err(|e| format!("Can't open {}: {}", path.display(), e))?;
    let reader = std::io::BufReader::new(file);

    let mut read_errors = 0;
    let mut parse_failures = 0;
    let lines: Vec<String> = reader
        .lines()
        .filter_map(|r| match r {
            Ok(line) => Some(line),
            Err(_) => {
                read_errors += 1;
                None
            }
        })
        .filter(|line| {
            let trimmed = line.trim();
            !trimmed.is_empty() && !trimmed.starts_with('#')
        })
        .collect();

    let mut entries = Vec::new();
    for line in &lines {
        let trimmed = line.trim();
        match quick_add::parse_target(trimmed) {
            Ok(parsed) => {
                let alias = parsed
                    .hostname
                    .split('.')
                    .next()
                    .unwrap_or(&parsed.hostname)
                    .to_string();
                entries.push(HostEntry {
                    alias,
                    hostname: parsed.hostname,
                    user: parsed.user,
                    port: parsed.port,
                    ..Default::default()
                });
            }
            Err(_) => {
                parse_failures += 1;
            }
        }
    }

    let (imported, skipped) = add_entries(config, &entries, group)?;
    Ok((imported, skipped, parse_failures, read_errors))
}

/// Import hosts from ~/.ssh/known_hosts.
/// Returns (imported, skipped, parse_failures, read_errors).
pub fn import_from_known_hosts(
    config: &mut SshConfigFile,
    group: Option<&str>,
) -> Result<(usize, usize, usize, usize), String> {
    let home = dirs::home_dir().ok_or("Could not determine home directory.")?;
    let known_hosts_path = home.join(".ssh").join("known_hosts");

    if !known_hosts_path.exists() {
        return Err("~/.ssh/known_hosts not found.".to_string());
    }

    let file = std::fs::File::open(&known_hosts_path)
        .map_err(|e| format!("Can't open known_hosts: {}", e))?;
    let reader = std::io::BufReader::new(file);

    let mut read_errors = 0;
    let mut parse_failures = 0;
    let lines: Vec<String> = reader
        .lines()
        .filter_map(|r| match r {
            Ok(line) => Some(line),
            Err(_) => {
                read_errors += 1;
                None
            }
        })
        .filter(|line| {
            let trimmed = line.trim();
            !trimmed.is_empty() && !trimmed.starts_with('#')
        })
        .collect();

    let mut entries = Vec::new();
    for line in &lines {
        match parse_known_hosts_line(line) {
            KnownHostResult::Parsed(entry) => entries.push(entry),
            KnownHostResult::Skipped => {} // Intentional skip (hashed, marker, IP-only, wildcard)
            KnownHostResult::Failed => parse_failures += 1,
        }
    }

    let (imported, skipped) = add_entries(config, &entries, group)?;
    Ok((imported, skipped, parse_failures, read_errors))
}

/// Check if a hostname is a bare IP address (not an FQDN).
fn is_bare_ip(host: &str) -> bool {
    // IPv4: digits and dots only (e.g., "192.168.1.1")
    if !host.is_empty() && host.chars().all(|c| c.is_ascii_digit() || c == '.') {
        return true;
    }
    // IPv6: hex digits + colons + optional zone ID (e.g., "2001:db8::1", "fe80::1%en0")
    let ipv6_part = host.split('%').next().unwrap_or(host);
    ipv6_part.contains(':') && ipv6_part.chars().all(|c| c.is_ascii_hexdigit() || c == ':')
}

/// Result of parsing a known_hosts line.
#[allow(clippy::large_enum_variant)]
enum KnownHostResult {
    /// Successfully parsed into a HostEntry.
    Parsed(HostEntry),
    /// Intentionally skipped (hashed, marker, IP-only, wildcard).
    Skipped,
    /// Failed to parse (malformed line).
    Failed,
}

/// Parse a single known_hosts line into a HostEntry.
fn parse_known_hosts_line(line: &str) -> KnownHostResult {
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() < 3 {
        return KnownHostResult::Failed;
    }

    // Skip marker lines (@cert-authority, @revoked)
    if parts[0].starts_with('@') {
        return KnownHostResult::Skipped;
    }
    let host_part = parts[0];

    // Skip hashed entries (start with |)
    if host_part.starts_with('|') {
        return KnownHostResult::Skipped;
    }

    // Pick first non-IP host from comma-separated list.
    // known_hosts may have ip,hostname or hostname,ip pairs.
    let host = host_part
        .split(',')
        .find(|entry| {
            let bare = if entry.starts_with('[') {
                entry
                    .get(1..entry.find(']').unwrap_or(entry.len()))
                    .unwrap_or(entry)
            } else {
                entry
            };
            !is_bare_ip(bare)
        })
        .unwrap_or_else(|| host_part.split(',').next().unwrap_or(host_part));

    // Handle [host]:port format
    let (hostname, port) = if host.starts_with('[') {
        let Some(end) = host.find(']') else {
            return KnownHostResult::Failed;
        };
        let h = &host[1..end];
        let rest = &host[end + 1..];
        let p = if rest.is_empty() {
            22
        } else if let Some(port_str) = rest.strip_prefix(':') {
            if port_str.is_empty() {
                return KnownHostResult::Failed; // [host]: with no port
            }
            match port_str.parse::<u16>() {
                Ok(port) if port > 0 => port,
                _ => return KnownHostResult::Failed,
            }
        } else {
            return KnownHostResult::Failed; // [host]junk with no colon
        };
        (h.to_string(), p)
    } else {
        (host.to_string(), 22)
    };

    // Skip empty hostname
    if hostname.is_empty() {
        return KnownHostResult::Failed;
    }

    // Skip bare IP addresses (not FQDNs) before alias extraction.
    if is_bare_ip(&hostname) {
        return KnownHostResult::Skipped;
    }

    let alias = hostname
        .split('.')
        .next()
        .unwrap_or(&hostname)
        .to_string();

    // Skip wildcard/pattern entries
    if crate::ssh_config::model::is_host_pattern(&alias) {
        return KnownHostResult::Skipped;
    }

    KnownHostResult::Parsed(HostEntry {
        alias,
        hostname,
        port,
        ..Default::default()
    })
}

/// Add entries to config, skipping exact alias duplicates.
fn add_entries(
    config: &mut SshConfigFile,
    entries: &[HostEntry],
    group: Option<&str>,
) -> Result<(usize, usize), String> {
    let mut imported = 0;
    let mut skipped = 0;
    let mut header_written = false;

    for entry in entries {
        if config.has_host(&entry.alias) {
            skipped += 1;
            continue;
        }

        // Write group header before the first actually-imported host
        if let Some(group_name) = group.filter(|_| !header_written) {
            if !config.elements.is_empty() && !config.last_element_has_trailing_blank() {
                config.elements.push(
                    crate::ssh_config::model::ConfigElement::GlobalLine(String::new()),
                );
            }
            config.elements.push(
                crate::ssh_config::model::ConfigElement::GlobalLine(format!("# {}", group_name)),
            );
            header_written = true;
        }

        if group.is_some() && imported == 0 {
            // Push first host directly after group comment (no blank separator between them)
            let block = SshConfigFile::entry_to_block(entry);
            config
                .elements
                .push(crate::ssh_config::model::ConfigElement::HostBlock(block));
        } else {
            config.add_host(entry);
        }
        imported += 1;
    }

    Ok((imported, skipped))
}


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

    #[test]
    fn test_parse_known_hosts_simple() {
        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("example.com ssh-rsa AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.hostname, "example.com");
        assert_eq!(entry.alias, "example");
        assert_eq!(entry.port, 22);
    }

    #[test]
    fn test_parse_known_hosts_with_port() {
        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("[myhost.com]:2222 ssh-ed25519 AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.hostname, "myhost.com");
        assert_eq!(entry.alias, "myhost");
        assert_eq!(entry.port, 2222);
    }

    #[test]
    fn test_parse_known_hosts_hashed() {
        assert!(matches!(
            parse_known_hosts_line("|1|abc=|def= ssh-rsa AAAA..."),
            KnownHostResult::Skipped
        ));
    }

    #[test]
    fn test_parse_known_hosts_ip_only() {
        assert!(matches!(
            parse_known_hosts_line("192.168.1.1 ssh-rsa AAAA..."),
            KnownHostResult::Skipped
        ));
    }

    #[test]
    fn test_parse_known_hosts_ipv6_skipped() {
        // Bare IPv6 addresses should be skipped (hex digits + colons)
        assert!(matches!(
            parse_known_hosts_line("2001:db8::1 ssh-rsa AAAA..."),
            KnownHostResult::Skipped
        ));
        assert!(matches!(
            parse_known_hosts_line("fe80::1 ssh-ed25519 AAAA..."),
            KnownHostResult::Skipped
        ));
    }

    #[test]
    fn test_parse_known_hosts_hex_hostname_not_skipped() {
        // Pure hex hostnames without colons are valid hostnames, not IPs
        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("deadbeef ssh-rsa AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.alias, "deadbeef");

        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("cafe.example.com ssh-rsa AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.alias, "cafe");
    }

    #[test]
    fn test_parse_known_hosts_invalid_port() {
        // Non-numeric port
        assert!(matches!(
            parse_known_hosts_line("[myhost]:abc ssh-rsa AAAA..."),
            KnownHostResult::Failed
        ));
        // Port out of u16 range
        assert!(matches!(
            parse_known_hosts_line("[myhost]:70000 ssh-rsa AAAA..."),
            KnownHostResult::Failed
        ));
        // Port 0
        assert!(matches!(
            parse_known_hosts_line("[myhost]:0 ssh-rsa AAAA..."),
            KnownHostResult::Failed
        ));
    }

    #[test]
    fn test_parse_known_hosts_comma_separated() {
        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("myserver.com,192.168.1.1 ssh-ed25519 AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.hostname, "myserver.com");
        assert_eq!(entry.alias, "myserver");
    }

    #[test]
    fn test_parse_known_hosts_malformed_is_failure() {
        // Too few fields = parse failure
        assert!(matches!(
            parse_known_hosts_line("onlyhost ssh-rsa"),
            KnownHostResult::Failed
        ));
        // Unclosed bracket = parse failure
        assert!(matches!(
            parse_known_hosts_line("[broken ssh-rsa AAAA..."),
            KnownHostResult::Failed
        ));
    }

    #[test]
    fn test_parse_known_hosts_marker_is_skipped() {
        assert!(matches!(
            parse_known_hosts_line("@cert-authority *.example.com ssh-rsa AAAA..."),
            KnownHostResult::Skipped
        ));
        assert!(matches!(
            parse_known_hosts_line("@revoked host.com ssh-rsa AAAA..."),
            KnownHostResult::Skipped
        ));
    }

    #[test]
    fn test_parse_known_hosts_numeric_first_label_not_skipped() {
        // "123.example.com" has a numeric first label but is a valid FQDN, not an IP
        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("123.example.com ssh-rsa AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.hostname, "123.example.com");
        assert_eq!(entry.alias, "123");
    }

    #[test]
    fn test_parse_known_hosts_bracket_trailing_colon_fails() {
        // [host]: with no port number should fail
        assert!(matches!(
            parse_known_hosts_line("[myhost]: ssh-rsa AAAA..."),
            KnownHostResult::Failed
        ));
    }

    #[test]
    fn test_parse_known_hosts_bracket_junk_after_close_fails() {
        // [host]junk with no colon separator should fail
        assert!(matches!(
            parse_known_hosts_line("[myhost]junk ssh-rsa AAAA..."),
            KnownHostResult::Failed
        ));
    }

    #[test]
    fn test_parse_known_hosts_bracket_no_port() {
        // [host] with no port should default to 22
        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("[myhost.com] ssh-rsa AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.hostname, "myhost.com");
        assert_eq!(entry.port, 22);
    }

    #[test]
    fn test_parse_known_hosts_wildcard_is_skipped() {
        assert!(matches!(
            parse_known_hosts_line("*.example.com ssh-rsa AAAA..."),
            KnownHostResult::Skipped
        ));
    }

    #[test]
    fn test_parse_known_hosts_bracket_pattern_skipped() {
        // OpenSSH character class pattern [12] should be skipped
        assert!(matches!(
            parse_known_hosts_line("web[12].example.com ssh-rsa AAAA..."),
            KnownHostResult::Skipped
        ));
    }

    #[test]
    fn test_parse_known_hosts_negation_pattern_skipped() {
        assert!(matches!(
            parse_known_hosts_line("!prod.example.com ssh-rsa AAAA..."),
            KnownHostResult::Skipped
        ));
    }

    #[test]
    fn test_parse_known_hosts_ip_first_comma_picks_hostname() {
        // When IP comes before hostname in comma list, hostname should still be used
        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("192.0.2.10,web.example.com ssh-rsa AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.hostname, "web.example.com");
        assert_eq!(entry.alias, "web");
    }

    #[test]
    fn test_parse_known_hosts_ipv6_first_comma_picks_hostname() {
        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("2001:db8::1,server.example.com ssh-rsa AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.hostname, "server.example.com");
        assert_eq!(entry.alias, "server");
    }

    #[test]
    fn test_parse_known_hosts_all_ips_comma_skipped() {
        // If all comma entries are IPs, skip the whole line
        assert!(matches!(
            parse_known_hosts_line("192.0.2.10,10.0.0.1 ssh-rsa AAAA..."),
            KnownHostResult::Skipped
        ));
    }

    #[test]
    fn test_parse_known_hosts_bracketed_ip_first_comma_picks_hostname() {
        // [ip]:port,hostname format should pick the hostname
        let KnownHostResult::Parsed(entry) =
            parse_known_hosts_line("[192.0.2.10]:2222,web.example.com ssh-rsa AAAA...")
        else {
            panic!("expected Parsed");
        };
        assert_eq!(entry.hostname, "web.example.com");
        assert_eq!(entry.alias, "web");
    }

    #[test]
    fn test_is_bare_ip() {
        assert!(is_bare_ip("192.168.1.1"));
        assert!(is_bare_ip("10.0.0.1"));
        assert!(is_bare_ip("2001:db8::1"));
        assert!(is_bare_ip("fe80::1"));
        assert!(is_bare_ip("fe80::1%en0"));
        assert!(is_bare_ip("fe80::1%eth0"));
        assert!(!is_bare_ip("example.com"));
        assert!(!is_bare_ip("123.example.com"));
        assert!(!is_bare_ip("deadbeef"));
        assert!(!is_bare_ip(""));
    }
}