purple_ssh/ssh_config/model.rs
1use std::path::PathBuf;
2
3/// Represents the entire SSH config file as a sequence of elements.
4/// Preserves the original structure for round-trip fidelity.
5#[derive(Debug, Clone)]
6pub struct SshConfigFile {
7 pub elements: Vec<ConfigElement>,
8 pub path: PathBuf,
9 /// Whether the original file used CRLF line endings.
10 pub crlf: bool,
11 /// Whether the original file started with a UTF-8 BOM.
12 pub bom: bool,
13}
14
15/// An Include directive that references other config files.
16#[derive(Debug, Clone)]
17pub struct IncludeDirective {
18 pub raw_line: String,
19 pub pattern: String,
20 pub resolved_files: Vec<IncludedFile>,
21}
22
23/// A file resolved from an Include directive.
24#[derive(Debug, Clone)]
25pub struct IncludedFile {
26 pub path: PathBuf,
27 pub elements: Vec<ConfigElement>,
28}
29
30/// A single element in the config file.
31#[derive(Debug, Clone)]
32pub enum ConfigElement {
33 /// A Host block: the `Host <pattern>` line plus all indented directives.
34 HostBlock(HostBlock),
35 /// A comment, blank line, or global directive not inside a Host block.
36 GlobalLine(String),
37 /// An Include directive referencing other config files (read-only).
38 Include(IncludeDirective),
39}
40
41/// A parsed Host block with its directives.
42#[derive(Debug, Clone)]
43pub struct HostBlock {
44 /// The host alias/pattern (the value after "Host").
45 pub host_pattern: String,
46 /// The original raw "Host ..." line for faithful reproduction.
47 pub raw_host_line: String,
48 /// Parsed directives inside this block.
49 pub directives: Vec<Directive>,
50}
51
52/// A directive line inside a Host block.
53#[derive(Debug, Clone)]
54pub struct Directive {
55 /// The directive key (e.g., "HostName", "User", "Port").
56 pub key: String,
57 /// The directive value.
58 pub value: String,
59 /// The original raw line (preserves indentation, inline comments).
60 pub raw_line: String,
61 /// Whether this is a comment-only or blank line inside a host block.
62 pub is_non_directive: bool,
63}
64
65/// Convenience view for the TUI — extracted from a HostBlock.
66#[derive(Debug, Clone)]
67pub struct HostEntry {
68 pub alias: String,
69 pub hostname: String,
70 pub user: String,
71 pub port: u16,
72 pub identity_file: String,
73 pub proxy_jump: String,
74 /// If this host comes from an included file, the file path.
75 pub source_file: Option<PathBuf>,
76 /// User-added tags from purple:tags comment.
77 pub tags: Vec<String>,
78 /// Provider-synced tags from purple:provider_tags comment.
79 pub provider_tags: Vec<String>,
80 /// Whether a purple:provider_tags comment exists (distinguishes "never migrated" from "empty").
81 pub has_provider_tags: bool,
82 /// Cloud provider label from purple:provider comment (e.g. "do", "vultr").
83 pub provider: Option<String>,
84 /// Provider config label from a 3-segment purple:provider marker
85 /// (`provider:label:server_id`). None for legacy 2-segment markers.
86 /// Used together with `provider` to resolve which labeled config a host
87 /// belongs to in multi-config setups.
88 pub provider_label: Option<String>,
89 /// Number of tunnel forwarding directives.
90 pub tunnel_count: u16,
91 /// Password source from purple:askpass comment (e.g. "keychain", "op://...", "pass:...").
92 pub askpass: Option<String>,
93 /// Vault SSH certificate signing role from purple:vault-ssh comment.
94 pub vault_ssh: Option<String>,
95 /// Optional Vault HTTP endpoint from purple:vault-addr comment. When
96 /// set, purple passes it as `VAULT_ADDR` to the `vault` subprocess for
97 /// this host's signing, overriding the parent shell. Empty = inherit env.
98 pub vault_addr: Option<String>,
99 /// CertificateFile directive value (e.g. "~/.ssh/my-cert.pub").
100 pub certificate_file: String,
101 /// Provider metadata from purple:meta comment (region, plan, etc.).
102 pub provider_meta: Vec<(String, String)>,
103 /// Unix timestamp when the host was marked stale (disappeared from provider sync).
104 pub stale: Option<u64>,
105}
106
107impl Default for HostEntry {
108 fn default() -> Self {
109 Self {
110 alias: String::new(),
111 hostname: String::new(),
112 user: String::new(),
113 port: 22,
114 identity_file: String::new(),
115 proxy_jump: String::new(),
116 source_file: None,
117 tags: Vec::new(),
118 provider_tags: Vec::new(),
119 has_provider_tags: false,
120 provider: None,
121 provider_label: None,
122 tunnel_count: 0,
123 askpass: None,
124 vault_ssh: None,
125 vault_addr: None,
126 certificate_file: String::new(),
127 provider_meta: Vec::new(),
128 stale: None,
129 }
130 }
131}
132
133impl HostEntry {
134 /// Build the SSH command string for this host.
135 /// Includes `-F <config_path>` when the config is non-default so the alias
136 /// resolves correctly when pasted into a terminal.
137 /// Shell-quotes both the config path and alias to prevent injection.
138 pub fn ssh_command(&self, config_path: &std::path::Path) -> String {
139 let escaped = self.alias.replace('\'', "'\\''");
140 let default = dirs::home_dir()
141 .map(|h| h.join(".ssh/config"))
142 .unwrap_or_default();
143 if config_path == default {
144 format!("ssh -- '{}'", escaped)
145 } else {
146 let config_escaped = config_path.display().to_string().replace('\'', "'\\''");
147 format!("ssh -F '{}' -- '{}'", config_escaped, escaped)
148 }
149 }
150}
151
152/// Convenience view for pattern Host blocks in the TUI.
153#[derive(Debug, Clone, Default)]
154pub struct PatternEntry {
155 pub pattern: String,
156 pub hostname: String,
157 pub user: String,
158 pub port: u16,
159 pub identity_file: String,
160 pub proxy_jump: String,
161 pub tags: Vec<String>,
162 pub askpass: Option<String>,
163 pub source_file: Option<PathBuf>,
164 /// All non-comment directives as key-value pairs for display.
165 pub directives: Vec<(String, String)>,
166}
167
168/// Inherited field hints from matching patterns. Each field is `Some((value,
169/// source_pattern))` when a pattern provides that directive, `None` otherwise.
170#[derive(Debug, Clone, Default)]
171pub struct InheritedHints {
172 pub proxy_jump: Option<(String, String)>,
173 pub user: Option<(String, String)>,
174 pub identity_file: Option<(String, String)>,
175}
176
177use super::pattern::apply_first_match_fields;
178/// Returns true if the host pattern contains wildcards, character classes,
179/// negation or whitespace-separated multi-patterns (*, ?, [], !, space/tab).
180/// These are SSH match patterns, not concrete hosts.
181// Pattern-matching lives in `ssh_config::pattern`. These re-exports preserve
182// the old `ssh_config::model::*` import paths used across the codebase and in
183// the model_tests file mounted below.
184#[allow(unused_imports)]
185pub use super::pattern::{
186 host_pattern_matches, is_host_pattern, proxy_jump_contains_self, ssh_pattern_match,
187};
188
189/// True if a `CertificateFile` directive value points at purple's managed
190/// certificate directory. Recognises both tilde-prefixed and absolute paths
191/// (`~/.purple/certs/...`, `/home/user/.purple/certs/...`,
192/// `$HOME/.purple/certs/...`). Used by `set_host_certificate_file` so
193/// user-set custom CertificateFile entries are preserved across vault
194/// sign / unsign cycles.
195pub(super) fn is_purple_managed_cert_value(value: &str) -> bool {
196 let trimmed = value.trim();
197 // Strip surrounding double quotes; OpenSSH treats `"~/.purple/..."` and
198 // `~/.purple/...` as equivalent.
199 let unquoted = trimmed
200 .strip_prefix('"')
201 .and_then(|s| s.strip_suffix('"'))
202 .unwrap_or(trimmed);
203 unquoted.contains(".purple/certs/")
204}
205// Re-exported so the test file mounted below keeps working.
206#[allow(unused_imports)]
207pub(super) use super::repair::provider_group_display_name;
208
209impl SshConfigFile {
210 /// Get all host entries as convenience views (including from Include files).
211 /// Pattern-inherited directives (ProxyJump, User, IdentityFile) are merged
212 /// using SSH-faithful alias-only matching so indicators like ↗ reflect what
213 /// SSH will actually apply when connecting via `ssh <alias>`.
214 pub fn host_entries(&self) -> Vec<HostEntry> {
215 let mut entries = Vec::new();
216 Self::collect_host_entries(&self.elements, &mut entries);
217 self.apply_pattern_inheritance(&mut entries);
218 entries
219 }
220
221 /// Get a single host entry by alias without pattern inheritance applied.
222 /// Returns the raw directives from the host's own block only. Used by the
223 /// edit form so inherited values can be shown as dimmed placeholders.
224 pub fn raw_host_entry(&self, alias: &str) -> Option<HostEntry> {
225 Self::find_raw_host_entry(&self.elements, alias)
226 }
227
228 fn find_raw_host_entry(elements: &[ConfigElement], alias: &str) -> Option<HostEntry> {
229 for e in elements {
230 match e {
231 ConfigElement::HostBlock(block)
232 if !is_host_pattern(&block.host_pattern) && block.host_pattern == alias =>
233 {
234 return Some(block.to_host_entry());
235 }
236 ConfigElement::Include(inc) => {
237 for file in &inc.resolved_files {
238 if let Some(mut found) = Self::find_raw_host_entry(&file.elements, alias) {
239 if found.source_file.is_none() {
240 found.source_file = Some(file.path.clone());
241 }
242 return Some(found);
243 }
244 }
245 }
246 _ => {}
247 }
248 }
249 None
250 }
251
252 /// Apply SSH first-match-wins pattern inheritance to host entries.
253 /// Matches patterns against the alias only (SSH-faithful: `Host` patterns
254 /// match the token typed on the command line, not the resolved `Hostname`).
255 fn apply_pattern_inheritance(&self, entries: &mut [HostEntry]) {
256 // Patterns are pre-collected once. Host entries never contain pattern
257 // aliases — collect_host_entries skips is_host_pattern blocks.
258 let all_patterns = self.pattern_entries();
259 for entry in entries.iter_mut() {
260 if !entry.proxy_jump.is_empty()
261 && !entry.user.is_empty()
262 && !entry.identity_file.is_empty()
263 {
264 continue;
265 }
266 for p in &all_patterns {
267 if !host_pattern_matches(&p.pattern, &entry.alias) {
268 continue;
269 }
270 apply_first_match_fields(
271 &mut entry.proxy_jump,
272 &mut entry.user,
273 &mut entry.identity_file,
274 p,
275 );
276 if !entry.proxy_jump.is_empty()
277 && !entry.user.is_empty()
278 && !entry.identity_file.is_empty()
279 {
280 break;
281 }
282 }
283 }
284 }
285
286 /// Compute pattern-provided field hints for a host alias. Returns first-match
287 /// values and their source patterns for ProxyJump, User and IdentityFile.
288 /// These are returned regardless of whether the host has its own values for
289 /// those fields. The caller (form rendering) decides visibility based on
290 /// whether the field is empty. Matches by alias only (SSH-faithful).
291 pub fn inherited_hints(&self, alias: &str) -> InheritedHints {
292 let patterns = self.matching_patterns(alias);
293 let mut hints = InheritedHints::default();
294 for p in &patterns {
295 if hints.proxy_jump.is_none() && !p.proxy_jump.is_empty() {
296 hints.proxy_jump = Some((p.proxy_jump.clone(), p.pattern.clone()));
297 }
298 if hints.user.is_none() && !p.user.is_empty() {
299 hints.user = Some((p.user.clone(), p.pattern.clone()));
300 }
301 if hints.identity_file.is_none() && !p.identity_file.is_empty() {
302 hints.identity_file = Some((p.identity_file.clone(), p.pattern.clone()));
303 }
304 if hints.proxy_jump.is_some() && hints.user.is_some() && hints.identity_file.is_some() {
305 break;
306 }
307 }
308 hints
309 }
310
311 /// Get all pattern entries as convenience views (including from Include files).
312 pub fn pattern_entries(&self) -> Vec<PatternEntry> {
313 let mut entries = Vec::new();
314 Self::collect_pattern_entries(&self.elements, &mut entries);
315 entries
316 }
317
318 fn collect_pattern_entries(elements: &[ConfigElement], entries: &mut Vec<PatternEntry>) {
319 for e in elements {
320 match e {
321 ConfigElement::HostBlock(block) => {
322 if !is_host_pattern(&block.host_pattern) {
323 continue;
324 }
325 entries.push(block.to_pattern_entry());
326 }
327 ConfigElement::Include(include) => {
328 for file in &include.resolved_files {
329 let start = entries.len();
330 Self::collect_pattern_entries(&file.elements, entries);
331 for entry in &mut entries[start..] {
332 if entry.source_file.is_none() {
333 entry.source_file = Some(file.path.clone());
334 }
335 }
336 }
337 }
338 ConfigElement::GlobalLine(_) => {}
339 }
340 }
341 }
342
343 /// Find all pattern blocks that match a given host alias and hostname.
344 /// Returns entries in config order (first match first).
345 pub fn matching_patterns(&self, alias: &str) -> Vec<PatternEntry> {
346 let mut matches = Vec::new();
347 Self::collect_matching_patterns(&self.elements, alias, &mut matches);
348 matches
349 }
350
351 fn collect_matching_patterns(
352 elements: &[ConfigElement],
353 alias: &str,
354 matches: &mut Vec<PatternEntry>,
355 ) {
356 for e in elements {
357 match e {
358 ConfigElement::HostBlock(block) => {
359 if !is_host_pattern(&block.host_pattern) {
360 continue;
361 }
362 if host_pattern_matches(&block.host_pattern, alias) {
363 matches.push(block.to_pattern_entry());
364 }
365 }
366 ConfigElement::Include(include) => {
367 for file in &include.resolved_files {
368 let start = matches.len();
369 Self::collect_matching_patterns(&file.elements, alias, matches);
370 for entry in &mut matches[start..] {
371 if entry.source_file.is_none() {
372 entry.source_file = Some(file.path.clone());
373 }
374 }
375 }
376 }
377 ConfigElement::GlobalLine(_) => {}
378 }
379 }
380 }
381
382 /// Collect all resolved Include file paths (recursively).
383 pub fn include_paths(&self) -> Vec<PathBuf> {
384 let mut paths = Vec::new();
385 Self::collect_include_paths(&self.elements, &mut paths);
386 paths
387 }
388
389 fn collect_include_paths(elements: &[ConfigElement], paths: &mut Vec<PathBuf>) {
390 for e in elements {
391 if let ConfigElement::Include(include) = e {
392 for file in &include.resolved_files {
393 paths.push(file.path.clone());
394 Self::collect_include_paths(&file.elements, paths);
395 }
396 }
397 }
398 }
399
400 /// Collect parent directories of Include glob patterns.
401 /// When a file is added/removed under a glob dir, the directory's mtime changes.
402 pub fn include_glob_dirs(&self) -> Vec<PathBuf> {
403 let config_dir = self.path.parent();
404 let mut seen = std::collections::HashSet::new();
405 let mut dirs = Vec::new();
406 Self::collect_include_glob_dirs(&self.elements, config_dir, &mut seen, &mut dirs);
407 dirs
408 }
409
410 fn collect_include_glob_dirs(
411 elements: &[ConfigElement],
412 config_dir: Option<&std::path::Path>,
413 seen: &mut std::collections::HashSet<PathBuf>,
414 dirs: &mut Vec<PathBuf>,
415 ) {
416 for e in elements {
417 if let ConfigElement::Include(include) = e {
418 // Split respecting quoted paths (same as resolve_include does)
419 for single in Self::split_include_patterns(&include.pattern) {
420 let expanded = Self::expand_env_vars(&Self::expand_tilde(single));
421 let resolved = if expanded.starts_with('/') {
422 PathBuf::from(&expanded)
423 } else if let Some(dir) = config_dir {
424 dir.join(&expanded)
425 } else {
426 continue;
427 };
428 if let Some(parent) = resolved.parent() {
429 let parent = parent.to_path_buf();
430 if seen.insert(parent.clone()) {
431 dirs.push(parent);
432 }
433 }
434 }
435 // Recurse into resolved files
436 for file in &include.resolved_files {
437 Self::collect_include_glob_dirs(&file.elements, file.path.parent(), seen, dirs);
438 }
439 }
440 }
441 }
442
443 /// Remove `# purple:group <Name>` headers that have no corresponding
444 /// provider hosts. Returns the number of headers removed.
445 /// Recursively collect host entries from a list of elements.
446 fn collect_host_entries(elements: &[ConfigElement], entries: &mut Vec<HostEntry>) {
447 for e in elements {
448 match e {
449 ConfigElement::HostBlock(block) => {
450 if is_host_pattern(&block.host_pattern) {
451 continue;
452 }
453 entries.push(block.to_host_entry());
454 }
455 ConfigElement::Include(include) => {
456 for file in &include.resolved_files {
457 let start = entries.len();
458 Self::collect_host_entries(&file.elements, entries);
459 for entry in &mut entries[start..] {
460 if entry.source_file.is_none() {
461 entry.source_file = Some(file.path.clone());
462 }
463 }
464 }
465 }
466 ConfigElement::GlobalLine(_) => {}
467 }
468 }
469 }
470
471 /// Check if a host alias already exists (including in Include files).
472 /// Walks the element tree directly without building HostEntry structs.
473 pub fn has_host(&self, alias: &str) -> bool {
474 Self::has_host_in_elements(&self.elements, alias)
475 }
476
477 fn has_host_in_elements(elements: &[ConfigElement], alias: &str) -> bool {
478 for e in elements {
479 match e {
480 ConfigElement::HostBlock(block) => {
481 if pattern_contains_token(&block.host_pattern, alias) {
482 return true;
483 }
484 }
485 ConfigElement::Include(include) => {
486 for file in &include.resolved_files {
487 if Self::has_host_in_elements(&file.elements, alias) {
488 return true;
489 }
490 }
491 }
492 ConfigElement::GlobalLine(_) => {}
493 }
494 }
495 false
496 }
497
498 /// Return the sibling aliases that share a `Host` block with `alias`.
499 ///
500 /// An empty vector means `alias` lives in its own single-alias block (or
501 /// is not present). A non-empty vector lists the other tokens in the
502 /// block in source order, so the UI can render indicators like `+N` or
503 /// spell the aliases out in a confirm dialog before a destructive
504 /// action. Does not recurse into `Include`d files: those are read-only
505 /// and their hosts cannot be edited from purple anyway.
506 pub fn siblings_of(&self, alias: &str) -> Vec<String> {
507 if alias.is_empty() {
508 return Vec::new();
509 }
510 self.elements
511 .iter()
512 .find_map(|el| match el {
513 ConfigElement::HostBlock(b) => {
514 // Full-pattern match means the caller is acting on the
515 // whole block (e.g. pattern browser delete of
516 // `web-01 web-01.prod`). All tokens are the target, so
517 // there are no "siblings" to preserve.
518 if b.host_pattern == alias {
519 return Some(Vec::new());
520 }
521 let tokens: Vec<String> = b
522 .host_pattern
523 .split_whitespace()
524 .map(String::from)
525 .collect();
526 if tokens.iter().any(|t| t == alias) {
527 Some(tokens.into_iter().filter(|t| t != alias).collect())
528 } else {
529 None
530 }
531 }
532 _ => None,
533 })
534 .unwrap_or_default()
535 }
536
537 /// Find a mutable top-level `HostBlock` whose `host_pattern` contains
538 /// `alias` as one of its whitespace-separated tokens.
539 ///
540 /// Mirrors the matching used by read-path helpers like `has_host` and
541 /// `find_tunnel_directives`, so that any host visible in the TUI is also
542 /// addressable from write paths (`update_host`, `delete_host`,
543 /// `set_host_*`). Prior to this helper, writers compared the full
544 /// `host_pattern` for exact equality, which silently no-op'd on
545 /// multi-alias blocks like `Host web-01 web-01.prod 10.0.1.5` and
546 /// resulted in on-disk drift between the in-memory view and the config
547 /// file.
548 ///
549 /// Does not recurse into `Include`d files: those are read-only.
550 ///
551 /// A block matches when either (a) its full `host_pattern` equals
552 /// `alias` (used by the pattern browser for blocks like `web-* db-*`
553 /// or `web-01 web-01.prod` whose full pattern is the caller's key) or
554 /// (b) `alias` appears as one of the whitespace-separated tokens (used
555 /// by the host list for multi-alias blocks). The full-pattern match is
556 /// tried first so callers that pass a pattern string do not
557 /// accidentally trigger the token-strip path.
558 fn find_host_block_mut(&mut self, alias: &str) -> Option<&mut HostBlock> {
559 if alias.is_empty() {
560 return None;
561 }
562 self.elements.iter_mut().find_map(|el| match el {
563 ConfigElement::HostBlock(b)
564 if b.host_pattern == alias || pattern_contains_token(&b.host_pattern, alias) =>
565 {
566 Some(b)
567 }
568 _ => None,
569 })
570 }
571
572 /// Check if a host block with exactly this host_pattern exists (top-level only).
573 /// Unlike `has_host` which splits multi-host patterns and checks individual parts,
574 /// this matches the full `Host` line pattern string (e.g. "web-* db-*").
575 /// Does not search Include files (patterns from includes are read-only).
576 pub fn has_host_block(&self, pattern: &str) -> bool {
577 self.elements
578 .iter()
579 .any(|e| matches!(e, ConfigElement::HostBlock(block) if block.host_pattern == pattern))
580 }
581
582 /// Check if a host alias is from an included file (read-only).
583 /// Handles multi-pattern Host lines by splitting on whitespace.
584 pub fn is_included_host(&self, alias: &str) -> bool {
585 // Not in top-level elements → must be in an Include
586 for e in &self.elements {
587 match e {
588 ConfigElement::HostBlock(block) => {
589 if pattern_contains_token(&block.host_pattern, alias) {
590 return false;
591 }
592 }
593 ConfigElement::Include(include) => {
594 for file in &include.resolved_files {
595 if Self::has_host_in_elements(&file.elements, alias) {
596 return true;
597 }
598 }
599 }
600 ConfigElement::GlobalLine(_) => {}
601 }
602 }
603 false
604 }
605
606 /// Add a new host entry to the config.
607 /// Inserts before any trailing wildcard/pattern Host blocks (e.g. `Host *`)
608 /// so that SSH "first match wins" semantics are preserved. If wildcards are
609 /// only at the top of the file (acting as global defaults), appends at end.
610 pub fn add_host(&mut self, entry: &HostEntry) {
611 let block = Self::entry_to_block(entry);
612 let insert_pos = self.find_trailing_pattern_start();
613
614 if let Some(pos) = insert_pos {
615 // Insert before the trailing pattern group, with blank separators
616 let needs_blank_before = pos > 0
617 && !matches!(
618 self.elements.get(pos - 1),
619 Some(ConfigElement::GlobalLine(line)) if line.trim().is_empty()
620 );
621 let mut idx = pos;
622 if needs_blank_before {
623 self.elements
624 .insert(idx, ConfigElement::GlobalLine(String::new()));
625 idx += 1;
626 }
627 self.elements.insert(idx, ConfigElement::HostBlock(block));
628 // Ensure a blank separator after the new block (before the wildcard group)
629 let after = idx + 1;
630 if after < self.elements.len()
631 && !matches!(
632 self.elements.get(after),
633 Some(ConfigElement::GlobalLine(line)) if line.trim().is_empty()
634 )
635 {
636 self.elements
637 .insert(after, ConfigElement::GlobalLine(String::new()));
638 }
639 } else {
640 // No trailing patterns: append at end
641 if !self.elements.is_empty() && !self.last_element_has_trailing_blank() {
642 self.elements.push(ConfigElement::GlobalLine(String::new()));
643 }
644 self.elements.push(ConfigElement::HostBlock(block));
645 }
646 }
647
648 /// Find the start of a trailing group of wildcard/pattern Host blocks.
649 /// Scans backwards from the end, skipping GlobalLines (blanks/comments/Match).
650 /// Returns `None` if no trailing patterns exist (or if ALL hosts are patterns,
651 /// i.e. patterns start at position 0 — in that case we append at end).
652 fn find_trailing_pattern_start(&self) -> Option<usize> {
653 let mut first_pattern_pos = None;
654 for i in (0..self.elements.len()).rev() {
655 match &self.elements[i] {
656 ConfigElement::HostBlock(block) => {
657 if is_host_pattern(&block.host_pattern) {
658 first_pattern_pos = Some(i);
659 } else {
660 // Found a concrete host: the trailing group starts after this
661 break;
662 }
663 }
664 ConfigElement::GlobalLine(_) => {
665 // Blank lines, comments, Match blocks between patterns: keep scanning
666 if first_pattern_pos.is_some() {
667 first_pattern_pos = Some(i);
668 }
669 }
670 ConfigElement::Include(_) => break,
671 }
672 }
673 // Don't return position 0 — that means everything is patterns (or patterns at top)
674 first_pattern_pos.filter(|&pos| pos > 0)
675 }
676
677 /// Check if the last element already ends with a blank line.
678 pub fn last_element_has_trailing_blank(&self) -> bool {
679 match self.elements.last() {
680 Some(ConfigElement::HostBlock(block)) => block
681 .directives
682 .last()
683 .is_some_and(|d| d.is_non_directive && d.raw_line.trim().is_empty()),
684 Some(ConfigElement::GlobalLine(line)) => line.trim().is_empty(),
685 _ => false,
686 }
687 }
688
689 /// Update an existing host entry by alias.
690 /// Merges changes into the existing block, preserving unknown directives.
691 ///
692 /// Alias matching uses whitespace-tokenized equality, so a host visible
693 /// under a multi-alias block like `Host web-01 web-01.prod` is reachable
694 /// from any of its aliases. Directives are shared across all tokens in
695 /// the block (per SSH semantics): updating `User` on `web-01.prod`
696 /// therefore also affects `web-01`.
697 ///
698 /// On rename of a multi-alias block only the matching token is replaced
699 /// in the `Host` line; sibling aliases are preserved verbatim.
700 pub fn update_host(&mut self, old_alias: &str, entry: &HostEntry) {
701 let Some(block) = self.find_host_block_mut(old_alias) else {
702 return;
703 };
704
705 if entry.alias != old_alias {
706 // Sanitise the new alias before it flows into `raw_host_line`.
707 // A malicious provider response with `\n` in the alias would
708 // otherwise inject extra Host blocks into the user's config.
709 // entry_to_block already sanitises the add-host path; this
710 // mirrors it for the rename path.
711 let safe_alias = HostBlock::sanitize_raw_line_value(&entry.alias);
712 // Full-pattern match (pattern browser rename) replaces the whole
713 // `host_pattern` verbatim. Token match (host list rename on a
714 // multi-alias block) replaces only the selected token so
715 // siblings survive. Single-alias blocks are covered by the
716 // token path because `tokens == [old_alias]`.
717 let is_full_pattern_match = block.host_pattern == old_alias;
718 let new_pattern: String = if is_full_pattern_match {
719 safe_alias.to_string()
720 } else {
721 block
722 .host_pattern
723 .split_whitespace()
724 .map(|t| {
725 if t == old_alias {
726 safe_alias.as_ref()
727 } else {
728 t
729 }
730 })
731 .collect::<Vec<_>>()
732 .join(" ")
733 };
734 block.host_pattern = new_pattern.clone();
735 block.raw_host_line = rebuild_host_line(&block.raw_host_line, &new_pattern);
736 }
737
738 // Merge known directives (update existing, add missing, remove empty)
739 Self::upsert_directive(block, "HostName", &entry.hostname);
740 Self::upsert_directive(block, "User", &entry.user);
741 if entry.port != 22 {
742 Self::upsert_directive(block, "Port", &entry.port.to_string());
743 } else {
744 // Port 22 is the SSH default: drop the explicit directive so
745 // the rendered block stays minimal. Route through
746 // `upsert_directive` with an empty value so the first-only
747 // semantics match every other key here; a separate `retain`
748 // would diverge from the cumulative-directive invariant.
749 Self::upsert_directive(block, "Port", "");
750 }
751 Self::upsert_directive(block, "IdentityFile", &entry.identity_file);
752 Self::upsert_directive(block, "ProxyJump", &entry.proxy_jump);
753 }
754
755 /// Update a directive in-place, add it if missing, or remove it if value is empty.
756 ///
757 /// When `value` is empty only the FIRST matching directive is removed.
758 /// OpenSSH treats some directives (`IdentityFile`, `CertificateFile`,
759 /// `LocalForward`, etc.) as cumulative: a host with three `IdentityFile`
760 /// lines is intentionally multi-key. Wiping all matching directives on
761 /// an empty form field would silently delete the user's other keys.
762 /// The form only edits the first occurrence (see `to_host_entry` which
763 /// reads `if entry.identity_file.is_empty()`), so the symmetric remove
764 /// only-first behaviour keeps the per-form-field invariant intact:
765 /// "what the user sees in the field is what the field controls".
766 fn upsert_directive(block: &mut HostBlock, key: &str, value: &str) {
767 // Defence in depth: sanitise the value before interpolation. The
768 // provider-sync update path passes `remote.ip` directly to
769 // `update_host` -> `upsert_directive`, so a self-hosted provider
770 // with TLS verification disabled (Proxmox, OCI) could supply a
771 // hostname containing `\n ProxyCommand evil` and inject a real
772 // directive. `entry_to_block` (the add-host path) sanitises at
773 // construction; mirroring it here closes the symmetric edit path.
774 let value_owned = HostBlock::sanitize_raw_line_value(value);
775 let value = value_owned.as_ref();
776 if value.is_empty() {
777 if let Some(pos) = block
778 .directives
779 .iter()
780 .position(|d| !d.is_non_directive && d.key.eq_ignore_ascii_case(key))
781 {
782 block.directives.remove(pos);
783 }
784 return;
785 }
786 let indent = block.detect_indent();
787 for d in &mut block.directives {
788 if !d.is_non_directive && d.key.eq_ignore_ascii_case(key) {
789 // Only rebuild raw_line when value actually changed (preserves inline comments)
790 if d.value != value {
791 d.value = value.to_string();
792 // Detect separator style from original raw_line and preserve it.
793 // Handles: "Key value", "Key=value", "Key = value", "Key =value"
794 // Only considers '=' as separator if it appears before any
795 // non-whitespace content (avoids matching '=' inside values
796 // like "IdentityFile ~/.ssh/id=prod").
797 let trimmed = d.raw_line.trim_start();
798 let after_key = &trimmed[d.key.len()..];
799 let sep = if after_key.trim_start().starts_with('=') {
800 let eq_pos = after_key.find('=').unwrap();
801 let after_eq = &after_key[eq_pos + 1..];
802 let trailing_ws = after_eq.len() - after_eq.trim_start().len();
803 after_key[..eq_pos + 1 + trailing_ws].to_string()
804 } else {
805 " ".to_string()
806 };
807 // Preserve inline comment from original raw_line (e.g. "# production")
808 let comment_suffix = Self::extract_inline_comment(&d.raw_line, &d.key);
809 d.raw_line = format!("{}{}{}{}{}", indent, d.key, sep, value, comment_suffix);
810 }
811 return;
812 }
813 }
814 // Not found — insert before trailing blanks
815 let pos = block.content_end();
816 block.directives.insert(
817 pos,
818 Directive {
819 key: key.to_string(),
820 value: value.to_string(),
821 raw_line: format!("{}{} {}", indent, key, value),
822 is_non_directive: false,
823 },
824 );
825 }
826
827 /// Extract the inline comment suffix from a directive's raw line.
828 /// Returns the trailing portion (e.g. " # production") or empty string.
829 /// Respects double-quoted strings so that `#` inside quotes is not a comment.
830 fn extract_inline_comment(raw_line: &str, key: &str) -> String {
831 let trimmed = raw_line.trim_start();
832 if trimmed.len() <= key.len() {
833 return String::new();
834 }
835 // Skip past key and separator to reach the value portion
836 let after_key = &trimmed[key.len()..];
837 let rest = after_key.trim_start();
838 let rest = rest.strip_prefix('=').unwrap_or(rest).trim_start();
839 // Scan for inline comment (# preceded by whitespace, outside quotes)
840 let bytes = rest.as_bytes();
841 let mut in_quote = false;
842 for i in 0..bytes.len() {
843 if bytes[i] == b'"' {
844 in_quote = !in_quote;
845 } else if !in_quote
846 && bytes[i] == b'#'
847 && i > 0
848 && (bytes[i - 1] == b' ' || bytes[i - 1] == b'\t')
849 {
850 // Found comment start. The clean value ends before the whitespace preceding #.
851 let clean_end = rest[..i].trim_end().len();
852 return rest[clean_end..].to_string();
853 }
854 }
855 String::new()
856 }
857
858 /// Set provider on a host block by alias using a full ProviderConfigId.
859 /// Emits a 3-segment marker when the id has a label, 2-segment otherwise.
860 ///
861 /// Refuses pattern aliases and multi-alias blocks: claiming a sibling
862 /// alias as provider-owned cascades into stale-marking and bulk-purge,
863 /// which would silently delete the user's hand-curated entries.
864 #[must_use = "check the return value to detect silently-skipped mutations (renamed, deleted or shared-block hosts)"]
865 pub fn set_host_provider_id(
866 &mut self,
867 alias: &str,
868 id: &crate::providers::config::ProviderConfigId,
869 server_id: &str,
870 ) -> bool {
871 if alias.is_empty() || is_host_pattern(alias) {
872 return false;
873 }
874 let Some(block) = self.find_host_block_mut(alias) else {
875 return false;
876 };
877 if is_host_pattern(&block.host_pattern) {
878 return false;
879 }
880 block.set_provider_id(id, server_id);
881 true
882 }
883
884 /// Rewrite every 2-segment legacy marker for `provider_name` to a
885 /// 3-segment marker keyed to `(provider_name, label)`. Used by the
886 /// lazy-migration flow so existing hosts of a now-labeled config stay
887 /// owned (and don't get re-claimed or stale-marked) on the next sync.
888 ///
889 /// Only top-level host blocks are rewritten; Include files are read-only
890 /// per the project's invariant. Returns the count of host blocks touched.
891 pub fn rewrite_legacy_markers_to_label(&mut self, provider_name: &str, label: &str) -> usize {
892 let new_id = crate::providers::config::ProviderConfigId::labeled(provider_name, label);
893 let mut rewritten = 0usize;
894 for element in &mut self.elements {
895 if let ConfigElement::HostBlock(block) = element {
896 let Some((id, server_id)) = block.provider_id() else {
897 continue;
898 };
899 if id.provider == provider_name && id.label.is_none() {
900 block.set_provider_id(&new_id, &server_id);
901 rewritten += 1;
902 }
903 }
904 }
905 rewritten
906 }
907
908 /// Find all hosts with a specific provider, returning (alias, server_id) pairs.
909 /// Searches both top-level elements and Include files so that provider hosts
910 /// in included configs are recognized during sync (prevents duplicate additions).
911 pub fn find_hosts_by_provider(&self, provider_name: &str) -> Vec<(String, String)> {
912 let mut results = Vec::new();
913 Self::collect_provider_hosts(&self.elements, provider_name, &mut results);
914 results
915 }
916
917 /// Find hosts owned by an exact `ProviderConfigId`. Used during multi-config sync
918 /// so two labeled configs of the same provider don't claim each other's hosts.
919 /// Legacy 2-segment markers match a bare id (label=None) for backward compatibility.
920 pub fn find_hosts_by_id(
921 &self,
922 id: &crate::providers::config::ProviderConfigId,
923 ) -> Vec<(String, String)> {
924 let mut results = Vec::new();
925 Self::collect_provider_hosts_by_id(&self.elements, id, &mut results);
926 results
927 }
928
929 /// Like `find_hosts_by_provider`, but returns the FULL server_id from the
930 /// raw marker (everything after the first colon), without trying to
931 /// interpret the middle segment as a label. Used by sync of BARE configs
932 /// so server_ids containing colons (Proxmox `qemu:300`) are matched
933 /// against the API response one-to-one instead of being mis-parsed as
934 /// labeled markers.
935 pub fn find_hosts_by_provider_raw(&self, provider_name: &str) -> Vec<(String, String)> {
936 let mut results = Vec::new();
937 Self::collect_provider_hosts_raw(&self.elements, provider_name, &mut results);
938 results
939 }
940
941 fn collect_provider_hosts_raw(
942 elements: &[ConfigElement],
943 provider_name: &str,
944 results: &mut Vec<(String, String)>,
945 ) {
946 for element in elements {
947 match element {
948 ConfigElement::HostBlock(block) => {
949 if let Some((name, server_id)) = block.provider_raw() {
950 if name == provider_name {
951 results.push((block.host_pattern.clone(), server_id));
952 }
953 }
954 }
955 ConfigElement::Include(include) => {
956 for file in &include.resolved_files {
957 Self::collect_provider_hosts_raw(&file.elements, provider_name, results);
958 }
959 }
960 ConfigElement::GlobalLine(_) => {}
961 }
962 }
963 }
964
965 fn collect_provider_hosts(
966 elements: &[ConfigElement],
967 provider_name: &str,
968 results: &mut Vec<(String, String)>,
969 ) {
970 for element in elements {
971 match element {
972 ConfigElement::HostBlock(block) => {
973 if let Some((name, id)) = block.provider() {
974 if name == provider_name {
975 results.push((block.host_pattern.clone(), id));
976 }
977 }
978 }
979 ConfigElement::Include(include) => {
980 for file in &include.resolved_files {
981 Self::collect_provider_hosts(&file.elements, provider_name, results);
982 }
983 }
984 ConfigElement::GlobalLine(_) => {}
985 }
986 }
987 }
988
989 fn collect_provider_hosts_by_id(
990 elements: &[ConfigElement],
991 id: &crate::providers::config::ProviderConfigId,
992 results: &mut Vec<(String, String)>,
993 ) {
994 for element in elements {
995 match element {
996 ConfigElement::HostBlock(block) => {
997 if let Some((host_id, server_id)) = block.provider_id() {
998 if &host_id == id {
999 results.push((block.host_pattern.clone(), server_id));
1000 }
1001 }
1002 }
1003 ConfigElement::Include(include) => {
1004 for file in &include.resolved_files {
1005 Self::collect_provider_hosts_by_id(&file.elements, id, results);
1006 }
1007 }
1008 ConfigElement::GlobalLine(_) => {}
1009 }
1010 }
1011 }
1012
1013 /// Compare two directive values with whitespace normalization.
1014 /// Handles hand-edited configs with tabs or multiple spaces.
1015 fn values_match(a: &str, b: &str) -> bool {
1016 a.split_whitespace().eq(b.split_whitespace())
1017 }
1018
1019 /// Add a forwarding directive to a host block.
1020 /// Inserts at `content_end()` (before trailing blanks), using detected indentation.
1021 /// Uses split_whitespace matching for multi-pattern Host lines.
1022 pub fn add_forward(&mut self, alias: &str, directive_key: &str, value: &str) {
1023 for element in &mut self.elements {
1024 if let ConfigElement::HostBlock(block) = element {
1025 if pattern_contains_token(&block.host_pattern, alias) {
1026 let indent = block.detect_indent();
1027 let pos = block.content_end();
1028 block.directives.insert(
1029 pos,
1030 Directive {
1031 key: directive_key.to_string(),
1032 value: value.to_string(),
1033 raw_line: format!("{}{} {}", indent, directive_key, value),
1034 is_non_directive: false,
1035 },
1036 );
1037 return;
1038 }
1039 }
1040 }
1041 }
1042
1043 /// Remove a specific forwarding directive from a host block.
1044 /// Matches key (case-insensitive) and value (whitespace-normalized).
1045 /// Uses split_whitespace matching for multi-pattern Host lines.
1046 /// Returns true if a directive was actually removed.
1047 pub fn remove_forward(&mut self, alias: &str, directive_key: &str, value: &str) -> bool {
1048 for element in &mut self.elements {
1049 if let ConfigElement::HostBlock(block) = element {
1050 if pattern_contains_token(&block.host_pattern, alias) {
1051 if let Some(pos) = block.directives.iter().position(|d| {
1052 !d.is_non_directive
1053 && d.key.eq_ignore_ascii_case(directive_key)
1054 && Self::values_match(&d.value, value)
1055 }) {
1056 block.directives.remove(pos);
1057 return true;
1058 }
1059 return false;
1060 }
1061 }
1062 }
1063 false
1064 }
1065
1066 /// Check if a host block has a specific forwarding directive.
1067 /// Uses whitespace-normalized value comparison and split_whitespace host matching.
1068 pub fn has_forward(&self, alias: &str, directive_key: &str, value: &str) -> bool {
1069 for element in &self.elements {
1070 if let ConfigElement::HostBlock(block) = element {
1071 if pattern_contains_token(&block.host_pattern, alias) {
1072 return block.directives.iter().any(|d| {
1073 !d.is_non_directive
1074 && d.key.eq_ignore_ascii_case(directive_key)
1075 && Self::values_match(&d.value, value)
1076 });
1077 }
1078 }
1079 }
1080 false
1081 }
1082
1083 /// Find tunnel directives for a host alias, searching all elements including
1084 /// Include files. Uses split_whitespace matching like has_host() for multi-pattern
1085 /// Host lines.
1086 pub fn find_tunnel_directives(&self, alias: &str) -> Vec<crate::tunnel::TunnelRule> {
1087 Self::find_tunnel_directives_in(&self.elements, alias)
1088 }
1089
1090 fn find_tunnel_directives_in(
1091 elements: &[ConfigElement],
1092 alias: &str,
1093 ) -> Vec<crate::tunnel::TunnelRule> {
1094 for element in elements {
1095 match element {
1096 ConfigElement::HostBlock(block) => {
1097 if pattern_contains_token(&block.host_pattern, alias) {
1098 return block.tunnel_directives();
1099 }
1100 }
1101 ConfigElement::Include(include) => {
1102 for file in &include.resolved_files {
1103 let rules = Self::find_tunnel_directives_in(&file.elements, alias);
1104 if !rules.is_empty() {
1105 return rules;
1106 }
1107 }
1108 }
1109 ConfigElement::GlobalLine(_) => {}
1110 }
1111 }
1112 Vec::new()
1113 }
1114
1115 /// Generate a unique alias by appending -2, -3, etc. if the base alias is taken.
1116 pub fn deduplicate_alias(&self, base: &str) -> String {
1117 self.deduplicate_alias_excluding(base, None)
1118 }
1119
1120 /// Generate a unique alias, optionally excluding one alias from collision detection.
1121 /// Used during rename so the host being renamed doesn't collide with itself.
1122 pub fn deduplicate_alias_excluding(&self, base: &str, exclude: Option<&str>) -> String {
1123 let is_taken = |alias: &str| {
1124 if exclude == Some(alias) {
1125 return false;
1126 }
1127 self.has_host(alias)
1128 };
1129 if !is_taken(base) {
1130 return base.to_string();
1131 }
1132 for n in 2..=9999 {
1133 let candidate = format!("{}-{}", base, n);
1134 if !is_taken(&candidate) {
1135 return candidate;
1136 }
1137 }
1138 // Practically unreachable: fall back to PID-based suffix
1139 format!("{}-{}", base, std::process::id())
1140 }
1141
1142 /// Set tags on a host block by alias.
1143 ///
1144 /// Refuses pattern aliases and multi-alias blocks symmetric with the
1145 /// vault/certificate setters: a tag on a shared block silently applies to
1146 /// every sibling alias, which is rarely the user's intent.
1147 #[must_use = "check the return value to detect silently-skipped mutations (renamed, deleted or shared-block hosts)"]
1148 pub fn set_host_tags(&mut self, alias: &str, tags: &[String]) -> bool {
1149 if alias.is_empty() || is_host_pattern(alias) {
1150 return false;
1151 }
1152 let Some(block) = self.find_host_block_mut(alias) else {
1153 return false;
1154 };
1155 if is_host_pattern(&block.host_pattern) {
1156 return false;
1157 }
1158 block.set_tags(tags);
1159 true
1160 }
1161
1162 /// Set provider-synced tags on a host block by alias.
1163 ///
1164 /// Same multi-alias and pattern refusal as the other purple-marker
1165 /// setters. Provider tags drive sync decisions, so a wrong-block mutation
1166 /// can cascade into delete/stale.
1167 #[must_use = "check the return value to detect silently-skipped mutations (renamed, deleted or shared-block hosts)"]
1168 pub fn set_host_provider_tags(&mut self, alias: &str, tags: &[String]) -> bool {
1169 if alias.is_empty() || is_host_pattern(alias) {
1170 return false;
1171 }
1172 let Some(block) = self.find_host_block_mut(alias) else {
1173 return false;
1174 };
1175 if is_host_pattern(&block.host_pattern) {
1176 return false;
1177 }
1178 block.set_provider_tags(tags);
1179 true
1180 }
1181
1182 /// Set askpass source on a host block by alias.
1183 ///
1184 /// Askpass is an authentication credential source; applying it to a
1185 /// sibling alias in a shared block would route the wrong credential.
1186 #[must_use = "check the return value to detect silently-skipped mutations (renamed, deleted or shared-block hosts)"]
1187 pub fn set_host_askpass(&mut self, alias: &str, source: &str) -> bool {
1188 if alias.is_empty() || is_host_pattern(alias) {
1189 return false;
1190 }
1191 let Some(block) = self.find_host_block_mut(alias) else {
1192 return false;
1193 };
1194 if is_host_pattern(&block.host_pattern) {
1195 return false;
1196 }
1197 block.set_askpass(source);
1198 true
1199 }
1200
1201 /// Set or remove the Vault SSH role comment on a host block by alias.
1202 /// Empty `role` removes the comment.
1203 ///
1204 /// Mirrors the safety invariants of `set_host_certificate_file` and
1205 /// `set_host_vault_addr`: wildcard aliases are refused so a `Host *.prod`
1206 /// pattern can never have a Vault role silently assigned to every host
1207 /// it resolves, and multi-alias blocks (`Host web-01 web-01.prod`) are
1208 /// refused so the role is never applied to sibling aliases the user did
1209 /// not authorise. Returns `true` on a successful mutation, `false` when
1210 /// the alias is invalid, missing, or lives in an Include file.
1211 ///
1212 /// Callers that run asynchronously (form submit handlers, sync workers)
1213 /// MUST check the return value so a silent config mutation failure is
1214 /// surfaced instead of pretending the role was wired up.
1215 #[must_use = "check the return value to detect silently-skipped mutations (renamed, deleted or shared-block hosts)"]
1216 pub fn set_host_vault_ssh(&mut self, alias: &str, role: &str) -> bool {
1217 if alias.is_empty() || is_host_pattern(alias) {
1218 return false;
1219 }
1220 let Some(block) = self.find_host_block_mut(alias) else {
1221 return false;
1222 };
1223 if is_host_pattern(&block.host_pattern) {
1224 return false;
1225 }
1226 block.set_vault_ssh(role);
1227 true
1228 }
1229
1230 /// Set or remove the Vault SSH endpoint comment on a host block by alias.
1231 /// Empty `url` removes the comment.
1232 ///
1233 /// Mirrors the safety invariants of `set_host_certificate_file`: wildcard
1234 /// aliases are refused to avoid accidentally applying a vault address to
1235 /// every host resolved through a pattern, and Match blocks are not
1236 /// touched (they live as inert `GlobalLines`). Returns `true` on a
1237 /// successful mutation, `false` when the alias is invalid or the block
1238 /// is not found.
1239 ///
1240 /// Callers that run asynchronously (e.g. form submit handlers that
1241 /// resolve the alias before writing) MUST check the return value so a
1242 /// silent config mutation failure is surfaced instead of pretending the
1243 /// vault address was wired up.
1244 #[must_use = "check the return value to detect silently-skipped mutations (renamed or deleted hosts)"]
1245 pub fn set_host_vault_addr(&mut self, alias: &str, url: &str) -> bool {
1246 // Same guard as `set_host_certificate_file`: refuse empty aliases
1247 // and any SSH pattern shape. `is_host_pattern` already covers
1248 // wildcards, negation and whitespace-separated multi-host forms.
1249 if alias.is_empty() || is_host_pattern(alias) {
1250 return false;
1251 }
1252 let Some(block) = self.find_host_block_mut(alias) else {
1253 return false;
1254 };
1255 // Defense in depth: refuse to mutate a block that is itself a
1256 // pattern or a multi-alias block (ExactAliasOnly policy). Writing a
1257 // vault endpoint onto such a block would apply to every sibling
1258 // alias and every host resolving through the pattern, which is
1259 // almost certainly not what the caller intends.
1260 if is_host_pattern(&block.host_pattern) {
1261 return false;
1262 }
1263 block.set_vault_addr(url);
1264 true
1265 }
1266
1267 /// Set or remove the CertificateFile directive on a host block by alias.
1268 /// Empty path removes the directive.
1269 /// Set the `CertificateFile` directive on the host block that matches
1270 /// `alias` exactly. Returns `true` if a matching block was found and
1271 /// updated, `false` if no top-level `HostBlock` matched (alias was
1272 /// renamed, deleted or lives only inside an `Include`d file).
1273 ///
1274 /// Only touches `CertificateFile` directives that are purple-managed
1275 /// (path contains `.purple/certs/`). User-set custom `CertificateFile`
1276 /// entries (e.g. a corporate or personal cert at `~/.ssh/corp-cert.pub`)
1277 /// are never modified or removed: empty-path clears only the purple
1278 /// managed line; non-empty path updates the purple-managed line in
1279 /// place or inserts a new one if absent. A host with both a corporate
1280 /// cert and a Vault-signed cert ends up with both lines present, in
1281 /// OpenSSH's documented cumulative semantics.
1282 ///
1283 /// Callers that run asynchronously (e.g. the Vault SSH bulk-sign worker)
1284 /// MUST check the return value so a silent config mutation failure is
1285 /// surfaced to the user instead of pretending the cert was wired up.
1286 #[must_use = "check the return value to detect silently-skipped mutations (renamed or deleted hosts)"]
1287 pub fn set_host_certificate_file(&mut self, alias: &str, path: &str) -> bool {
1288 // Defense in depth: refuse to mutate a host block when the requested
1289 // alias is empty or matches any SSH pattern shape (`*`, `?`, `[`,
1290 // leading `!`, or whitespace-separated multi-host form like
1291 // `Host web-* db-*`). Writing `CertificateFile` onto a pattern
1292 // block is almost never what a user intends and would affect every
1293 // host that resolves through that pattern. Reusing `is_host_pattern`
1294 // keeps this check in sync with the form-level pattern detection.
1295 if alias.is_empty() || is_host_pattern(alias) {
1296 return false;
1297 }
1298 let Some(block) = self.find_host_block_mut(alias) else {
1299 return false;
1300 };
1301 // Additionally refuse when the matched block is itself a pattern or
1302 // multi-alias block (ExactAliasOnly policy). The input `alias` may
1303 // be a plain token yet resolve into a block like `Host web-01
1304 // web-01.prod`, where writing `CertificateFile` would silently
1305 // affect sibling aliases.
1306 if is_host_pattern(&block.host_pattern) {
1307 return false;
1308 }
1309
1310 // Find the existing purple-managed CertificateFile entry, if any.
1311 let purple_pos = block.directives.iter().position(|d| {
1312 !d.is_non_directive
1313 && d.key.eq_ignore_ascii_case("CertificateFile")
1314 && is_purple_managed_cert_value(&d.value)
1315 });
1316
1317 if path.is_empty() {
1318 if let Some(pos) = purple_pos {
1319 block.directives.remove(pos);
1320 }
1321 return true;
1322 }
1323
1324 let sanitized = HostBlock::sanitize_raw_line_value(path);
1325 let indent = block.detect_indent();
1326 if let Some(pos) = purple_pos {
1327 let d = &mut block.directives[pos];
1328 if d.value != sanitized.as_ref() {
1329 d.value = sanitized.to_string();
1330 // Preserve separator style + inline comment in the same way
1331 // upsert_directive does for the single-line case.
1332 let trimmed = d.raw_line.trim_start();
1333 let after_key = &trimmed[d.key.len()..];
1334 let sep = if after_key.trim_start().starts_with('=') {
1335 let eq_pos = after_key.find('=').unwrap();
1336 let after_eq = &after_key[eq_pos + 1..];
1337 let trailing_ws = after_eq.len() - after_eq.trim_start().len();
1338 after_key[..eq_pos + 1 + trailing_ws].to_string()
1339 } else {
1340 " ".to_string()
1341 };
1342 let comment_suffix = Self::extract_inline_comment(&d.raw_line, &d.key);
1343 d.raw_line = format!("{}{}{}{}{}", indent, d.key, sep, sanitized, comment_suffix);
1344 }
1345 } else if is_purple_managed_cert_value(sanitized.as_ref()) {
1346 // Defensive gate: only insert a NEW CertificateFile line when
1347 // the caller's path is itself purple-managed. The rollback flow
1348 // in `app/hosts.rs` may pass `old_entry.certificate_file` which
1349 // could be a user-set custom path; inserting it here would
1350 // duplicate a user-managed entry. A non-purple-managed path
1351 // with no existing purple-managed line is a no-op.
1352 let pos = block.content_end();
1353 block.directives.insert(
1354 pos,
1355 Directive {
1356 key: "CertificateFile".to_string(),
1357 value: sanitized.to_string(),
1358 raw_line: format!("{}CertificateFile {}", indent, sanitized),
1359 is_non_directive: false,
1360 },
1361 );
1362 }
1363 true
1364 }
1365
1366 /// Set provider metadata on a host block by alias.
1367 ///
1368 /// Refuses pattern aliases and multi-alias blocks; same rationale as the
1369 /// other `# purple:*` setters.
1370 #[must_use = "check the return value to detect silently-skipped mutations (renamed, deleted or shared-block hosts)"]
1371 pub fn set_host_meta(&mut self, alias: &str, meta: &[(String, String)]) -> bool {
1372 if alias.is_empty() || is_host_pattern(alias) {
1373 return false;
1374 }
1375 let Some(block) = self.find_host_block_mut(alias) else {
1376 return false;
1377 };
1378 if is_host_pattern(&block.host_pattern) {
1379 return false;
1380 }
1381 block.set_meta(meta);
1382 true
1383 }
1384
1385 /// Mark a host as stale by alias.
1386 ///
1387 /// Stale markers drive the `X` purge flow which deletes the full block,
1388 /// so a wrong-block mutation here cascades into data loss for a sibling
1389 /// alias the user added by hand. Refuse pattern and multi-alias blocks.
1390 #[must_use = "check the return value to detect silently-skipped mutations (renamed, deleted or shared-block hosts)"]
1391 pub fn set_host_stale(&mut self, alias: &str, timestamp: u64) -> bool {
1392 if alias.is_empty() || is_host_pattern(alias) {
1393 return false;
1394 }
1395 let Some(block) = self.find_host_block_mut(alias) else {
1396 return false;
1397 };
1398 if is_host_pattern(&block.host_pattern) {
1399 return false;
1400 }
1401 block.set_stale(timestamp);
1402 true
1403 }
1404
1405 /// Clear stale marking from a host by alias.
1406 ///
1407 /// Symmetric guard with `set_host_stale`. Clearing on a shared block is
1408 /// benign but the asymmetry would be confusing; reject for consistency.
1409 #[must_use = "check the return value to detect silently-skipped mutations (renamed, deleted or shared-block hosts)"]
1410 pub fn clear_host_stale(&mut self, alias: &str) -> bool {
1411 if alias.is_empty() || is_host_pattern(alias) {
1412 return false;
1413 }
1414 let Some(block) = self.find_host_block_mut(alias) else {
1415 return false;
1416 };
1417 if is_host_pattern(&block.host_pattern) {
1418 return false;
1419 }
1420 block.clear_stale();
1421 true
1422 }
1423
1424 /// Collect all stale hosts with their timestamps.
1425 pub fn stale_hosts(&self) -> Vec<(String, u64)> {
1426 let mut result = Vec::new();
1427 for element in &self.elements {
1428 if let ConfigElement::HostBlock(block) = element {
1429 if let Some(ts) = block.stale() {
1430 result.push((block.host_pattern.clone(), ts));
1431 }
1432 }
1433 }
1434 result
1435 }
1436
1437 /// Delete a host entry by alias.
1438 ///
1439 /// For a single-alias block this removes the whole block (and cleans up
1440 /// any orphaned `# purple:group` header left behind). For a multi-alias
1441 /// block like `Host web-01 web-01.prod 10.0.1.5` only the matching
1442 /// alias token is stripped from the `Host` line; sibling aliases and
1443 /// all directives are preserved so that `delete_host("web-01.prod")`
1444 /// does not silently wipe configuration for `web-01` and `10.0.1.5`.
1445 ///
1446 /// Callers that want to remove the entire block regardless of sibling
1447 /// aliases should surface an explicit confirmation in the UI and then
1448 /// delete each sibling alias in turn.
1449 pub fn delete_host(&mut self, alias: &str) {
1450 // Two matching modes:
1451 // - Full-pattern match: block.host_pattern == alias. Removes the
1452 // entire block (plus duplicates). Used by the pattern browser,
1453 // where `alias` is a full pattern string like `web-* db-*` or
1454 // `web-01 web-01.prod`.
1455 // - Token match: alias appears as one of the whitespace-separated
1456 // tokens. Strips just that token from a multi-alias block and
1457 // removes single-alias blocks outright. Used by the host list.
1458 // Full-pattern is checked first so pattern-browser deletes never
1459 // degenerate into partial token strips.
1460 let has_full_match = self
1461 .elements
1462 .iter()
1463 .any(|e| matches!(e, ConfigElement::HostBlock(b) if b.host_pattern == alias));
1464
1465 // Capture the provider for orphaned-group cleanup before mutation.
1466 let provider_name = self.elements.iter().find_map(|e| match e {
1467 ConfigElement::HostBlock(b)
1468 if (has_full_match && b.host_pattern == alias)
1469 || (!has_full_match && pattern_contains_token(&b.host_pattern, alias)) =>
1470 {
1471 b.provider().map(|(name, _)| name)
1472 }
1473 _ => None,
1474 });
1475
1476 if has_full_match {
1477 // Harvest trailing comments (column-0 `#` lines or section
1478 // headers) from each block we're about to delete, so they
1479 // survive the delete and re-attach to whatever follows.
1480 // Skip `# purple:*` metadata — that's bookkeeping owned by the
1481 // block being removed.
1482 let mut salvaged_comments: Vec<String> = Vec::new();
1483 for el in &mut self.elements {
1484 if let ConfigElement::HostBlock(block) = el {
1485 if block.host_pattern == alias {
1486 let drain_from = {
1487 let mut idx = block.directives.len();
1488 while idx > 0 {
1489 let d = &block.directives[idx - 1];
1490 let is_user_comment = d.is_non_directive
1491 && (d.raw_line.trim().is_empty()
1492 || (d.raw_line.trim().starts_with('#')
1493 && !d.raw_line.trim().starts_with("# purple:")));
1494 if !is_user_comment {
1495 break;
1496 }
1497 idx -= 1;
1498 }
1499 idx
1500 };
1501 for d in block.directives.drain(drain_from..) {
1502 if !d.raw_line.trim().is_empty() {
1503 salvaged_comments.push(d.raw_line);
1504 }
1505 }
1506 }
1507 }
1508 }
1509 // Remove every block whose full host_pattern equals the input
1510 // (duplicate-block invariant preserved, matches pre-refactor).
1511 self.elements.retain(|e| match e {
1512 ConfigElement::HostBlock(block) => block.host_pattern != alias,
1513 _ => true,
1514 });
1515 // Re-emit salvaged comments as GlobalLines just before the next
1516 // remaining HostBlock, so a section-header lands above what
1517 // follows rather than vanishing with the preceding host.
1518 if !salvaged_comments.is_empty() {
1519 let next_host = self
1520 .elements
1521 .iter()
1522 .position(|e| matches!(e, ConfigElement::HostBlock(_)));
1523 let insert_pos = next_host.unwrap_or(self.elements.len());
1524 for (offset, raw) in salvaged_comments.into_iter().enumerate() {
1525 self.elements
1526 .insert(insert_pos + offset, ConfigElement::GlobalLine(raw));
1527 }
1528 }
1529 }
1530 // Always run the token-strip pass too. A config can contain BOTH a
1531 // full-pattern block (`Host web-01`) AND a sibling block that carries
1532 // the same alias as one token of a multi-alias pattern (`Host web-01
1533 // staging`). Without this second pass, `delete_host("web-01")` would
1534 // remove the first block, leave the second untouched, and `ssh web-01`
1535 // would silently re-route to staging's HostName. The strip is a no-op
1536 // when no token-only sibling exists.
1537 for el in &mut self.elements {
1538 if let ConfigElement::HostBlock(block) = el {
1539 let tokens: Vec<&str> = block.host_pattern.split_whitespace().collect();
1540 if tokens.len() > 1 && tokens.contains(&alias) {
1541 let new_pattern = tokens
1542 .iter()
1543 .filter(|t| **t != alias)
1544 .copied()
1545 .collect::<Vec<_>>()
1546 .join(" ");
1547 block.host_pattern = new_pattern.clone();
1548 block.raw_host_line = rebuild_host_line(&block.raw_host_line, &new_pattern);
1549 }
1550 }
1551 }
1552 self.elements.retain(|e| match e {
1553 ConfigElement::HostBlock(block) => {
1554 let mut tokens = block.host_pattern.split_whitespace();
1555 !matches!(
1556 (tokens.next(), tokens.next()),
1557 (Some(first), None) if first == alias
1558 )
1559 }
1560 _ => true,
1561 });
1562
1563 if let Some(name) = provider_name {
1564 self.remove_orphaned_group_header(&name);
1565 }
1566
1567 // Collapse consecutive blank lines left by deletion
1568 self.elements.dedup_by(|a, b| {
1569 matches!(
1570 (&*a, &*b),
1571 (ConfigElement::GlobalLine(x), ConfigElement::GlobalLine(y))
1572 if x.trim().is_empty() && y.trim().is_empty()
1573 )
1574 });
1575 }
1576
1577 /// Delete a host and return the removed element and its position for undo.
1578 /// Does NOT collapse blank lines or remove group headers so the position
1579 /// stays valid for re-insertion via `insert_host_at()`.
1580 /// Orphaned group headers (if any) are cleaned up at next startup.
1581 ///
1582 /// For multi-alias blocks this returns `None`: undoable-delete of a
1583 /// single alias out of a shared `Host` line cannot be round-tripped via
1584 /// `insert_host_at` because sibling aliases would be lost. Callers
1585 /// should fall back to `delete_host` in that case (which strips only
1586 /// the requested token).
1587 pub fn delete_host_undoable(&mut self, alias: &str) -> Option<(ConfigElement, usize)> {
1588 // Two-mode match mirroring `delete_host`: full-pattern first (for
1589 // pattern-browser deletes where `alias` is the whole pattern
1590 // string), then token match. Undoable delete is only safe when
1591 // removing the entire block; token-strip on a multi-alias block is
1592 // therefore refused (returns `None`) because re-inserting the
1593 // whole element would not reverse a token strip.
1594 let full_pos = self
1595 .elements
1596 .iter()
1597 .position(|e| matches!(e, ConfigElement::HostBlock(b) if b.host_pattern == alias));
1598 let pos = if let Some(p) = full_pos {
1599 p
1600 } else {
1601 let token_pos = self.elements.iter().position(|e| match e {
1602 ConfigElement::HostBlock(b) => pattern_contains_token(&b.host_pattern, alias),
1603 _ => false,
1604 })?;
1605 if let ConfigElement::HostBlock(b) = &self.elements[token_pos] {
1606 if b.host_pattern.split_whitespace().count() > 1 {
1607 return None;
1608 }
1609 }
1610 token_pos
1611 };
1612 let element = self.elements.remove(pos);
1613 Some((element, pos))
1614 }
1615
1616 /// Insert a host block at a specific position (for undo).
1617 pub fn insert_host_at(&mut self, element: ConfigElement, position: usize) {
1618 let pos = position.min(self.elements.len());
1619 self.elements.insert(pos, element);
1620 }
1621
1622 /// Find the position after the last HostBlock that belongs to a provider.
1623 /// Returns `None` if no hosts for this provider exist in the config.
1624 /// Used by the sync engine to insert new hosts adjacent to existing provider hosts.
1625 pub fn find_provider_insert_position(&self, provider_name: &str) -> Option<usize> {
1626 let mut last_pos = None;
1627 for (i, element) in self.elements.iter().enumerate() {
1628 if let ConfigElement::HostBlock(block) = element {
1629 if let Some((name, _)) = block.provider() {
1630 if name == provider_name {
1631 last_pos = Some(i);
1632 }
1633 }
1634 }
1635 }
1636 // Return position after the last provider host
1637 last_pos.map(|p| p + 1)
1638 }
1639
1640 /// Swap two host blocks in the config by alias. Returns true if swap was performed.
1641 #[allow(dead_code)]
1642 pub fn swap_hosts(&mut self, alias_a: &str, alias_b: &str) -> bool {
1643 let pos_a = self
1644 .elements
1645 .iter()
1646 .position(|e| matches!(e, ConfigElement::HostBlock(b) if b.host_pattern == alias_a));
1647 let pos_b = self
1648 .elements
1649 .iter()
1650 .position(|e| matches!(e, ConfigElement::HostBlock(b) if b.host_pattern == alias_b));
1651 if let (Some(a), Some(b)) = (pos_a, pos_b) {
1652 if a == b {
1653 return false;
1654 }
1655 let (first, second) = (a.min(b), a.max(b));
1656
1657 // Strip trailing blanks from both blocks before swap
1658 if let ConfigElement::HostBlock(block) = &mut self.elements[first] {
1659 block.pop_trailing_blanks();
1660 }
1661 if let ConfigElement::HostBlock(block) = &mut self.elements[second] {
1662 block.pop_trailing_blanks();
1663 }
1664
1665 // Swap
1666 self.elements.swap(first, second);
1667
1668 // Add trailing blank to first block (separator between the two)
1669 if let ConfigElement::HostBlock(block) = &mut self.elements[first] {
1670 block.ensure_trailing_blank();
1671 }
1672
1673 // Add trailing blank to second only if not the last element
1674 if second < self.elements.len() - 1 {
1675 if let ConfigElement::HostBlock(block) = &mut self.elements[second] {
1676 block.ensure_trailing_blank();
1677 }
1678 }
1679
1680 return true;
1681 }
1682 false
1683 }
1684
1685 /// Convert a HostEntry into a new HostBlock with clean formatting.
1686 ///
1687 /// Every value that ends up inside a `raw_line` is routed through
1688 /// `HostBlock::sanitize_raw_line_value`. A `\n` or `\r` in `alias`,
1689 /// `hostname`, `user`, `identity_file` or `proxy_jump` would otherwise
1690 /// split the rendered line and inject extra SSH config directives — for
1691 /// example a provider API returning `name = "evil\n ProxyJump bad"`
1692 /// would land as a real ProxyJump directive in the user's config. The
1693 /// previous `debug_assert!` guards were stripped from release builds,
1694 /// so the sanitiser is the only release-mode defence.
1695 pub(crate) fn entry_to_block(entry: &HostEntry) -> HostBlock {
1696 let alias = HostBlock::sanitize_raw_line_value(&entry.alias);
1697 let hostname = HostBlock::sanitize_raw_line_value(&entry.hostname);
1698 let user = HostBlock::sanitize_raw_line_value(&entry.user);
1699 let identity_file = HostBlock::sanitize_raw_line_value(&entry.identity_file);
1700 let proxy_jump = HostBlock::sanitize_raw_line_value(&entry.proxy_jump);
1701
1702 let mut directives = Vec::new();
1703
1704 if !hostname.is_empty() {
1705 directives.push(Directive {
1706 key: "HostName".to_string(),
1707 value: hostname.to_string(),
1708 raw_line: format!(" HostName {}", hostname),
1709 is_non_directive: false,
1710 });
1711 }
1712 if !user.is_empty() {
1713 directives.push(Directive {
1714 key: "User".to_string(),
1715 value: user.to_string(),
1716 raw_line: format!(" User {}", user),
1717 is_non_directive: false,
1718 });
1719 }
1720 if entry.port != 22 {
1721 directives.push(Directive {
1722 key: "Port".to_string(),
1723 value: entry.port.to_string(),
1724 raw_line: format!(" Port {}", entry.port),
1725 is_non_directive: false,
1726 });
1727 }
1728 if !identity_file.is_empty() {
1729 directives.push(Directive {
1730 key: "IdentityFile".to_string(),
1731 value: identity_file.to_string(),
1732 raw_line: format!(" IdentityFile {}", identity_file),
1733 is_non_directive: false,
1734 });
1735 }
1736 if !proxy_jump.is_empty() {
1737 directives.push(Directive {
1738 key: "ProxyJump".to_string(),
1739 value: proxy_jump.to_string(),
1740 raw_line: format!(" ProxyJump {}", proxy_jump),
1741 is_non_directive: false,
1742 });
1743 }
1744
1745 HostBlock {
1746 host_pattern: alias.to_string(),
1747 raw_host_line: format!("Host {}", alias),
1748 directives,
1749 }
1750 }
1751}
1752
1753/// Check whether `host_pattern` contains `alias` as one of its
1754/// whitespace-separated tokens, with quote-stripping. OpenSSH accepts
1755/// `Host "alpha"` as `Host alpha`; without quote-stripping the stored pattern
1756/// `"alpha"` (with literal quote characters) would never match the typed
1757/// alias `alpha`, leaving the block unreachable to the mutation API.
1758pub(super) fn pattern_contains_token(host_pattern: &str, alias: &str) -> bool {
1759 host_pattern.split_whitespace().any(|t| {
1760 let unquoted = if t.len() >= 2 && t.starts_with('"') && t.ends_with('"') {
1761 &t[1..t.len() - 1]
1762 } else {
1763 t
1764 };
1765 unquoted == alias
1766 })
1767}
1768
1769/// Rebuild a `Host` line with a new pattern, preserving the original line's
1770/// keyword form (`Host` vs `HOST`, with or without `=`), separator (space vs
1771/// tab) and trailing inline comment. Used by delete-token and rename paths
1772/// so that an unrelated edit on a multi-alias block never silently drops the
1773/// inline comment or tab style the user typed.
1774///
1775/// Falls back to `format!("Host {}", new_pattern)` when the original line
1776/// is too short or malformed to deconstruct.
1777pub(super) fn rebuild_host_line(original: &str, new_pattern: &str) -> String {
1778 // Find the position of the inline comment (if any). Inline comments on
1779 // SSH config lines start with a `#` preceded by whitespace, OUTSIDE any
1780 // quoted string. This mirrors `strip_inline_comment` in parser.rs.
1781 let (body, suffix) = {
1782 let bytes = original.as_bytes();
1783 let mut in_quote = false;
1784 let mut comment_start: Option<usize> = None;
1785 for i in 0..bytes.len() {
1786 if bytes[i] == b'"' {
1787 in_quote = !in_quote;
1788 } else if !in_quote
1789 && bytes[i] == b'#'
1790 && i > 0
1791 && (bytes[i - 1] == b' ' || bytes[i - 1] == b'\t')
1792 {
1793 comment_start = Some(i - 1); // include the leading whitespace
1794 break;
1795 }
1796 }
1797 match comment_start {
1798 Some(idx) => (
1799 original[..idx].trim_end_matches([' ', '\t']),
1800 &original[idx..],
1801 ),
1802 None => (original.trim_end_matches([' ', '\t']), ""),
1803 }
1804 };
1805
1806 // Split body into keyword + separator + (existing pattern, which we drop).
1807 // Accept tab or space and optional `=`, matching parse_host_line.
1808 let bytes = body.as_bytes();
1809 if bytes.len() < 5 || !bytes[..4].eq_ignore_ascii_case(b"host") {
1810 return format!("Host {}", new_pattern);
1811 }
1812 let sep = bytes[4];
1813 if !sep.is_ascii_whitespace() && sep != b'=' {
1814 return format!("Host {}", new_pattern);
1815 }
1816
1817 // Preserve the original keyword casing (`Host` vs `HOST` vs `host`).
1818 let keyword = &body[..4];
1819
1820 // Capture the original separator span between keyword and pattern so a
1821 // tab-separated `Host\tweb-01` stays tab-separated and `Host=foo` stays
1822 // equals-separated.
1823 let after_keyword = &body[4..];
1824 let pattern_start = after_keyword
1825 .char_indices()
1826 .find(|(_, c)| !c.is_whitespace() && *c != '=')
1827 .map(|(i, _)| i)
1828 .unwrap_or(after_keyword.len());
1829 let separator = &after_keyword[..pattern_start];
1830
1831 format!("{}{}{}{}", keyword, separator, new_pattern, suffix)
1832}
1833
1834#[cfg(test)]
1835#[path = "model_tests.rs"]
1836mod tests;