Skip to main content

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