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