From 278124f12d705b080f3831fb2c07cf66174b6a73 Mon Sep 17 00:00:00 2001 From: w33d Date: Mon, 26 Oct 2026 09:03:59 +0800 Subject: [PATCH] feat(ssh): manage known hosts in settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - crabport-ssh/known_hosts: expose list / remove / clear and the store path so the UI can manage the TOFU trust store. Mutations now share one process-wide lock — a connection's add and a settings delete are separate handles, and without it an add could read the file before the delete and write the entry back. - Settings: new Known Hosts tab with a search box (host / port / algorithm / fingerprint), per-entry forget behind a danger confirmation that shows the full fingerprint, forget-all, the trusted count, and the store path with an open-folder shortcut. Rows show host:port only, so a long fingerprint no longer truncates to SHA256:…. - The settings window hosts its own AlertController: it is a separate GPUI window, so the main window's alert host is out of reach. - i18n: English and Simplified Chinese strings for the new pane. --- crabport-ssh/src/known_hosts.rs | 152 ++++++- crabport-ui/i18n/en.toml | 22 + crabport-ui/i18n/zh-CN.toml | 22 + crabport-ui/src/windows/settings.rs | 49 ++- .../src/windows/settings/known_hosts.rs | 413 ++++++++++++++++++ 5 files changed, 651 insertions(+), 7 deletions(-) create mode 100644 crabport-ui/src/windows/settings/known_hosts.rs diff --git a/crabport-ssh/src/known_hosts.rs b/crabport-ssh/src/known_hosts.rs index b226721..e5e2e51 100644 --- a/crabport-ssh/src/known_hosts.rs +++ b/crabport-ssh/src/known_hosts.rs @@ -26,7 +26,8 @@ use std::collections::HashSet; use std::fs; use std::io::Write; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, MutexGuard}; /// A single known_hosts entry. #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -82,6 +83,23 @@ pub enum LookupResult { }, } +/// Serializes read-modify-write cycles across every handle in the process. +/// +/// Each SSH connection opens its own [`KnownHosts`] and the Settings window +/// opens another, so without this a concurrent TOFU `add` could read the file +/// before a `remove` rewrote it and then write the deleted entry back. The +/// lock is process-local — an external editor still races, which is why the +/// file keeps its "do not edit while the app is running" header. +static STORE_LOCK: Mutex<()> = Mutex::new(()); + +fn store_lock() -> MutexGuard<'static, ()> { + // A panic while holding the lock must not disable known_hosts for the + // rest of the process; the data is a plain file, so recovering is safe. + STORE_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + /// Persistent known_hosts store backed by a plain text file. pub struct KnownHosts { path: PathBuf, @@ -97,11 +115,22 @@ impl KnownHosts { }) } + /// Where [`Self::open`] stores the file, whether or not it exists yet. + /// Lets the UI show / reveal the path before the first host is trusted. + pub fn default_path() -> std::io::Result { + Ok(default_data_dir()?.join("known_hosts")) + } + /// Open at an explicit path (mainly for tests). pub fn open_at(path: PathBuf) -> Self { Self { path } } + /// The file backing this store. + pub fn path(&self) -> &Path { + &self.path + } + /// Read all entries currently in the file. fn read_all(&self) -> std::io::Result> { let mut set = HashSet::new(); @@ -158,11 +187,49 @@ impl KnownHosts { } } + /// Every stored entry, sorted by host, port and algorithm. + pub fn list(&self) -> std::io::Result> { + let mut entries: Vec = self.read_all()?.into_iter().collect(); + entries.sort_by(|a, b| { + a.host + .cmp(&b.host) + .then(a.port.cmp(&b.port)) + .then(a.algo.cmp(&b.algo)) + .then(a.fingerprint.cmp(&b.fingerprint)) + }); + Ok(entries) + } + /// Persist a new trusted entry. Rewrites the file atomically. pub fn add(&self, entry: &KnownHost) -> std::io::Result<()> { + let _guard = store_lock(); let mut all = self.read_all()?; all.insert(entry.clone()); + self.write_all(&all) + } + + /// Remove one trusted key. Returns `false` when it was not stored (the + /// caller may be looking at a stale snapshot). + pub fn remove(&self, entry: &KnownHost) -> std::io::Result { + let _guard = store_lock(); + let mut all = self.read_all()?; + if !all.remove(entry) { + return Ok(false); + } + self.write_all(&all)?; + Ok(true) + } + /// Forget every trusted key. Leaves the file in place (header only) so + /// the next connect starts from a clean TOFU state. + pub fn clear(&self) -> std::io::Result<()> { + let _guard = store_lock(); + self.write_all(&HashSet::new()) + } + + /// Atomically rewrite the store with `all`. Callers must hold + /// [`STORE_LOCK`]. + fn write_all(&self, all: &HashSet) -> std::io::Result<()> { if let Some(parent) = self.path.parent() { fs::create_dir_all(parent)?; } @@ -235,7 +302,8 @@ mod tests { // Unknown host:port → NotFound (ask the user). assert_eq!( - kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:aaa").unwrap(), + kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:aaa") + .unwrap(), LookupResult::NotFound ); @@ -243,12 +311,16 @@ mod tests { kh.add(&entry("example.com", 22, "ssh-ed25519", "SHA256:aaa")) .unwrap(); assert_eq!( - kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:aaa").unwrap(), + kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:aaa") + .unwrap(), LookupResult::Matched ); // Same host, different key → Mismatched with the stored expectation. - match kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:EVIL").unwrap() { + match kh + .lookup("example.com", 22, "ssh-ed25519", "SHA256:EVIL") + .unwrap() + { LookupResult::Mismatched { expected_algo, expected_fingerprint, @@ -261,7 +333,8 @@ mod tests { // Same host on a different port is a separate TOFU decision. assert_eq!( - kh.lookup("example.com", 2222, "ssh-ed25519", "SHA256:aaa").unwrap(), + kh.lookup("example.com", 2222, "ssh-ed25519", "SHA256:aaa") + .unwrap(), LookupResult::NotFound ); @@ -300,7 +373,8 @@ mod tests { let path = tmp_path("multi-algo"); let kh = KnownHosts::open_at(path.clone()); kh.add(&entry("h", 22, "ssh-ed25519", "SHA256:ed")).unwrap(); - kh.add(&entry("h", 22, "rsa-sha2-512", "SHA256:rsa")).unwrap(); + kh.add(&entry("h", 22, "rsa-sha2-512", "SHA256:rsa")) + .unwrap(); assert_eq!( kh.lookup("h", 22, "ssh-ed25519", "SHA256:ed").unwrap(), @@ -313,4 +387,70 @@ mod tests { let _ = fs::remove_file(&path); } + + #[test] + fn list_is_sorted_and_skips_malformed_lines() { + let path = tmp_path("list"); + let kh = KnownHosts::open_at(path.clone()); + kh.add(&entry("b.example", 22, "ssh-ed25519", "SHA256:b")) + .unwrap(); + kh.add(&entry("a.example", 2222, "ssh-rsa", "SHA256:a2")) + .unwrap(); + kh.add(&entry("a.example", 22, "ssh-rsa", "SHA256:a1")) + .unwrap(); + + // Junk lines (hand edits) don't reach the list. + let mut contents = fs::read_to_string(&path).unwrap(); + contents.push_str("not a known_hosts line\n\n"); + fs::write(&path, contents).unwrap(); + + let listed = kh.list().unwrap(); + let targets: Vec<(&str, u16)> = listed.iter().map(|e| (e.host.as_str(), e.port)).collect(); + assert_eq!( + targets, + vec![("a.example", 22), ("a.example", 2222), ("b.example", 22),] + ); + assert_eq!(kh.path(), path.as_path()); + + let _ = fs::remove_file(&path); + } + + #[test] + fn remove_deletes_one_entry_and_clear_empties_the_store() { + let path = tmp_path("remove-clear"); + let kh = KnownHosts::open_at(path.clone()); + let ed = entry("h", 22, "ssh-ed25519", "SHA256:ed"); + let rsa = entry("h", 22, "ssh-rsa", "SHA256:rsa"); + kh.add(&ed).unwrap(); + kh.add(&rsa).unwrap(); + + // Removing one key leaves the host's other algorithm trusted. + assert!(kh.remove(&ed).unwrap()); + assert_eq!( + kh.lookup("h", 22, "ssh-rsa", "SHA256:rsa").unwrap(), + LookupResult::Matched + ); + assert_eq!( + kh.lookup("h", 22, "ssh-ed25519", "SHA256:ed").unwrap(), + LookupResult::Mismatched { + expected_algo: "ssh-rsa".into(), + expected_fingerprint: "SHA256:rsa".into(), + } + ); + // Removing an entry that isn't stored is a no-op, not an error. + assert!(!kh.remove(&ed).unwrap()); + + kh.clear().unwrap(); + assert!(kh.list().unwrap().is_empty()); + assert_eq!( + kh.lookup("h", 22, "ssh-rsa", "SHA256:rsa").unwrap(), + LookupResult::NotFound + ); + // The file survives with its header so the store stays discoverable. + let contents = fs::read_to_string(&path).unwrap(); + assert_eq!(contents.lines().count(), 1); + assert!(contents.starts_with('#')); + + let _ = fs::remove_file(&path); + } } diff --git a/crabport-ui/i18n/en.toml b/crabport-ui/i18n/en.toml index 662fb49..8e2d0da 100644 --- a/crabport-ui/i18n/en.toml +++ b/crabport-ui/i18n/en.toml @@ -416,6 +416,7 @@ general = "General" appearance = "Appearance" keybinds = "Keybinds" connection = "Connection" +known_hosts = "Known Hosts" panels = "Panels" ai = "AI" @@ -578,6 +579,27 @@ desc = "Keepalive probes keep idle sessions from being dropped by NAT and firewa keepalive = "Keepalive interval (s)" auto_reconnect = "Auto-reconnect on drop" +[window.settings.known_hosts] +section = "Known Hosts" +desc = "SSH host keys you trusted on first connect. Forgetting a key makes CrabPort ask you to verify that host again the next time you connect." +file = "File" +open_folder = "Open Folder" +search_placeholder = "Search host, key type or fingerprint" +count = "Trusted keys: %{count}" +empty = "No hosts trusted yet" +no_matches = "No hosts match your search" +forget_all = "Forget All" +delete_title = "Forget host key" +delete_desc = "CrabPort will ask you to verify %{host} again on the next connection." +detail_host = "Host" +detail_type = "Key type" +detail_fingerprint = "Fingerprint" +delete_confirm = "Forget" +clear_title = "Forget all known hosts" +clear_desc = "Every trusted host key will be deleted. You will be asked to verify each host again on the next connection." +clear_confirm = "Forget All" +error = "Could not update known hosts: %{error}" + [window.settings.appearance] section_language = "Language" language_en = "English" diff --git a/crabport-ui/i18n/zh-CN.toml b/crabport-ui/i18n/zh-CN.toml index a0dc17f..2888486 100644 --- a/crabport-ui/i18n/zh-CN.toml +++ b/crabport-ui/i18n/zh-CN.toml @@ -415,6 +415,7 @@ general = "通用" appearance = "外观" keybinds = "快捷键" connection = "连接" +known_hosts = "已知主机" panels = "面板" ai = "AI" @@ -579,6 +580,27 @@ desc = "心跳探测避免空闲会话被 NAT / 防火墙超时断开;断线 keepalive = "心跳间隔 (秒)" auto_reconnect = "断线自动重连" +[window.settings.known_hosts] +section = "已知主机" +desc = "首次连接时信任的 SSH 主机密钥。删除某个密钥后,下次连接该主机时会重新要求你确认。" +file = "文件" +open_folder = "打开文件夹" +search_placeholder = "搜索主机、密钥类型或指纹" +count = "已信任密钥:%{count} 个" +empty = "还没有信任任何主机" +no_matches = "没有匹配的主机" +forget_all = "全部删除" +delete_title = "删除主机密钥" +delete_desc = "下次连接 %{host} 时将重新要求你确认。" +detail_host = "主机" +detail_type = "密钥类型" +detail_fingerprint = "指纹" +delete_confirm = "删除" +clear_title = "删除所有已知主机" +clear_desc = "所有已信任的主机密钥都将被删除,下次连接每个主机时都需要重新确认。" +clear_confirm = "全部删除" +error = "更新已知主机失败:%{error}" + [window.settings.appearance] section_language = "语言" language_en = "English" diff --git a/crabport-ui/src/windows/settings.rs b/crabport-ui/src/windows/settings.rs index bc1b74f..6dfbcb0 100644 --- a/crabport-ui/src/windows/settings.rs +++ b/crabport-ui/src/windows/settings.rs @@ -9,6 +9,8 @@ //! //! Sections are built declaratively via [`crate::windows::settings_section::Section`]. +mod known_hosts; + use gpui::prelude::FluentBuilder; use gpui::*; use gpui_component::input::{InputEvent, InputState}; @@ -24,6 +26,7 @@ use crate::ai::PROVIDER_TYPES; use crate::app_state::AppState; use crate::color::*; use crate::components::button::Button; +use crate::components::dialog::AlertController; use crate::components::dropdown::Dropdown; use crate::components::input::StyledInput; use crate::components::number_input::{StyledNumberInput, subscribe_number_filter}; @@ -47,16 +50,19 @@ pub enum SettingsTab { Panels, /// Session liveness: keepalive probes and auto-reconnect. Connection, + /// Trusted SSH host keys (the TOFU store). + KnownHosts, Keybinds, Ai, } impl SettingsTab { - const ALL: [SettingsTab; 6] = [ + const ALL: [SettingsTab; 7] = [ SettingsTab::General, SettingsTab::Appearance, SettingsTab::Panels, SettingsTab::Connection, + SettingsTab::KnownHosts, SettingsTab::Keybinds, SettingsTab::Ai, ]; @@ -67,6 +73,7 @@ impl SettingsTab { SettingsTab::Appearance => t!("window.settings.tab.appearance").into(), SettingsTab::Panels => t!("window.settings.tab.panels").into(), SettingsTab::Connection => t!("window.settings.tab.connection").into(), + SettingsTab::KnownHosts => t!("window.settings.tab.known_hosts").into(), SettingsTab::Keybinds => t!("window.settings.tab.keybinds").into(), SettingsTab::Ai => t!("window.settings.tab.ai").into(), } @@ -295,6 +302,19 @@ pub struct SettingsWindow { /// Error message for the action currently being recorded, if any /// (e.g. conflict with another binding). keybind_error: Option, + /// Search box backing the Known Hosts pane (filters by host, algorithm + /// and fingerprint). + known_hosts_search: Entity, + /// Current Known Hosts search text, mirrored from the input's `Change` + /// events so rendering doesn't have to read the input entity. + known_hosts_query: String, + /// Last failed known_hosts mutation, shown in the Known Hosts pane until + /// the next successful one. + known_hosts_error: Option, + /// Alert host for the Known Hosts pane's destructive confirmations. The + /// settings window is its own GPUI window, so it can't reuse the main + /// window's `AlertController`. + alert_controller: Entity, } /// Input entities for one AI provider entry, matched to its @@ -383,6 +403,24 @@ impl SettingsWindow { cx.refresh_windows(); }) .detach(); + // Known Hosts pane: search box + the alert host for its destructive + // confirmations. The main window's alert controller lives in the + // other window, so this one needs its own. + let known_hosts_search = cx.new(|cx| { + InputState::new(window, cx) + .placeholder(t!("window.settings.known_hosts.search_placeholder").to_string()) + }); + cx.subscribe( + &known_hosts_search, + |this, input, event: &InputEvent, cx| { + if let InputEvent::Change = event { + this.known_hosts_query = input.read(cx).value().to_string(); + cx.notify(); + } + }, + ) + .detach(); + let alert_controller = cx.new(|_cx| AlertController::new()); // AI provider entries — one input triple per configured endpoint, // built from the persisted config so the pane opens pre-filled. let ai_entry_inputs: Vec = config::snapshot() @@ -415,6 +453,10 @@ impl SettingsWindow { recording_action: None, focus_handle: cx.focus_handle(), keybind_error: None, + known_hosts_search, + known_hosts_query: String::new(), + known_hosts_error: None, + alert_controller, } } @@ -1802,6 +1844,7 @@ impl Render for SettingsWindow { SettingsTab::Appearance => self.render_appearance_pane(cx).into_any_element(), SettingsTab::Panels => self.render_panels_pane(cx).into_any_element(), SettingsTab::Connection => self.render_connection_pane(cx).into_any_element(), + SettingsTab::KnownHosts => self.render_known_hosts_pane(cx).into_any_element(), // The AI tab is either its landing page or one of its // second-level pages. SettingsTab::Ai => match self.ai_sub_page { @@ -1840,6 +1883,10 @@ impl Render for SettingsWindow { ) .id("settings-root") .track_focus(&self.focus_handle) + // The Known Hosts pane's confirmation dialogs live inside this + // window; the controller positions itself absolutely, so it overlays + // the sidebar + content without taking part in the flex layout. + .child(self.alert_controller.clone()) // Intercept key presses while recording a keybind. .when(self.recording_action.is_some(), |el| { el.on_key_down(cx.listener(Self::on_key_recording)) diff --git a/crabport-ui/src/windows/settings/known_hosts.rs b/crabport-ui/src/windows/settings/known_hosts.rs new file mode 100644 index 0000000..6e55a63 --- /dev/null +++ b/crabport-ui/src/windows/settings/known_hosts.rs @@ -0,0 +1,413 @@ +//! Known-hosts settings pane: inspect and forget trusted SSH host keys. +//! +//! The store itself lives in `crabport-ssh` (`crabport_ssh::known_hosts`); +//! this pane only renders it and routes destructive actions through the +//! settings window's own `AlertController`. Entries are re-read on every +//! render — the file is tiny, and a terminal tab can trust a new key while +//! this window is open, so a cached copy would go stale. + +use std::rc::Rc; + +use gpui::prelude::FluentBuilder; +use gpui::*; +use rust_i18n::t; + +use crabport_ssh::known_hosts::{KnownHost, KnownHosts}; + +use crate::color::*; +use crate::components::button::Button; +use crate::components::dialog::{AlertSeverity, AlertState}; +use crate::components::input::StyledInput; +use crate::components::settings_section::Section; +use crate::motion::RADIUS_MD; + +use super::{SettingsWindow, open_path}; + +/// Fixed row height for the single-line entry rows. +const ROW_HEIGHT: f32 = 40.0; + +impl SettingsWindow { + /// The Known Hosts pane: a searchable list of the TOFU trust store. + pub(super) fn render_known_hosts_pane(&self, cx: &mut Context) -> impl IntoElement { + let handle = cx.entity().clone(); + + // Read the store fresh on each render. `open` failure is reported in + // the pane rather than hidden: it usually means the data directory + // isn't writable, which the user can act on. + let (path, entries, load_error) = match KnownHosts::open() { + Ok(store) => { + let path = store.path().display().to_string(); + match store.list() { + Ok(entries) => (path, entries, None), + Err(e) => (path, Vec::new(), Some(e.to_string())), + } + } + Err(e) => ( + KnownHosts::default_path() + .map(|p| p.display().to_string()) + .unwrap_or_default(), + Vec::new(), + Some(e.to_string()), + ), + }; + let total = entries.len(); + + let query = self.known_hosts_query.trim().to_lowercase(); + let rows: Vec = entries + .into_iter() + .filter(|e| matches_query(e, &query)) + .collect(); + let is_empty = rows.is_empty(); + + let list_rows: Vec = rows + .into_iter() + .enumerate() + .map(|(i, entry)| { + let copy_value = entry.fingerprint.clone(); + let copy_btn = Button::new(ElementId::Name(format!("known-hosts-copy-{i}").into())) + .ghost() + .icon("icons/copy.svg") + .w_auto() + .h_7() + .px_2() + .on_click(move |_e, _w, cx| { + cx.write_to_clipboard(ClipboardItem::new_string(copy_value.clone())); + }); + + let target = entry.clone(); + let alert = self.alert_controller.clone(); + let handle_for_confirm = handle.clone(); + let forget_btn = + Button::new(ElementId::Name(format!("known-hosts-forget-{i}").into())) + .ghost() + .icon("icons/trash.svg") + .w_auto() + .h_7() + .px_2() + .on_click(move |_e, _w, cx| { + let target = target.clone(); + let handle_for_confirm = handle_for_confirm.clone(); + alert.update(cx, |controller, cx| { + let target_label = format!("{}:{}", target.host, target.port); + controller.show( + AlertState { + severity: AlertSeverity::Danger, + title: t!("window.settings.known_hosts.delete_title") + .to_string() + .into(), + description: Some( + t!( + "window.settings.known_hosts.delete_desc", + host = target_label.as_str() + ) + .to_string() + .into(), + ), + details: vec![ + ( + t!("window.settings.known_hosts.detail_host") + .to_string() + .into(), + target_label.into(), + ), + ( + t!("window.settings.known_hosts.detail_type") + .to_string() + .into(), + target.algo.clone().into(), + ), + ( + t!( + "window.settings.known_hosts.detail_fingerprint" + ) + .to_string() + .into(), + target.fingerprint.clone().into(), + ), + ], + confirm_label: t!( + "window.settings.known_hosts.delete_confirm" + ) + .to_string() + .into(), + cancel_label: t!("terminal.host_key_cancel") + .to_string() + .into(), + on_confirm: Some(Rc::new(move |_w, cx| { + let result = + KnownHosts::open().and_then(|s| s.remove(&target)); + let error = result.err().map(|e| e.to_string()); + handle_for_confirm.update(cx, |view, cx| { + view.known_hosts_error = error; + cx.notify(); + }); + })), + ..AlertState::default() + }, + cx, + ); + }); + }); + + known_host_row(i, &entry, copy_btn, forget_btn).into_any_element() + }) + .collect(); + + // ---- Forget-all button (confirmation alert, then wipe) ---- + let alert = self.alert_controller.clone(); + let handle_for_confirm = handle.clone(); + let clear_btn = Button::new("known-hosts-clear") + .ghost() + .icon("icons/trash.svg") + .w_auto() + .px_2() + .child(t!("window.settings.known_hosts.forget_all").to_string()) + .on_click(move |_e, _w, cx| { + let handle_for_confirm = handle_for_confirm.clone(); + alert.update(cx, |controller, cx| { + controller.show( + AlertState { + severity: AlertSeverity::Danger, + title: t!("window.settings.known_hosts.clear_title") + .to_string() + .into(), + description: Some( + t!("window.settings.known_hosts.clear_desc") + .to_string() + .into(), + ), + confirm_label: t!("window.settings.known_hosts.clear_confirm") + .to_string() + .into(), + cancel_label: t!("terminal.host_key_cancel").to_string().into(), + on_confirm: Some(Rc::new(move |_w, cx| { + let result = KnownHosts::open().and_then(|s| s.clear()); + let error = result.err().map(|e| e.to_string()); + handle_for_confirm.update(cx, |view, cx| { + view.known_hosts_error = error; + cx.notify(); + }); + })), + ..AlertState::default() + }, + cx, + ); + }); + }); + + let folder = std::path::Path::new(&path) + .parent() + .map(|p| p.to_path_buf()); + let reveal_btn = Button::action( + "known-hosts-open-folder", + t!("window.settings.known_hosts.open_folder").to_string(), + ) + .on_click(move |_e, _w, cx| { + if let Some(folder) = folder.as_ref() { + let _ = open_path(folder, cx); + } + }); + + let error = load_error.or_else(|| self.known_hosts_error.clone()); + + div() + .size_full() + .flex() + .flex_col() + .p_6() + .gap_4() + .child( + Section::new() + .header(t!("window.settings.known_hosts.section")) + .desc(t!("window.settings.known_hosts.desc")) + // A bare, full-width row so the path truncates instead of + // forcing the pane wider on a narrow window (the same + // reason the General pane's data-dir row is bare). + .bare( + div() + .w_full() + .flex() + .flex_row() + .items_center() + .gap_3() + .child( + div() + .flex_shrink_0() + .text_xs() + .text_color(rgb(text_muted())) + .child(t!("window.settings.known_hosts.file").to_string()), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_xs() + .text_color(rgb(text_muted())) + .child(path.clone()), + ) + .child(reveal_btn), + ), + ) + .child( + // Search + count + forget all, on one line. + div() + .flex() + .flex_row() + .items_center() + .gap_2() + .child( + div().flex_1().min_w_0().child( + StyledInput::new("known-hosts-search", self.known_hosts_search.clone()) + .xsmall() + .prefix( + svg() + .path("icons/search.svg") + .size(px(12.0)) + .text_color(rgb(text_muted())), + ), + ), + ) + .when(total > 0, |el| { + el.child( + div() + .flex_shrink_0() + .text_xs() + .text_color(rgb(text_muted())) + .child( + t!("window.settings.known_hosts.count", count = total) + .to_string(), + ), + ) + }) + .when(total > 0, |el| el.child(clear_btn)), + ) + .when_some(error, |el, error| { + el.child(div().text_xs().text_color(rgb(term_red())).child( + t!("window.settings.known_hosts.error", error = error.as_str()).to_string(), + )) + }) + .child( + div() + .id("known-hosts-list") + .flex_1() + .min_h_0() + .overflow_y_scroll() + .rounded(RADIUS_MD) + .border_1() + .border_color(rgb(border())) + .bg(rgb(bg_base())) + .when_else( + is_empty, + |el| { + el.flex() + .flex_col() + .items_center() + .justify_center() + .gap_2() + .child( + svg() + .path("icons/key.svg") + .size_4() + .text_color(rgb(text_muted())) + .opacity(0.5), + ) + .child(div().text_sm().text_color(rgb(text_muted())).child( + if total == 0 { + t!("window.settings.known_hosts.empty").to_string() + } else { + t!("window.settings.known_hosts.no_matches").to_string() + }, + )) + }, + |el| el.flex().flex_col().children(list_rows), + ), + ) + } +} + +/// Case-insensitive search over everything the row shows. `query` must +/// already be trimmed and lowercased by the caller; an empty query matches +/// every entry. +fn matches_query(entry: &KnownHost, query: &str) -> bool { + query.is_empty() + || entry.host.to_lowercase().contains(query) + || entry.port.to_string().contains(query) + || entry.algo.to_lowercase().contains(query) + || entry.fingerprint.to_lowercase().contains(query) +} + +/// One fixed-height entry row: key icon, `host:port`, then the copy / +/// forget actions. The key type and fingerprint stay out of the list (they +/// are shown in the forget confirmation) so long fingerprints don't +/// truncate into an unreadable `SHA256:…`. +fn known_host_row( + index: usize, + entry: &KnownHost, + copy_btn: Button, + forget_btn: Button, +) -> impl IntoElement { + div() + .id(ElementId::Name(format!("known-hosts-row-{index}").into())) + .h(px(ROW_HEIGHT)) + .w_full() + .flex() + .flex_row() + .items_center() + .gap_3() + .px_3() + .when(index > 0, |el| { + // Extra vertical breathing room between entries; the hairline + // still marks where one record ends and the next begins. + el.mt_2().border_t_1().border_color(rgb(border())) + }) + .child( + svg() + .path("icons/key.svg") + .size_4() + .flex_shrink_0() + .text_color(rgb(text_muted())), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_sm() + .text_color(rgb(text_primary())) + .child(format!("{}:{}", entry.host, entry.port)), + ) + .child(copy_btn) + .child(forget_btn) +} + +#[cfg(test)] +mod tests { + // Deliberately not `use super::*`: this module's parent glob-imports + // `gpui::*`, which brings in gpui's own `test` attribute macro and makes + // the built-in `#[test]` expand recursively. + use super::matches_query; + use crabport_ssh::known_hosts::KnownHost; + + fn entry(host: &str, port: u16, algo: &str, fingerprint: &str) -> KnownHost { + KnownHost { + host: host.into(), + port, + algo: algo.into(), + fingerprint: fingerprint.into(), + } + } + + #[test] + fn search_matches_host_port_algo_and_fingerprint() { + let e = entry("Example.COM", 2222, "ssh-ed25519", "SHA256:AbC123"); + + assert!(matches_query(&e, "")); + assert!(matches_query(&e, "example")); + assert!(matches_query(&e, "2222")); + assert!(matches_query(&e, "ed25519")); + assert!(matches_query(&e, "abc123")); + assert!(!matches_query(&e, "example.com:22")); + assert!(!matches_query(&e, "missing")); + } +}