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